:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): split posthog/models/integration.py into a package (#85309)
Julian Bez4c9e93bad6d3
diff --git a/AGENTS.md b/AGENTS.mdindex feb00922e806..ed834aeea755 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -216,7 +216,7 @@ See [.agents/security.md](.agents/security.md) for security guidelines — least- Comments: never log change history or chat context in code — no "previously did X, now does Y", "per <task/PR>", "changed because…", or "AI:"/"agent:" notes. That goes in the commit message and PR description- Comments: when refactoring or moving code, preserve existing comments unless they are explicitly made obsolete by the change- Python tests: do not add doc comments-- Python: do not create empty `__init__.py` files, with one exception: the package markers import tooling needs — `products/`, every product's `backend/`, and their `facade/` and `presentation/` trees. `products/` carries one so file-based mypy resolves `products.<name>.backend` rather than `<name>.backend`; that makes it a regular package, and grimp then stops descending at the first directory without a marker, silently dropping everything below it from every import-linter contract. `hogli product:lint` enforces those markers. Everywhere else — test directories, generated trees — leave the file out+- Python: do not create empty `__init__.py` files, with two exceptions, both cases where a missing marker breaks tooling silently. (1) The package markers import tooling needs — `products/`, every product's `backend/`, and their `facade/` and `presentation/` trees. `products/` carries one so file-based mypy resolves `products.<name>.backend` rather than `<name>.backend`; that makes it a regular package, and grimp then stops descending at the first directory without a marker, silently dropping everything below it from every import-linter contract. `hogli product:lint` enforces those markers. (2) A test directory whose parent directory already has an `__init__.py`. Under pytest's default `prepend` import mode a test module is named by walking up from its file while `__init__.py` exists, so a subdirectory that skips the marker gets bare basenames — `test_github`, `test_jira`, `test_oauth` — and any same-named file elsewhere in the repo becomes uncollectable with `import file mismatch`. The directory collected first wins and the other file drops out of the run entirely, so the cost lands on someone else's tests. CI does not catch it, because the Core backend lane collects `posthog`/`ee` while `products/*` run under separate turbo lanes and no single session spans both trees. Adding the marker fixes every basename in that directory at once, including future ones; renaming the colliding modules does not. Check a new test package with `pytest --collect-only <new-dir> <dir-holding-the-same-basenames>`. Everywhere else — test directories under a parent that is not a package, generated trees — leave the file out- jest tests: when writing jest tests, prefer a single top-level describe block in a file- Tests: prefer parameterized tests (use the `parameterized` library in Python) — if you're writing multiple assertions for variations of the same logic, it should be parameterized- Tests must earn their place: every new test has to catch a realistic regression no existing test already catches (if you can't name it, don't add it), assert observable behavior through the public interface rather than implementation details, and stay cheap — deterministic, isolated, and at the lowest level that catches the bug (see `/writing-tests`)diff --git a/posthog/api/test/test_github_installation_webhook.py b/posthog/api/test/test_github_installation_webhook.pyindex c36c079ffdef..4f7da9825bb1 100644--- a/posthog/api/test/test_github_installation_webhook.py+++ b/posthog/api/test/test_github_installation_webhook.py@@ -95,13 +95,13 @@ class TestGitHubInstallationReferenceHelpers(TestCase):def test_uninstall_app_installation_false_when_not_configured(self):self.assertFalse(GitHubIntegration.uninstall_app_installation("12345"))- @patch("posthog.models.integration.GitHubIntegration.uninstall_app_installation")+ @patch("posthog.models.integration.github.GitHubIntegration.uninstall_app_installation")def test_uninstall_if_last_reference_skips_when_references_remain(self, mock_uninstall):self._team_integration()self.assertFalse(GitHubIntegration.uninstall_if_last_reference("12345"))mock_uninstall.assert_not_called()- @patch("posthog.models.integration.GitHubIntegration.uninstall_app_installation")+ @patch("posthog.models.integration.github.GitHubIntegration.uninstall_app_installation")def test_uninstall_if_last_reference_uninstalls_when_none_remain(self, mock_uninstall):mock_uninstall.return_value = Trueself.assertTrue(GitHubIntegration.uninstall_if_last_reference("12345"))diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex ba49f212c526..a5d55926abcb 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -81,7 +81,7 @@ class TestSlackIntegration:sensitive_config={"access_token": "test-token-123"},)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_list_channels_with_access(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -124,7 +124,7 @@ class TestSlackIntegration:assert channels[3]["id"] == "CP123"assert channels[3]["name"] == "d_private_channel"- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_list_channels_without_access(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -168,7 +168,7 @@ class TestSlackIntegration:assert channels[0]["name"] == PRIVATE_CHANNEL_WITHOUT_ACCESSassert channels[0]["is_private_without_access"]- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_get_channel_by_id_private_with_access(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -191,7 +191,7 @@ class TestSlackIntegration:assert channel["is_private"]assert not channel["is_private_without_access"]- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_get_channel_by_id_private_without_access(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -214,7 +214,7 @@ class TestSlackIntegration:assert channel["is_private"]assert channel["is_private_without_access"]- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_get_channel_by_id_public_with_access(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -237,7 +237,7 @@ class TestSlackIntegration:assert not channel["is_private"]assert not channel["is_private_without_access"]- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_get_channel_by_id_public_without_access(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -304,7 +304,7 @@ class TestEmailIntegration:self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")- @patch("posthog.models.integration.SESProvider")+ @patch("posthog.models.integration.email.SESProvider")def test_integration_from_domain(self, mock_ses_provider_class):mock_client = MagicMock()mock_ses_provider_class.return_value = mock_client@@ -336,7 +336,7 @@ class TestEmailIntegration:org_team_ids=[self.team.id],)- @patch("posthog.models.integration.SESProvider")+ @patch("posthog.models.integration.email.SESProvider")def test_email_verify_returns_ses_result(self, mock_ses_provider_class):mock_client = MagicMock()mock_ses_provider_class.return_value = mock_client@@ -395,7 +395,7 @@ class TestEmailIntegration:"provider": "ses",}- @patch("posthog.models.integration.SESProvider")+ @patch("posthog.models.integration.email.SESProvider")def test_email_verify_updates_integration(self, mock_ses_provider_class):mock_client = MagicMock()mock_ses_provider_class.return_value = mock_client@@ -432,7 +432,7 @@ class TestEmailIntegration:"provider": "ses",}- @patch("posthog.models.integration.SESProvider")+ @patch("posthog.models.integration.email.SESProvider")def test_email_verify_updates_all_other_integrations_with_same_domain(self, mock_ses_provider_class, settings):settings.SES_ACCESS_KEY_ID = "test_access_key"settings.SES_SECRET_ACCESS_KEY = "test_secret_key"@@ -496,7 +496,7 @@ class TestDatabricksIntegration:self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN)- @patch("posthog.models.integration.is_url_allowed", return_value=(True, None))+ @patch("posthog.models.integration.databricks.is_url_allowed", return_value=(True, None))def test_integration_from_config_with_valid_config(self,mock_is_url_allowed,@@ -635,7 +635,7 @@ class TestAWSIntegration:)self.integration_kind = aws_integration_kind- @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")+ @patch("posthog.models.integration.aws.validate_aws_credentials", return_value="123456789012")def test_create_with_valid_config(self, mock_validate, client: HttpClient):client.force_login(self.user)@@ -671,7 +671,7 @@ class TestAWSIntegration:assert "aws_secret_access_key" not in response_bodyassert "AKIAEXAMPLE" not in response_body- @patch("posthog.models.integration.validate_aws_credentials")+ @patch("posthog.models.integration.aws.validate_aws_credentials")def test_create_rejects_invalid_credentials(self, mock_validate, client: HttpClient):from posthog.models.integration import IntegrationError@@ -694,7 +694,7 @@ class TestAWSIntegration:assert response.status_code == status.HTTP_400_BAD_REQUESTassert "AWS credentials are not valid" in response.json()["detail"]- @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")+ @patch("posthog.models.integration.aws.validate_aws_credentials", return_value="123456789012")def test_create_rejects_duplicate_name(self, mock_validate, client: HttpClient):client.force_login(self.user)payload = {@@ -1194,14 +1194,24 @@ class TestIntegrationAPIKeyAccess:assert response.json()["kind"] == "twilio"@patch(- "posthog.models.integration.get_instance_settings",+ "posthog.models.integration.oauth.get_instance_settings",return_value={"SLACK_APP_CLIENT_ID": "test-client-id","SLACK_APP_CLIENT_SECRET": "test-client-secret","SLACK_APP_SIGNING_SECRET": "test-signing-secret",},)- def test_retrieve_slack_integration_with_scope_succeeds(self, _mock_settings, client: HttpClient):+ @patch(+ "posthog.models.integration.slack.get_instance_settings",+ return_value={+ "SLACK_APP_CLIENT_ID": "test-client-id",+ "SLACK_APP_CLIENT_SECRET": "test-client-secret",+ "SLACK_APP_SIGNING_SECRET": "test-signing-secret",+ },+ )+ def test_retrieve_slack_integration_with_scope_succeeds(+ self, _mock_settings, _mock_oauth_settings, client: HttpClient+ ):slack_integration = Integration.objects.create(team=self.team,kind="slack",@@ -1259,7 +1269,7 @@ class TestIntegrationAPIKeyAccess:assert response.status_code == status.HTTP_400_BAD_REQUESTassert expected_provider in response.json()["detail"]- @patch("posthog.models.integration.GitHubIntegration.list_cached_repositories")+ @patch("posthog.models.integration.github.GitHubIntegration.list_cached_repositories")def test_github_repos_with_scope_succeeds(self, mock_list_repos, client: HttpClient):mock_list_repos.return_value = ([@@ -1290,7 +1300,7 @@ class TestIntegrationAPIKeyAccess:assert data["has_more"] is Falsemock_list_repos.assert_called_once_with(search="", limit=100, offset=0)- @patch("posthog.models.integration.GitHubIntegration.list_cached_repositories")+ @patch("posthog.models.integration.github.GitHubIntegration.list_cached_repositories")def test_github_repos_pagination(self, mock_list_repos, client: HttpClient):repos = [{"id": i, "name": f"repo{i}", "full_name": f"org/repo{i}"} for i in range(100)]mock_list_repos.return_value = (repos, True)@@ -1314,7 +1324,7 @@ class TestIntegrationAPIKeyAccess:assert data["has_more"] is Truemock_list_repos.assert_called_once_with(search="", limit=100, offset=100)- @patch("posthog.models.integration.GitHubIntegration.list_cached_repositories")+ @patch("posthog.models.integration.github.GitHubIntegration.list_cached_repositories")def test_github_repos_has_more_false_when_partial_page(self, mock_list_repos, client: HttpClient):repos = [{"id": i, "name": f"repo{i}", "full_name": f"org/repo{i}"} for i in range(50)]mock_list_repos.return_value = (repos, False)@@ -1337,7 +1347,7 @@ class TestIntegrationAPIKeyAccess:assert len(data["repositories"]) == 50assert data["has_more"] is False- @patch("posthog.models.integration.GitHubIntegration.list_cached_repositories")+ @patch("posthog.models.integration.github.GitHubIntegration.list_cached_repositories")def test_github_repos_passes_limit_offset(self, mock_list_repos, client: HttpClient):repos = [{"id": i, "name": f"repo{i}", "full_name": f"org/repo{i}"} for i in range(10)]mock_list_repos.return_value = (repos, True)@@ -1361,7 +1371,7 @@ class TestIntegrationAPIKeyAccess:assert data["has_more"] is Truemock_list_repos.assert_called_once_with(search="", limit=10, offset=50)- @patch("posthog.models.integration.GitHubIntegration.list_cached_repositories")+ @patch("posthog.models.integration.github.GitHubIntegration.list_cached_repositories")def test_github_repos_passes_search_before_pagination(self, mock_list_repos, client: HttpClient):repos = [{"id": 2, "name": "posthog-js", "full_name": "org/posthog-js"}]mock_list_repos.return_value = (repos, False)@@ -1411,7 +1421,7 @@ class TestIntegrationAPIKeyAccess:),],)- @patch("posthog.models.integration.GitHubIntegration.list_teams")+ @patch("posthog.models.integration.github.GitHubIntegration.list_teams")def test_github_teams(self, mock_list_teams, query_string, mock_return, expected_call, client: HttpClient):mock_list_teams.return_value = mock_return@@ -1434,7 +1444,7 @@ class TestIntegrationAPIKeyAccess:assert data["has_more"] is mock_return[1]mock_list_teams.assert_called_once_with(**expected_call)- @patch("posthog.models.integration.GitHubIntegration.list_teams")+ @patch("posthog.models.integration.github.GitHubIntegration.list_teams")def test_github_teams_errors_return_400(self, mock_list_teams, client: HttpClient):mock_list_teams.side_effect = GitHubIntegrationError("GitHubIntegration: list_teams failed")@@ -1515,7 +1525,7 @@ class TestIntegrationAPIKeyAccess:mock_ensure_token_valid.assert_called_once_with(linear_integration)mock_list_teams.assert_called_once_with()- @patch("posthog.models.integration.GitHubIntegration.sync_repository_cache")+ @patch("posthog.models.integration.github.GitHubIntegration.sync_repository_cache")def test_refresh_github_repos_with_write_scope_succeeds(self, mock_sync_repository_cache, client: HttpClient):mock_sync_repository_cache.return_value = [{"id": 1, "name": "repo1", "full_name": "org/repo1"},@@ -1543,7 +1553,7 @@ class TestIntegrationAPIKeyAccess:min_refresh_interval_seconds=GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS)- @patch("posthog.models.integration.GitHubIntegration.sync_repository_cache")+ @patch("posthog.models.integration.github.GitHubIntegration.sync_repository_cache")def test_refresh_github_repos_uses_sync_path_even_with_fresh_cache(self,mock_sync_repository_cache,@@ -1572,7 +1582,7 @@ class TestIntegrationAPIKeyAccess:min_refresh_interval_seconds=GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS)- @patch("posthog.models.integration.GitHubIntegration.sync_repository_cache")+ @patch("posthog.models.integration.github.GitHubIntegration.sync_repository_cache")def test_refresh_github_repos_with_read_scope_fails(self, mock_sync_repository_cache, client: HttpClient):key_value = "test_key_123"PersonalAPIKey.objects.create(@@ -2118,7 +2128,7 @@ class TestGitHubIntegrationCreatedReporting:)@patch("posthog.event_usage.report_user_action")- @patch("posthog.models.integration.GitHubIntegration.fetch_installation_access")+ @patch("posthog.models.integration.github.GitHubIntegration.fetch_installation_access")def test_reports_integration_created_once_per_installation(self, mock_fetch, mock_report):mock_fetch.return_value = GitHubInstallationAccess(installation_id="12345",@@ -2161,7 +2171,7 @@ class TestGitHubIntegrationStateValidation:base.update(overrides)return base- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_create_github_integration_without_state_rejected(self, mock_from_install, client: HttpClient):client.force_login(self.user)@@ -2175,7 +2185,7 @@ class TestGitHubIntegrationStateValidation:assert "state token must be provided" in response.json()["detail"]mock_from_install.assert_not_called()- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_create_github_integration_without_code_rejected(self, mock_from_install, client: HttpClient):client.force_login(self.user)@@ -2189,7 +2199,7 @@ class TestGitHubIntegrationStateValidation:assert "OAuth code must be provided" in response.json()["detail"]mock_from_install.assert_not_called()- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_create_github_integration_with_invalid_state_rejected(self, mock_from_install, client: HttpClient):client.force_login(self.user)store_unified_authorize_state(@@ -2212,7 +2222,7 @@ class TestGitHubIntegrationStateValidation:assert "Invalid or expired state token" in response.json()["detail"]mock_from_install.assert_not_called()- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_create_github_integration_with_expired_state_rejected(self, mock_from_install, client: HttpClient):client.force_login(self.user)# No token in cache = expired@@ -2278,8 +2288,8 @@ class TestGitHubIntegrationStateValidation:assert mock_report.call_args.args[2] == {"integration_kind": "tiktok-ads"}@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")@patch("posthog.models.user_integration.user_github_integration_from_installation")def test_create_github_integration_with_valid_state_succeeds(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient@@ -2335,8 +2345,8 @@ class TestGitHubIntegrationStateValidation:@patch("posthog.api.integration.report_user_action")@patch("posthog.event_usage.report_user_action")@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")- @patch("posthog.models.integration.GitHubIntegration.fetch_installation_access")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.fetch_installation_access")def test_create_github_integration_reports_created_exactly_once(self,mock_fetch,@@ -2394,8 +2404,8 @@ class TestGitHubIntegrationStateValidation:assert props["account_type"] == "organization"@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")@patch("posthog.models.user_integration.user_github_integration_from_installation")def test_create_github_integration_state_token_single_use(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient@@ -2449,7 +2459,7 @@ class TestGitHubIntegrationStateValidation:assert response.status_code == status.HTTP_400_BAD_REQUESTassert "Invalid or expired state token" in response.json()["detail"]- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_create_github_integration_cross_user_state_rejected(self, mock_from_install, client: HttpClient):other_user = User.objects.create_and_join(self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN@@ -2476,8 +2486,8 @@ class TestGitHubIntegrationStateValidation:assert "Invalid or expired state token" in response.json()["detail"]mock_from_install.assert_not_called()- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_create_github_integration_code_exchange_failure_rejected(self, mock_from_install, mock_from_code, client: HttpClient):@@ -2505,8 +2515,8 @@ class TestGitHubIntegrationStateValidation:assert "Failed to exchange the OAuth code" in response.json()["detail"]mock_from_install.assert_not_called()- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_create_github_integration_rejects_foreign_installation_id(self, mock_from_install, mock_user_from_code, client: HttpClient):@@ -2837,8 +2847,8 @@ class TestGitHubTeamIntegrationComplete:assert kwargs["team"] == self.team@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")@patch("posthog.models.user_integration.user_github_integration_from_installation")def test_success_redirects_to_next_with_integration_id(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient@@ -2905,8 +2915,8 @@ class TestGitHubTeamIntegrationComplete:assert not Integration.objects.filter(team=self.team, kind="github").exists()@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")@patch("posthog.models.user_integration.user_github_integration_from_installation")def test_member_can_complete_fresh_team_install(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient@@ -2971,8 +2981,8 @@ class TestGitHubTeamIntegrationComplete:assert Integration.objects.filter(id=existing.id).count() == 1@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")@patch("posthog.models.user_integration.user_github_integration_from_installation")def test_environment_integrations_flow_uses_team_id_from_authorize_cache(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient@@ -3009,9 +3019,9 @@ class TestGitHubTeamIntegrationComplete:assert "github_setup_error=invalid_state" not in response["Location"]assert "integration_id=" in response["Location"]- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)- @patch("posthog.models.integration.GitHubIntegration.client_request")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.verify_user_installation_access", return_value=True)+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")def test_personal_github_setup_finishes_inline(self, mock_user_from_code, mock_client_request, mock_verify, client: HttpClient):@@ -3057,9 +3067,9 @@ class TestGitHubTeamIntegrationComplete:assert "/complete/github-link" not in response["Location"]mock_user_from_code.assert_called_once_with("oauth-code-abc")- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)- @patch("posthog.models.integration.GitHubIntegration.client_request")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.verify_user_installation_access", return_value=True)+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")def test_personal_github_setup_with_forged_team_next_still_finishes_personal(self, mock_user_from_code, mock_client_request, mock_verify, client: HttpClient):@@ -3110,7 +3120,7 @@ class TestGitHubTeamIntegrationComplete:assert not Integration.objects.filter(team=self.team, kind="github").exists()assert UserIntegration.objects.filter(user=self.user, kind="github", integration_id="12345").exists()- @patch("posthog.models.integration.GitHubIntegration.client_request")+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")def test_personal_github_setup_update_redirects_to_personal_settings(self, mock_client_request, client: HttpClient):client.force_login(self.user)UserIntegration.objects.create(@@ -3148,7 +3158,7 @@ class TestGitHubTeamIntegrationComplete:assert integration.sensitive_config["access_token"] == "ghs_install_token"assert integration.sensitive_config["user_access_token"] == "gho_user"- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_team_github_setup_update_without_state_redirects_to_project_integrations(self, mock_refresh, client: HttpClient):@@ -3166,7 +3176,7 @@ class TestGitHubTeamIntegrationComplete:assert "github_setup_error" not in response["Location"]mock_refresh.assert_called_once_with("12345", self.team.pk, self.user)- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_update_setup_action_via_callback_redirects_successfully(self, mock_refresh, client: HttpClient):client.force_login(self.user)mock_refresh.return_value = self._team_github_integration(installation_id="98797544")@@ -3197,7 +3207,7 @@ class TestGitHubTeamIntegrationComplete:assert "integration_id=" in response["Location"]mock_refresh.assert_called_once()- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_prepare_callback_update_without_state_redirects_to_account_connected(self, mock_refresh, client: HttpClient):@@ -3227,7 +3237,7 @@ class TestGitHubTeamIntegrationComplete:mock_refresh.assert_called_once()@pytest.mark.parametrize("callback_installation_id,expect_error", [("12345", False), ("99999", True)])- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_team_update_callback_binds_seeded_installation_id(self, mock_refresh, callback_installation_id, expect_error, client: HttpClient):@@ -3306,7 +3316,7 @@ class TestGitHubTeamIntegrationComplete:assert response["Location"].startswith("https://github.com/login/oauth/authorize")mock_build_oauth_url.assert_called_once()- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_admin_links_existing_org_installation_without_personal_github(self, mock_from_install, client: HttpClient):# A GitHub App installs once per org, so a second project hits the Setup URL with# setup_action=update and no OAuth code. A team admin must be able to complete that link@@ -3360,7 +3370,7 @@ class TestGitHubTeamIntegrationComplete:codes = exc_info.value.get_codes()assert isinstance(codes, list) and GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED in codes- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)+ @patch("posthog.models.integration.github.GitHubIntegration.verify_user_installation_access", return_value=True)def test_authorize_link_existing_proves_non_admin_access_with_personal_oauth_token(self, mock_verify):# The proof must run on the user-to-server OAuth token, not the installation-scoped# access_token: /user/installations/{id}/repositories authenticates as the user, and an@@ -3374,7 +3384,7 @@ class TestGitHubTeamIntegrationComplete:mock_verify.assert_called_once_with("12345", "gho_personal_token")- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_link_existing_auto_resolves_single_org_installation(self, mock_from_install):# The one-click "Link existing installation" UI sends no source_team_id / installation_id;# the service must resolve the org's single existing installation and link it to this team.@@ -3422,7 +3432,7 @@ class TestGitHubTeamIntegrationComplete:installation_id_param=None,)- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_link_existing_with_installation_id_disambiguates_multiple(self, mock_from_install):# With more than one org installation, auto-resolve is ambiguous; passing the chosen# installation_id must link that specific installation instead of raising.@@ -3536,7 +3546,7 @@ class TestGitHubTeamIntegrationComplete:codes = exc_info.value.get_codes()assert isinstance(codes, list) and GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION in codes- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)+ @patch("posthog.models.integration.github.GitHubIntegration.verify_user_installation_access", return_value=True)def test_link_existing_never_adopts_installation_linked_to_inaccessible_project(self, mock_verify):# Personal GitHub access must not override the project access boundary: an installation# linked to a private sibling isn't an orphan, so adoption must not even be attempted,@@ -3559,7 +3569,7 @@ class TestGitHubTeamIntegrationComplete:mock_verify.assert_not_called()assert not Integration.objects.filter(team=self.team, kind="github", integration_id="777").exists()- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_link_existing_links_installation_also_held_by_an_inaccessible_project(self, mock_from_install):# One installation shared by a private project and an accessible one. Resolving the source# across the whole org and only then checking access would settle on the private project's@@ -3583,7 +3593,7 @@ class TestGitHubTeamIntegrationComplete:)assert mock_from_install.call_args.args[0] == "111"- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_auto_resolve_ignores_installations_the_user_cannot_access(self, mock_from_install):# The picker offers exactly one installation, so the UI sends the one-click empty payload.# Counting installations the caller can't see would call that ambiguous and dead-end the very@@ -3641,7 +3651,7 @@ class TestGitHubTeamIntegrationComplete:assert "github_setup_error=invalid_state" in response["Location"]@pytest.mark.parametrize("stored_installation_id", [12345, "12345"])- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_team_update_heuristic_finds_existing_integration_regardless_of_jsonb_id_type(self, mock_refresh, stored_installation_id, client: HttpClient):@@ -3667,7 +3677,7 @@ class TestGitHubTeamIntegrationComplete:assert "github_setup_error" not in response["Location"]assert f"integration_id={existing.id}" in response["Location"]- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_team_prepare_callback_update_wins_when_personal_integration_also_exists(self, mock_refresh, client: HttpClient):@@ -3704,8 +3714,8 @@ class TestGitHubTeamIntegrationComplete:assert f"integration_id={team_integration.id}" in response["Location"]mock_refresh.assert_called_once()- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.verify_user_installation_access", return_value=True)+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")def test_link_existing_adopts_orphan_installation_with_personal_github_proof(self, mock_from_install, mock_verify):# No PostHog team anywhere has installation "424242" linked, so it's a true orphan: installed# on GitHub but never round-tripped through PostHog's callback. Proving personal access to it@@ -3728,7 +3738,7 @@ class TestGitHubTeamIntegrationComplete:integration = Integration.objects.get(team=self.team, kind="github", integration_id="424242")assert integration.config["connecting_user_github_login"] == "personaluser"- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=False)+ @patch("posthog.models.integration.github.GitHubIntegration.verify_user_installation_access", return_value=False)def test_link_existing_adoption_rejects_when_verification_fails(self, _mock_verify):self._personal_github_integration(self.user)@@ -3746,7 +3756,7 @@ class TestGitHubTeamIntegrationComplete:assert not Integration.objects.filter(kind="github", integration_id="424242").exists()@patch(- "posthog.models.integration.GitHubIntegration.verify_user_installation_access",+ "posthog.models.integration.github.GitHubIntegration.verify_user_installation_access",side_effect=requests.RequestException("boom"),)def test_link_existing_adoption_rejects_when_verification_errors(self, _mock_verify):@@ -3792,7 +3802,7 @@ class TestGitHubTeamIntegrationComplete:assert isinstance(codes, list) and expected_code in codesassert not Integration.objects.filter(kind="github", integration_id="424242").exists()- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)+ @patch("posthog.models.integration.github.GitHubIntegration.verify_user_installation_access", return_value=True)def test_link_existing_adoption_refuses_member_even_with_valid_github_proof(self, mock_verify):# Valid personal GitHub access must not let a plain member introduce a new installation to# the org: unlike the create/update flows, adoption has no GitHub-side gate on who submits@@ -3881,7 +3891,7 @@ class TestGitHubTeamIntegrationComplete:assert usable_personal_github_token(self.user) == "gho_older_token"assert mock_get_token.call_count == 2- @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)+ @patch("posthog.models.integration.github.GitHubIntegration.verify_user_installation_access", return_value=True)def test_link_existing_rejects_leading_zero_installation_id(self, mock_verify):# "0111" would miss the string-equality check against the stored "111" and fall through to# adoption of an installation a private sibling already holds, so it must fail validation.@@ -4393,7 +4403,7 @@ class TestOauthIntegrationRevokeOnDisconnect:created_by=self.user,)- @patch("posthog.models.integration.requests.post")+ @patch("posthog.models.integration.oauth.requests.post")def test_destroy_salesforce_revokes_token_at_provider(self, mock_post, client: HttpClient):integration = self._create_salesforce_integration()@@ -4409,7 +4419,7 @@ class TestOauthIntegrationRevokeOnDisconnect:allow_redirects=False,)- @patch("posthog.models.integration.requests.post")+ @patch("posthog.models.integration.oauth.requests.post")def test_destroy_sandbox_salesforce_revokes_at_sandbox_host(self, mock_post, client: HttpClient):# Sandbox integrations are stored as kind "salesforce" with a sandbox instance_url; revoking# must hit that host, not login.salesforce.com, or the sandbox grant is never invalidated.@@ -4429,7 +4439,7 @@ class TestOauthIntegrationRevokeOnDisconnect:allow_redirects=False,)- @patch("posthog.models.integration.requests.post")+ @patch("posthog.models.integration.oauth.requests.post")def test_destroy_still_deletes_when_revoke_fails(self, mock_post, client: HttpClient):client.force_login(self.user)@@ -4450,7 +4460,7 @@ class TestOauthIntegrationRevokeOnDisconnect:assert response.status_code == status.HTTP_204_NO_CONTENTassert not Integration.objects.filter(id=rejected.id).exists()- @patch("posthog.models.integration.requests.post")+ @patch("posthog.models.integration.oauth.requests.post")def test_destroy_without_tokens_skips_revoke(self, mock_post, client: HttpClient):integration = self._create_salesforce_integration(sensitive_config={})@@ -4461,7 +4471,7 @@ class TestOauthIntegrationRevokeOnDisconnect:assert not Integration.objects.filter(id=integration.id).exists()mock_post.assert_not_called()- @patch("posthog.models.integration.requests.post")+ @patch("posthog.models.integration.oauth.requests.post")def test_destroy_kind_without_revoke_url_skips_revoke(self, mock_post, client: HttpClient):integration = Integration.objects.create(team=self.team,@@ -4520,7 +4530,7 @@ class TestStripeIntegrationOAuthTokens:)return integration, access_token, refresh_token- @patch("posthog.models.integration.settings")+ @patch("posthog.models.integration.stripe.settings")def test_destroy_oauth_tokens_deletes_tokens(self, mock_settings):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_idintegration, access_token, refresh_token = self._create_integration_with_tokens()@@ -4531,7 +4541,7 @@ class TestStripeIntegrationOAuthTokens:assert not OAuthAccessToken.objects.filter(pk=access_token.pk).exists()assert not OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()- @patch("posthog.models.integration.settings")+ @patch("posthog.models.integration.stripe.settings")def test_destroy_oauth_tokens_only_affects_same_team(self, mock_settings):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_idintegration, _, _ = self._create_integration_with_tokens()@@ -4559,7 +4569,7 @@ class TestStripeIntegrationOAuthTokens:assert OAuthAccessToken.objects.filter(pk=other_access_token.pk).exists()assert OAuthRefreshToken.objects.filter(pk=other_refresh_token.pk).exists()- @patch("posthog.models.integration.settings")+ @patch("posthog.models.integration.stripe.settings")def test_destroy_oauth_tokens_noop_when_no_oauth_app(self, mock_settings):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = Noneintegration, access_token, refresh_token = self._create_integration_with_tokens()@@ -4571,10 +4581,12 @@ class TestStripeIntegrationOAuthTokens:assert OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()@patch("stripe.StripeClient")- @patch("posthog.models.integration.settings")- def test_write_posthog_secrets_uses_account_scope(self, mock_settings, MockStripeClient):+ @patch("posthog.models.integration.oauth.settings")+ @patch("posthog.models.integration.stripe.settings")+ def test_write_posthog_secrets_uses_account_scope(self, mock_settings, mock_oauth_settings, MockStripeClient):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id- mock_settings.STRIPE_APP_SECRET_KEY = "sk_test"+ mock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"+ mock_oauth_settings.STRIPE_APP_SECRET_KEY = "sk_test"mock_client = MagicMock()MockStripeClient.return_value = mock_client@@ -4600,10 +4612,12 @@ class TestStripeIntegrationOAuthTokens:assert secret_payloads["posthog_oauth_client_id"] == self.oauth_app.client_id@patch("stripe.StripeClient")- @patch("posthog.models.integration.settings")- def test_write_posthog_secrets_mints_read_only_token(self, mock_settings, MockStripeClient):+ @patch("posthog.models.integration.oauth.settings")+ @patch("posthog.models.integration.stripe.settings")+ def test_write_posthog_secrets_mints_read_only_token(self, mock_settings, mock_oauth_settings, MockStripeClient):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id- mock_settings.STRIPE_APP_SECRET_KEY = "sk_test"+ mock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"+ mock_oauth_settings.STRIPE_APP_SECRET_KEY = "sk_test"MockStripeClient.return_value = MagicMock()integration = Integration.objects.create(@@ -4629,9 +4643,11 @@ class TestStripeIntegrationOAuthTokens:assert token.scoped_teams == [self.team.pk]@patch("stripe.StripeClient")- @patch("posthog.models.integration.settings")- def test_clear_posthog_secrets_uses_account_scope(self, mock_settings, MockStripeClient):- mock_settings.STRIPE_APP_SECRET_KEY = "sk_test"+ @patch("posthog.models.integration.oauth.settings")+ @patch("posthog.models.integration.stripe.settings")+ def test_clear_posthog_secrets_uses_account_scope(self, mock_settings, mock_oauth_settings, MockStripeClient):+ mock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"+ mock_oauth_settings.STRIPE_APP_SECRET_KEY = "sk_test"mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = Nonemock_client = MagicMock()MockStripeClient.return_value = mock_client@@ -4660,10 +4676,14 @@ class TestStripeIntegrationOAuthTokens:])@patch("stripe.StripeClient")- @patch("posthog.models.integration.settings")- def test_stripe_client_uses_live_secret(self, _name, method_name, mock_settings, MockStripeClient):+ @patch("posthog.models.integration.oauth.settings")+ @patch("posthog.models.integration.stripe.settings")+ def test_stripe_client_uses_live_secret(+ self, _name, method_name, mock_settings, mock_oauth_settings, MockStripeClient+ ):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id- mock_settings.STRIPE_APP_SECRET_KEY = "sk_live"+ mock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"+ mock_oauth_settings.STRIPE_APP_SECRET_KEY = "sk_live"MockStripeClient.return_value = MagicMock()integration = Integration.objects.create(@@ -4682,13 +4702,16 @@ class TestStripeIntegrationOAuthTokens:MockStripeClient.assert_called_once_with("sk_live")- @patch("posthog.models.integration.capture_exception")+ @patch("posthog.models.integration.stripe.capture_exception")@patch("stripe.StripeClient")- @patch("posthog.models.integration.settings")- def test_write_posthog_secrets_skips_when_keys_missing(self, mock_settings, MockStripeClient, mock_capture):+ @patch("posthog.models.integration.oauth.settings")+ @patch("posthog.models.integration.stripe.settings")+ def test_write_posthog_secrets_skips_when_keys_missing(+ self, mock_settings, mock_oauth_settings, MockStripeClient, mock_capture+ ):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id- mock_settings.STRIPE_APP_CLIENT_ID = None- mock_settings.STRIPE_APP_SECRET_KEY = None+ mock_oauth_settings.STRIPE_APP_CLIENT_ID = None+ mock_oauth_settings.STRIPE_APP_SECRET_KEY = NoneMockStripeClient.return_value = MagicMock()integration = Integration.objects.create(@@ -4707,15 +4730,16 @@ class TestStripeIntegrationOAuthTokens:captured_exc = mock_capture.call_args.args[0]assert isinstance(captured_exc, NotImplementedError)- @patch("posthog.models.integration.capture_exception")+ @patch("posthog.models.integration.stripe.capture_exception")@patch("stripe.StripeClient")- @patch("posthog.models.integration.settings")+ @patch("posthog.models.integration.oauth.settings")+ @patch("posthog.models.integration.stripe.settings")def test_clear_posthog_secrets_skips_and_revokes_tokens_when_keys_missing(- self, mock_settings, MockStripeClient, mock_capture+ self, mock_settings, mock_oauth_settings, MockStripeClient, mock_capture):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id- mock_settings.STRIPE_APP_CLIENT_ID = None- mock_settings.STRIPE_APP_SECRET_KEY = None+ mock_oauth_settings.STRIPE_APP_CLIENT_ID = None+ mock_oauth_settings.STRIPE_APP_SECRET_KEY = NoneMockStripeClient.return_value = MagicMock()integration, access_token, refresh_token = self._create_integration_with_tokens()@@ -4834,7 +4858,7 @@ class TestGitHubBranches:assert branches == namesassert mock_request.call_count == 2- @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.list_cached_branches")def test_api_endpoint_passes_search_limit_offset(self, mock_list_cached, client: HttpClient):mock_list_cached.return_value = ([f"branch-{i}" for i in range(10)], "main", True)client.force_login(self.user)@@ -4856,7 +4880,7 @@ class TestGitHubBranches:offset=50,)- @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.list_cached_branches")def test_api_endpoint_default_branch_first_on_page_one(self, mock_list_cached, client: HttpClient):mock_list_cached.return_value = (["main", "alpha", "zebra"], "main", False)client.force_login(self.user)@@ -4870,7 +4894,7 @@ class TestGitHubBranches:assert data["branches"][0] == "main"assert data["default_branch"] == "main"- @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.list_cached_branches")def test_api_endpoint_pages_cached_branches_without_reinserting_default(self, mock_list_cached, client: HttpClient):mock_list_cached.return_value = (["other"], "main", False)client.force_login(self.user)@@ -4883,7 +4907,7 @@ class TestGitHubBranches:data = response.json()assert data["branches"] == ["other"]- @patch("posthog.models.integration.GitHubIntegration.list_cached_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.list_cached_branches")def test_api_endpoint_prepends_default_branch_even_when_not_in_list(self, mock_list_cached, client: HttpClient):mock_list_cached.return_value = (["main", "alpha", "beta"], "main", False)client.force_login(self.user)@@ -4896,8 +4920,8 @@ class TestGitHubBranches:data = response.json()assert data["branches"] == ["main", "alpha", "beta"]- @patch("posthog.models.integration.GitHubIntegration.get_default_branch", return_value="main")- @patch("posthog.models.integration.GitHubIntegration.list_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.get_default_branch", return_value="main")+ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")def test_api_endpoint_validates_limit_max(self, mock_list, mock_default, client: HttpClient):mock_list.return_value = ([], False)client.force_login(self.user)@@ -5791,8 +5815,8 @@ class TestPushIdentityVerificationAPI(APIBaseTest):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()- @patch("posthog.models.integration.GoogleRequest")- @patch("posthog.models.integration.service_account.Credentials.from_service_account_info")+ @patch("posthog.models.integration.push.GoogleRequest")+ @patch("posthog.models.integration.push.service_account.Credentials.from_service_account_info")def test_setting_the_mode_reaches_the_integration(self, mock_from_sa, _mock_google_request):# The serializer builds each provider's arguments from named config fields, so a key it doesn't# know about is dropped before it ever reaches the integration. That silently made the setup@@ -5826,7 +5850,7 @@ class TestIntegrationMembershipPermissions(APIBaseTest):self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()- @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")+ @patch("posthog.models.integration.aws.validate_aws_credentials", return_value="123456789012")def test_member_can_create_integration(self, _mock_validate):response = self.client.post(f"/api/environments/{self.team.pk}/integrations",diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.pyindex 3d67f9121167..d1093b549c54 100644--- a/posthog/api/test/test_user_integration.py+++ b/posthog/api/test/test_user_integration.py@@ -357,8 +357,8 @@ class TestUserIntegrationEndpoints(APIBaseTest):SITE_URL="https://us.posthog.com",)@patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.client_request")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")def test_github_link_oauth_callback_creates_user_integration_without_installation_in_query(self, mock_user_from_code, mock_client_request, mock_verify_get):@@ -417,8 +417,8 @@ class TestUserIntegrationEndpoints(APIBaseTest):SITE_URL="https://us.posthog.com",)@patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.client_request")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")def test_github_link_oauth_callback_ignores_query_installation_id_when_state_binds_one(self, mock_user_from_code, mock_client_request, mock_verify_get):@@ -476,8 +476,8 @@ class TestUserIntegrationEndpoints(APIBaseTest):SITE_URL="https://us.posthog.com",)@patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.client_request")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")def test_github_link_oauth_discover_creates_user_integration_from_visible_installation(self, mock_user_from_code, mock_client_request, mock_requests_get):@@ -532,7 +532,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):return_value={"GITHUB_APP_SLUG": "posthog-dev"},)@patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")def test_github_link_oauth_discover_redirects_to_app_install_when_no_installations(self, mock_user_from_code, mock_requests_get, _mock_settings):@@ -562,8 +562,8 @@ class TestUserIntegrationEndpoints(APIBaseTest):@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")@patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.client_request")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")def test_github_link_callback_creates_user_integration(self, mock_user_from_code, mock_client_request, mock_verify_get):@@ -608,8 +608,8 @@ class TestUserIntegrationEndpoints(APIBaseTest):)@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")@patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.client_request")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")def test_github_link_redirects_to_client_destination_on_success(self,connect_from,@@ -783,10 +783,10 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertEqual(discover_state.connect_from, "posthog_code")@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")- @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")@patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.client_request")- @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")+ @patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")def test_github_link_callback_team_oauth_authorize_creates_team_integration(self,mock_user_from_code,@@ -1176,7 +1176,7 @@ class TestUserGitHubIntegrationFromInstallation(APIBaseTest):class TestGithubUserFromCode(APIBaseTest):@patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.requests.post")+ @patch("posthog.models.integration.github.requests.post")@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")def test_returns_full_authorization_including_tokens(self, mock_post, mock_get):mock_post.return_value = MagicMock(diff --git a/posthog/models/integration.py b/posthog/models/integration.pydeleted file mode 100644index eb312115b648..000000000000--- a/posthog/models/integration.py+++ /dev/null@@ -1,5855 +0,0 @@-import re-import hmac-import json-import time-import base64-import hashlib-import secrets-from collections.abc import Iterable, Mapping-from dataclasses import dataclass, field, replace-from datetime import datetime, timedelta-from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, NoReturn, Optional, Self, cast-from urllib.parse import parse_qs, urlencode, urlparse--from posthog.dataclasses import frozen--from products.workflows.backend.providers import MAILDEV_MOCK_DNS_RECORDS--if TYPE_CHECKING:- import aiohttp- from anthropic import Anthropic- from slack_sdk.web.async_client import AsyncWebClient- from stripe import StripeClient--from django.conf import settings-from django.core.cache import cache-from django.db import connection, models, transaction-from django.db.models import Q-from django.dispatch import receiver-from django.http import HttpRequest-from django.utils import timezone--import requests-import structlog-from cryptography.hazmat.primitives import serialization-from cryptography.hazmat.primitives.asymmetric import ec-from disposable_email_domains import blocklist as disposable_email_domains_list-from free_email_domains import whitelist as free_email_domains_list-from google.auth.transport.requests import Request as GoogleRequest-from google.oauth2 import service_account-from opentelemetry import trace-from prometheus_client import Counter-from requests.auth import HTTPBasicAuth-from rest_framework.exceptions import ValidationError-from rest_framework.request import Request-from slack_sdk.errors import SlackApiError-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed--from posthog.cache_utils import cache_for-from posthog.credentials import AWSKeyPair-from posthog.egress.github.transport import github_request-from posthog.egress.limiter.policies import Priority-from posthog.egress.slack.client import SlackWebClient as WebClient-from posthog.egress.slack.observability import record_slack_api_response-from posthog.exceptions_capture import capture_exception-from posthog.helpers.encrypted_fields import FERNET_TOKEN_PREFIX, EncryptedJSONField-from posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError-from posthog.models.instance_setting import get_instance_settings-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken-from posthog.models.team.team import Team-from posthog.models.user import User-from posthog.models.utils import IntegrityError, generate_random_oauth_access_token, generate_random_oauth_refresh_token-from posthog.plugins.plugin_server_api import reload_integrations_on_workers-from posthog.rbac.decorators import field_access_control-from posthog.schema_enums import SlackIntegrationScope-from posthog.scopes import get_oauth_scopes_supported-from posthog.security.url_validation import is_url_allowed-from posthog.sync import database_sync_to_async-from posthog.utils import get_instance_region--from products.workflows.backend.providers import SESProvider, TwilioProvider--logger = structlog.get_logger(__name__)-tracer = trace.get_tracer(__name__)---class UndecryptedIntegrationSecretError(ValueError):- """Raised when a value read off `Integration.sensitive_config` still looks like Fernet- ciphertext instead of the decrypted secret, and no configured key can open it.-- `sensitive_config` sets `ignore_decrypt_errors=True` so integrations written before- encryption existed keep loading, but that same leniency means a value that fails to- decrypt under every configured key (a lost key, a corrupted row) comes back as raw- ciphertext rather than raising. Left unchecked, that ciphertext gets sent to the- third-party API as if it were the real credential, which rejects it as invalid, hiding- the actual cause behind what looks like a bad customer-supplied key.-- The message is user-facing: it lands on the failed data warehouse job as `latest_error`.- """-- def __init__(self) -> None:- super().__init__(- "We couldn't read the saved credentials for this connection. Reconnect the account to start syncing again."- )---# Reading a still-encrypted secret means the row is either recoverably over-encrypted or-# permanently unreadable. Both are invisible from the sync failure alone, so count them by kind:-# a rising `unreadable` rate means live customer credentials are being lost.-integration_secret_decrypt_counter = Counter(- "integration_sensitive_config_decrypt_recovery",- "Reads of an Integration secret that came back still encrypted, by recovery outcome",- labelnames=["kind", "result"],-)---def _decrypted_sensitive_value(integration: "Integration", field_name: str) -> str | None:- """Read a secret off `sensitive_config`, peeling any extra encryption layers it picked up.-- A read-then-save of a row whose secret failed to decrypt writes that ciphertext back- encrypted again, so the stored value ends up double-encrypted. One decrypt (the field's- own) then leaves ciphertext behind. Peel the rest here: the underlying secret is intact- and the connection keeps working.- """- value = integration.sensitive_config.get(field_name)- if not isinstance(value, str) or not value.startswith(FERNET_TOKEN_PREFIX):- return value-- # django-stubs can't see through `field_access_control`, so it doesn't know this field name.- field = cast(EncryptedJSONField, integration._meta.get_field("sensitive_config")) # type: ignore[misc]- recovered = field.decrypt_all_layers(value)-- if recovered is None:- integration_secret_decrypt_counter.labels(kind=integration.kind, result="unreadable").inc()- logger.error(- "integration_sensitive_config_unreadable",- integration_id=integration.pk,- team_id=integration.team_id,- kind=integration.kind,- field=field_name,- )- raise UndecryptedIntegrationSecretError()-- integration_secret_decrypt_counter.labels(kind=integration.kind, result="recovered").inc()- logger.warning(- "integration_sensitive_config_over_encrypted",- integration_id=integration.pk,- team_id=integration.team_id,- kind=integration.kind,- field=field_name,- )- return recovered---def _decode_jwt_payload(token: str) -> dict | None:- """- Decode JWT payload without signature verification.-- Used to extract claims from OAuth tokens (id_token, access_token) where- we trust the token source (received directly from provider over HTTPS).-- Returns None if JWT doesn't have enough parts. Raises on decode errors- so callers can log exceptions with full traceback.- """- parts = token.split(".")- if len(parts) < 2:- return None- payload = parts[1]- # Handle missing base64 padding- decoded = base64.urlsafe_b64decode(payload + "===")- return json.loads(decoded)---oauth_refresh_counter = Counter(- "integration_oauth_refresh",- "Number of times an oauth refresh has been attempted",- labelnames=["kind", "result", "reason", "attempt"],-)--# Terminal rows are skipped by the sweep and stop emitting failure metrics, so a gradual fleet-# die-off would otherwise be invisible. Incremented once per row at the transition; a rising-# rate means connections are permanently breaking (e.g. a provider mass-revoking grants).-oauth_refresh_terminal_counter = Counter(- "integration_oauth_refresh_went_terminal",- "OAuth integrations whose refresh went terminal (unbroken invalid_grant streak)",- labelnames=["kind"],-)--# Consecutive-failure backoff for the every-minute refresh sweep (posthog/tasks/integrations.py).-# Without it, permanently dead integrations (revoked grants, deleted consumers) are retried every-# minute forever, hammering providers and drowning the failure metric in a noise floor that-# masks real fleet-wide breakage.-REFRESH_BACKOFF_BASE_SECONDS = 120-REFRESH_BACKOFF_MAX_SECONDS = 3600-REFRESH_TERMINAL_FAILURE_COUNT = 5--# `config` key flagging a grant that only the legacy fallback credentials can refresh.-CONFIG_LEGACY_OAUTH_CLIENT = "oauth_uses_legacy_client"--# `config` key holding the push device-registration identity verification policy, read by the-# push subscriptions endpoint. Owned by the customer, not by the provider credentials.-CONFIG_PUSH_IDENTITY_VERIFICATION = "push_identity_verification"-PUSH_IDENTITY_VERIFICATION_MODES = ("disabled", "optional", "required")--# `config` key holding the customer's EC (P-256) public key(s) used to verify ES256 identity tokens.-# Public halves only — the private key stays on the customer's backend. At most two, so a key can be-# rotated (register the new one, cut over, drop the old) without a gap, mirroring the secret's-# primary/backup pair.-CONFIG_PUSH_IDENTITY_PUBLIC_KEYS = "push_identity_public_keys"-MAX_PUSH_IDENTITY_PUBLIC_KEYS = 2---def _validate_push_identity_public_keys(public_keys: list[str]) -> None:- if not isinstance(public_keys, list) or not all(isinstance(key, str) for key in public_keys):- raise ValidationError("push_identity_public_keys must be a list of PEM-encoded public key strings")- if len(public_keys) > MAX_PUSH_IDENTITY_PUBLIC_KEYS:- raise ValidationError(f"push_identity_public_keys accepts at most {MAX_PUSH_IDENTITY_PUBLIC_KEYS} keys")- for key in public_keys:- try:- loaded = serialization.load_pem_public_key(key.encode())- except Exception:- raise ValidationError("Each push_identity_public_key must be a valid PEM-encoded public key")- # ES256 is defined over P-256 specifically. Accepting another curve (P-384/P-521) would store a- # key the verifier can't use — jwt.decode raises InvalidKeyError against it — so reject it here.- if not isinstance(loaded, ec.EllipticCurvePublicKey) or not isinstance(loaded.curve, ec.SECP256R1):- raise ValidationError("push_identity_public_keys must be P-256 (secp256r1) EC public keys for ES256")---def preserved_push_config(- team_id: int,- kind: str,- integration_id: str,- push_identity_verification: str | None,- push_identity_public_keys: list[str] | None = None,-) -> dict:- """Config keys a push credential upsert must carry over rather than drop.-- Connecting a push integration is an upsert, and the provider helpers rebuild `config` from the- credentials they were handed. Anything they don't know about would be lost, so rotating a Firebase- key or APNs .p8 would silently reset an enabled identity verification policy (its mode and its- registered public keys) back to nothing, reopening the device takeover it exists to prevent. Carry- each existing value forward unless the caller explicitly sets a new one; pass an empty list to- clear the public keys.- """- if push_identity_verification is not None and push_identity_verification not in PUSH_IDENTITY_VERIFICATION_MODES:- raise ValidationError(- f"push_identity_verification must be one of: {', '.join(PUSH_IDENTITY_VERIFICATION_MODES)}"- )- if push_identity_public_keys is not None:- _validate_push_identity_public_keys(push_identity_public_keys)-- # Serialize concurrent setup of this one integration for the rest of the caller's transaction.- # `select_for_update` alone only locks a row that already exists, so two first-time setups could- # both read "no policy" and the later write would clobber a policy the earlier one had just set.- # An advisory lock covers the not-yet-created case too, keyed on the integration's identity so it- # only serializes writers racing for the same integration. Every writer takes it, including one- # setting explicit values — otherwise it could slip its row in between a preserving writer's read- # and write, and have its policy dropped.- with connection.cursor() as cursor:- cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [team_id, f"{kind}:{integration_id}"])-- existing = (- Integration.objects.select_for_update()- .filter(team_id=team_id, kind=kind, integration_id=integration_id)- .only("config")- .first()- )- existing_config = (existing.config or {}) if existing else {}- result: dict = {}-- if push_identity_verification is not None:- result[CONFIG_PUSH_IDENTITY_VERIFICATION] = push_identity_verification- else:- # Drop a stored mode we don't recognize rather than carrying it forward. The push endpoint- # already treats an unknown mode as disabled, so preserving it would keep dead data alive, and- # raising here would leave a corrupted integration unable to rotate its credentials.- existing_mode = existing_config.get(CONFIG_PUSH_IDENTITY_VERIFICATION)- if existing_mode in PUSH_IDENTITY_VERIFICATION_MODES:- result[CONFIG_PUSH_IDENTITY_VERIFICATION] = existing_mode-- if push_identity_public_keys is not None:- # A non-empty list sets/replaces; an empty list clears (omit the key entirely).- if push_identity_public_keys:- result[CONFIG_PUSH_IDENTITY_PUBLIC_KEYS] = push_identity_public_keys- else:- existing_keys = existing_config.get(CONFIG_PUSH_IDENTITY_PUBLIC_KEYS)- if isinstance(existing_keys, list) and existing_keys:- result[CONFIG_PUSH_IDENTITY_PUBLIC_KEYS] = existing_keys-- return result---# Values for the counter's `reason` label, bucketed from the OAuth error response.-REFRESH_FAILURE_REASON_INVALID_GRANT = "invalid_grant"-REFRESH_FAILURE_REASON_INVALID_CLIENT = "invalid_client"-REFRESH_FAILURE_REASON_HTTP_5XX = "http_5xx"-REFRESH_FAILURE_REASON_NETWORK = "network"-REFRESH_FAILURE_REASON_RATE_LIMITED = "rate_limited"-REFRESH_FAILURE_REASON_OTHER = "other"-# Not a provider response: the stored refresh token itself can't be decrypted, so no request was-# made. Terminal on the first occurrence, since no later attempt can make the secret readable.-REFRESH_FAILURE_REASON_UNREADABLE_SECRET = "unreadable_secret"---def oauth_refresh_failure_reason(status_code: int, body: dict, kind: str | None = None) -> str:- error = body.get("error")- if error == REFRESH_FAILURE_REASON_INVALID_GRANT:- return REFRESH_FAILURE_REASON_INVALID_GRANT- if error == REFRESH_FAILURE_REASON_INVALID_CLIENT:- return REFRESH_FAILURE_REASON_INVALID_CLIENT- # Reddit reports a dead grant as `{"message": "Bad Request", "error": 400}` with no OAuth- # error code. Our refresh request shape is fixed and succeeds fleet-wide, so a 400 on this- # endpoint means the grant, not the request - match that exact shape for reddit only.- if kind == "reddit-ads" and status_code == 400 and error == 400:- return REFRESH_FAILURE_REASON_INVALID_GRANT- # HubSpot reports a grant whose portal (hub) was deleted or disconnected as- # `{"status": "BAD_HUB", "error": "access_denied", ...}` - no `invalid_grant` code, so- # without this mapping the row is retried forever instead of going terminal. Its- # `BAD_REFRESH_TOKEN` responses do carry `"error": "invalid_grant"` and need no special case.- if kind == "hubspot" and status_code < 500 and body.get("status") == "BAD_HUB":- return REFRESH_FAILURE_REASON_INVALID_GRANT- # Meta Graph nests its error as an object (`{"error": {"code": 190, ...}}`) and never- # sends the `invalid_grant` string. Code 190 means the access token is dead (password- # change, checkpoint, expiry, revocation). Without this mapping, a revoked Meta token- # classifies as `other`. Meta rate limits use codes 4, 17, and 32, which do not match.- if kind in ("meta-ads", "instagram") and status_code < 500 and isinstance(error, dict) and error.get("code") == 190:- return REFRESH_FAILURE_REASON_INVALID_GRANT- # Transient throttling, not a credential problem: the backoff cap synchronises failed- # integrations into retry herds that can trip a provider's per-second limit and take- # healthy refreshes in the same second down with them.- if status_code == 429:- return REFRESH_FAILURE_REASON_RATE_LIMITED- if status_code >= 500:- return REFRESH_FAILURE_REASON_HTTP_5XX- return REFRESH_FAILURE_REASON_OTHER---def record_refresh_failure(integration: "Integration", *, reason: str = REFRESH_FAILURE_REASON_OTHER) -> str:- """Track a consecutive refresh failure on the integration's config; caller saves.-- Schedules the next attempt with capped exponential backoff. `invalid_grant` means the grant- itself is dead and only a customer re-auth can fix it, so after an unbroken streak of them the- integration goes terminal and the sweep stops retrying entirely. The streak is tracked- separately from the total failure count and resets on any other reason, so one transient- invalid_grant amid e.g. a 5xx outage can't brick the integration. `unreadable_secret` goes- terminal on the first occurrence - we never even reached the provider, and retrying can't make- an undecryptable token readable. Other reasons (invalid_client, 5xx, network, rate_limited)- never go terminal - a platform-side credential fix must let the fleet self-recover.-- Returns "first"/"retry" for the metric's `attempt` label - a spike in first failures means- connections are newly breaking, regardless of retry noise.- """- count = int(integration.config.get("refresh_failure_count") or 0)- attempt = "first" if count == 0 else "retry"- count += 1- integration.config["refresh_failure_count"] = count- integration.config["refresh_next_attempt_at"] = int(time.time()) + min(- REFRESH_BACKOFF_BASE_SECONDS * 2 ** (count - 1), REFRESH_BACKOFF_MAX_SECONDS- )- if reason == REFRESH_FAILURE_REASON_UNREADABLE_SECRET:- integration.config.pop("refresh_invalid_grant_count", None)- if not integration.config.get("refresh_terminal"):- integration.config["refresh_terminal"] = True- oauth_refresh_terminal_counter.labels(kind=integration.kind).inc()- elif reason == REFRESH_FAILURE_REASON_INVALID_GRANT:- grant_streak = int(integration.config.get("refresh_invalid_grant_count") or 0) + 1- integration.config["refresh_invalid_grant_count"] = grant_streak- # Guarded so on-demand refreshes (which bypass the backoff) can't re-count a dead row- if grant_streak >= REFRESH_TERMINAL_FAILURE_COUNT and not integration.config.get("refresh_terminal"):- integration.config["refresh_terminal"] = True- oauth_refresh_terminal_counter.labels(kind=integration.kind).inc()- else:- integration.config.pop("refresh_invalid_grant_count", None)- return attempt---def record_refresh_success(integration: "Integration") -> None:- for key in ("refresh_failure_count", "refresh_invalid_grant_count", "refresh_next_attempt_at", "refresh_terminal"):- integration.config.pop(key, None)---def record_oauth_client_used(integration: "Integration", *, used_fallback: bool) -> None:- """Track whether the grant still depends on the legacy (fallback) OAuth credentials.-- A refresh token minted by a since-migrated app can only be refreshed by that app's- credentials, so a successful fallback refresh identifies exactly the connections that break- when the legacy app is retired. The flag rides on `config`, which the API exposes, so the- product can tell those teams to reconnect. Reconnecting mints a grant on the primary- credentials and replaces `config` wholesale, which clears the flag.- """- if used_fallback:- integration.config[CONFIG_LEGACY_OAUTH_CLIENT] = True- else:- integration.config.pop(CONFIG_LEGACY_OAUTH_CLIENT, None)---def issuing_oauth_client_ids(integration: "Integration") -> list[str]:- """The OAuth client ids the connection was established with. Empty when that can't be read.-- OIDC puts the client id in the id_token's `aud` claim, and we keep the id_token from the- authorization exchange - refreshes only overwrite the access and refresh tokens. So this reads- the app the customer actually connected through, which is knowable for connections that already- exist, without waiting for a refresh to reveal it.-- `aud` is a string or a list of strings per RFC 7519, so both shapes are normalized here.- Callers should test membership rather than assume a single value: treating a list-shaped- audience as unreadable would silently drop those connections from the reconnect campaign.- """- id_token = integration.sensitive_config.get("id_token")- if not id_token:- return []- try:- claims = _decode_jwt_payload(id_token) or {}- except Exception:- logger.warning("Failed to decode id_token", integration_id=integration.id, kind=integration.kind)- return []- audience = claims.get("aud")- if isinstance(audience, str):- return [audience]- if isinstance(audience, list):- return [entry for entry in audience if isinstance(entry, str)]- return []---def refresh_backoff_active(integration: "Integration") -> bool:- """Whether the refresh sweep should skip this integration. Reconnecting resets the state- (the OAuth callback replaces `config` wholesale), and on-demand API refreshes bypass this."""- if integration.config.get("refresh_terminal"):- return True- next_attempt_at = integration.config.get("refresh_next_attempt_at")- return bool(next_attempt_at) and time.time() < next_attempt_at---# `owner/repo`, single slash, no traversal. Used to keep repo/ref/sha values out of GitHub API URL-# paths where a crafted value (e.g. `../../other-repo/contents/x?ref=y`) could redirect the-# authenticated request to a different endpoint.-_GITHUB_REPO_PATH_RE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$")-_GITHUB_REF_RE = re.compile(r"^[A-Za-z0-9._\-/]+$")-_GITHUB_COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,40}$")--# Upper bound on the diff text we return, to keep a pathological diff (generated/vendored-# files) from bloating the JSON response and worker memory. ~1 MB of text.-_MAX_DIFF_CHARS = 1_000_000---def _is_safe_github_repo_path(repo_path: str) -> bool:- return ".." not in repo_path and bool(_GITHUB_REPO_PATH_RE.fullmatch(repo_path))---def _is_safe_github_ref(ref: str) -> bool:- """A git ref safe to interpolate into a GitHub API URL path (no traversal / URL-control chars)."""- return (- bool(ref)- and ".." not in ref- and not ref.startswith("/")- and not ref.endswith("/")- and bool(_GITHUB_REF_RE.fullmatch(ref))- )---def _is_safe_github_sha(sha: str) -> bool:- return bool(_GITHUB_COMMIT_SHA_RE.fullmatch(sha))---PRIVATE_CHANNEL_WITHOUT_ACCESS = "PRIVATE_CHANNEL_WITHOUT_ACCESS"---def dot_get(d: Any, path: str, default: Any = None) -> Any:- if path in d and d[path] is not None:- return d[path]- for key in path.split("."):- if not isinstance(d, dict):- return default- d = d.get(key, default)- return d---def _extract_oauth_error_message(res: requests.Response) -> str | None:- """Pull a human-readable error from a failed OAuth token-exchange response.-- Most providers (Stripe, Google, etc.) return JSON of the shape- `{"error": "...", "error_description": "..."}`. Fall back to the raw body- (truncated) when the JSON has none of those fields, or when the body isn't- JSON at all — better to dump a snippet than to swallow the cause silently- and let the caller render a status-code-only message.- """- try:- body = res.json()- except Exception:- text = (res.text or "").strip()- return text[:300] if text else None-- if isinstance(body, dict):- description = body.get("error_description") or body.get("message")- code = body.get("error")- if description and code:- return f"{code}: {description}"- if description:- return str(description)- if code:- return str(code)-- # Unknown shape — surface a serialized snippet so the customer at least sees what came back.- try:- snippet = json.dumps(body)- except (TypeError, ValueError):- snippet = (res.text or "").strip()- return snippet[:300] if snippet else None---def _raise_oauth_validation_error(kind: str, res: requests.Response) -> NoReturn:- """Raise a ValidationError describing a failed OAuth token exchange.-- DRF turns ValidationError into a 400 with a populated `detail`, so the frontend toast renders- a useful message instead of the generic "Something went wrong" fallback that follows from a- bare Exception (which surfaces as a 500 with no detail).- """- provider_error = _extract_oauth_error_message(res)- if provider_error:- raise ValidationError(f"{kind} OAuth failed: {provider_error}")- raise ValidationError(f"{kind} OAuth failed (status {res.status_code}). Please try again.")---ERROR_TOKEN_REFRESH_FAILED = "TOKEN_REFRESH_FAILED"--# Instagram API with Facebook Login: the professional account is reached through the Facebook Page-# it is linked to, so the grant needs the page permissions as well as the Instagram ones. Meta-# replaced the legacy `instagram_*` permission names with `instagram_business_*`; the old names are-# rejected at the OAuth dialog ("This app needs at least one supported permission").-# https://developers.facebook.com/docs/instagram-platform/instagram-api-with-facebook-login-INSTAGRAM_OAUTH_SCOPE = (- "instagram_business_basic instagram_business_manage_insights instagram_business_manage_comments"- " pages_show_list pages_read_engagement"-)---class IntegrationQuerySet(models.QuerySet["Integration"]):- def for_github_installation_id(self, installation_id: str | int) -> Self:- return self.filter(- Q(config__installation_id=str(installation_id)) | Q(config__installation_id=int(installation_id))- )---class IntegrationManager(models.Manager["Integration"]):- _queryset_class = IntegrationQuerySet-- def get_queryset(self) -> IntegrationQuerySet:- return IntegrationQuerySet(self.model, using=self._db)-- def filter(self, *args: Any, **kwargs: Any) -> IntegrationQuerySet:- return self.get_queryset().filter(*args, **kwargs)-- def first_github_for_team_installation(self, team_id: int, installation_id: str) -> "Integration | None":- return (- self.filter(team_id=team_id, kind=Integration.IntegrationKind.GITHUB)- .for_github_installation_id(installation_id)- .first()- )-- def first_github_for_user_installation(self, user: User, installation_id: str) -> "Integration | None":- user_team_ids = user.teams.values_list("id", flat=True)- return (- self.filter(team_id__in=user_team_ids, kind=Integration.IntegrationKind.GITHUB)- .for_github_installation_id(installation_id)- .first()- )---class Integration(models.Model):- class IntegrationKind(models.TextChoices):- ANTHROPIC = "anthropic"- APPLE_PUSH = "apns"- AWS_REDSHIFT = "aws-redshift"- AWS_S3 = "aws-s3"- AZURE_BLOB = "azure-blob"- BING_ADS = "bing-ads"- CLICKUP = "clickup"- CUSTOMERIO_APP = "customerio-app"- CUSTOMERIO_TRACK = "customerio-track"- CUSTOMERIO_WEBHOOK = "customerio-webhook"- DATABRICKS = "databricks"- EMAIL = "email"- FIREBASE = "firebase"- GITHUB = "github"- GITLAB = "gitlab"- GOOGLE_ADS = "google-ads"- GOOGLE_ANALYTICS = "google-analytics"- GOOGLE_CALENDAR = "google-calendar"- GOOGLE_CLOUD_SERVICE_ACCOUNT = "google-cloud-service-account"- GOOGLE_CLOUD_STORAGE = "google-cloud-storage"- GOOGLE_PUBSUB = "google-pubsub"- GOOGLE_SEARCH_CONSOLE = "google-search-console"- GOOGLE_SHEETS = "google-sheets"- HUBSPOT = "hubspot"- INSTAGRAM = "instagram"- INTERCOM = "intercom"- JIRA = "jira"- LINEAR = "linear"- LINKEDIN_ADS = "linkedin-ads"- META_ADS = "meta-ads"- PARDOT = "pardot"- PINTEREST_ADS = "pinterest-ads"- POSTGRESQL = "postgresql"- POSTHOG = "posthog"- REDDIT_ADS = "reddit-ads"- RESEND = "resend"- S3_COMPATIBLE = "s3-compatible"- SALESFORCE = "salesforce"- SLACK = "slack"- # Deprecated — kept in choices to avoid a no-op migration. The runtime no longer creates- # or reads this kind; see `products/slack_app/backend/api.py` for the live integration.- SLACK_POSTHOG_CODE = "slack-posthog-code"- SNAPCHAT = "snapchat"- SNOWFLAKE = "snowflake"- STRIPE = "stripe"- TIKTOK_ADS = "tiktok-ads"- TWILIO = "twilio"- VERCEL = "vercel"- YOUTUBE_ANALYTICS = "youtube-analytics"-- team = models.ForeignKey("Team", on_delete=models.CASCADE)-- # The integration type identifier- kind = field_access_control(models.CharField(max_length=32, choices=IntegrationKind), "project", "admin")- # The ID of the integration in the external system- integration_id = field_access_control(models.TextField(null=True, blank=True), "project", "admin")- # Any config that COULD be passed to the frontend- config = field_access_control(models.JSONField(default=dict), "project", "admin")- sensitive_config = field_access_control(- EncryptedJSONField(- default=dict,- ignore_decrypt_errors=True, # allows us to load previously unencrypted data- ),- "project",- "admin",- )- repository_cache = models.JSONField(default=list, blank=True)- repository_cache_updated_at = models.DateTimeField(null=True, blank=True)-- errors = models.TextField()-- # Meta- created_at = models.DateTimeField(auto_now_add=True, blank=True)- created_by = models.ForeignKey("User", on_delete=models.SET_NULL, null=True, blank=True)-- objects: IntegrationManager = IntegrationManager()-- class Meta:- constraints = [- models.UniqueConstraint(- fields=["team", "kind", "integration_id"], name="posthog_integration_kind_id_unique"- )- ]- indexes = [models.Index(fields=["kind", "integration_id"], name="posthog_integration_kind_ext")]-- @property- def display_name(self) -> str:- if self.kind == "pinterest-ads":- # Pinterest's OAuth username is an opaque hash, so prefer the business name when there is one.- return self.config.get("business_name") or self.config.get("username") or self.integration_id- if self.kind == "tiktok-ads":- # The OAuth id is a list of advertiser ids, so prefer whoever authorized the connection.- return self.config.get("user_email") or self.config.get("user_display_name") or self.integration_id- if self.kind in OauthIntegration.supported_kinds:- region = self.config.get("region") if self.kind == "posthog" else None- oauth_config = OauthIntegration.oauth_config_for_kind(self.kind, region)- return dot_get(self.config, oauth_config.name_path, self.integration_id)- if self.kind in GoogleCloudIntegration.supported_kinds:- return self.integration_id or "unknown ID"- if self.kind == "github":- return dot_get(self.config, "account.name", self.integration_id)- if self.kind == "databricks":- return self.integration_id or "unknown ID"- if self.kind == Integration.IntegrationKind.AWS_S3:- name = self.integration_id or "unknown ID"-- account_id = self.config.get("aws_account_id")- role = self.config.get("aws_role_arn")-- if role:- detail = f"AWS role '{role}'"- elif account_id:- detail = f"AWS account {account_id}"- else:- detail = "access key"-- return f"{name} ({detail})"- if self.kind == Integration.IntegrationKind.AWS_REDSHIFT:- name = self.integration_id or "unknown ID"-- account_id = self.config.get("aws_account_id")- role = self.config.get("aws_role_arn")- host = self.config.get("host")- user = self.config.get("user")-- if role:- detail = f"AWS role '{role}'"- elif account_id:- detail = f"AWS account {account_id}"- elif user and host:- detail = f"{user}@{host}"- else:- detail = "access key"-- return f"{name} ({detail})"- if self.kind == Integration.IntegrationKind.S3_COMPATIBLE:- name = self.integration_id or "unknown ID"- endpoint_url = self.config.get("endpoint_url")- detail = f"access key, {endpoint_url}" if endpoint_url else "access key"- return f"{name} ({detail})"- if self.kind == Integration.IntegrationKind.SNOWFLAKE:- name = self.integration_id or "unknown ID"- auth_type = self.config.get("authentication_type", "password")- account = self.config.get("account")- return f"{name} (account: {account}, {auth_type} auth)"- if self.kind == "gitlab":- return self.integration_id or "unknown ID"- if self.kind == "email":- return self.config.get("email", self.integration_id)- if self.kind == "apns":- return self.config.get("bundle_id", self.integration_id)-- return f"ID: {self.integration_id}"-- @property- def access_token(self) -> str | None:- return _decrypted_sensitive_value(self, "access_token")-- @property- def refresh_token(self) -> str | None:- return _decrypted_sensitive_value(self, "refresh_token")---def defer_repository_cache_fields(queryset: models.QuerySet[Integration]) -> models.QuerySet[Integration]:- return queryset.defer("repository_cache", "repository_cache_updated_at")---@database_sync_to_async-def aget_integration_by_id(integration_id: str, team_id: int) -> Integration | None:- return Integration.objects.get(id=integration_id, team_id=team_id)---@frozen-class OauthConfig:- authorize_url: str- token_url: str- client_id: str- client_secret: str = field(repr=False)- scope: str- id_path: str- name_path: str- token_info_url: str | None = None- token_info_graphql_query: str | None = None- token_info_config_fields: list[str] | None = None- additional_authorize_params: dict[str, str] | None = None- client_id_fallback: str | None = None- client_secret_fallback: str | None = field(default=None, repr=False)- # When true, the authorize/token-exchange flow uses PKCE (RFC 7636, S256)- pkce: bool = False- # When set, disconnecting the integration also revokes the grant at the provider- token_revoke_url: str | None = None---# Slack accepts comma-separated scopes on the OAuth authorize URL. The canonical list is the-# StrEnum declared in posthog/schema.py (generated from the SlackIntegrationScope enum in-# frontend/src/types.ts via `hogli build:schema`), so widening it on either side stays in sync.-#-# Every scope here is approved for the public Cloud app, so the same list is requested on every-# instance. Staging a scope Slack hasn't approved needs a DEV/local-only branch again — see the-# note by SlackIntegrationScope in frontend/src/types.ts.-POSTHOG_SLACK_SCOPE = ",".join(scope.value for scope in SlackIntegrationScope)---def _salesforce_instance_host(instance_url: str | None) -> str | None:- # Every Salesforce-issued instance_url host ends in .salesforce.com: login/test, the- # pod hosts (na1.salesforce.com, ...), and My Domain variants like- # acme.my.salesforce.com and acme--sandbox.sandbox.my.salesforce.com. Validating at- # the point of use means a stray write to integration.config can't cause the shared- # SALESFORCE_CONSUMER_SECRET to be POSTed to an attacker origin during a refresh,- # even if a future endpoint or admin tool exposes config as writable. Returns- # "https://<host>" for a legitimate value, None otherwise (caller falls back to the- # hardcoded prod URL).- if not instance_url:- return None- try:- parsed = urlparse(instance_url)- # port/hostname/username/password are lazily parsed from netloc on access, and- # port in particular raises ValueError on a non-numeric or out-of-range value- # (e.g. https://host:abc/). Keep every derived-property read inside the try so a- # poisoned instance_url can never crash the refresh sweep.- if parsed.scheme != "https" or parsed.port is not None or parsed.username or parsed.password:- return None- host = (parsed.hostname or "").lower()- except ValueError:- return None- if not host.endswith(".salesforce.com"):- return None- return f"https://{host}"---# Kinds authorized against Salesforce's OAuth server, so they share its quirks: the token-# response often omits expires_in, and refresh/revoke must go to the org's own instance host-# rather than the hardcoded login host (sandbox orgs reject the prod endpoints).-SALESFORCE_OAUTH_KINDS = ("salesforce", "pardot")---# PostHog connect. Unlike every other OAuth kind — which points at a fixed third-party provider —-# the `posthog` kind points at *another PostHog project*, in a region chosen by the user at connect-# time. That region may differ from the connecting project's or be the same one (same-region is just-# region == your own). So its authorize/token/userinfo URLs and client credentials are resolved per-# target region rather than baked into a static config. The connecting side is the OAuth client; the-# target region is the authorization server (its /oauth/authorize, /oauth/token, /oauth/userinfo,-# /oauth/revoke already exist). `openid`+`email` are always requested on top of the user-selected-# scopes so /oauth/userinfo can identify the connected account (`sub`/`email`).-POSTHOG_CONNECT_KIND = "posthog"-# `DEV` points at a local/self-hosted cell (`POSTHOG_CONNECT_BASE_URL_DEV` defaults to-# http://localhost:8000) and the token exchange is a server-side POST, so a production instance must-# never treat `DEV` as a real, connectable region — otherwise an org member could point the backend-# at a URL of their choosing. Gate it behind an explicit dev/test context rather than relying on the-# client id/secret env vars being unset.-_POSTHOG_CONNECT_ALLOW_DEV = bool(settings.DEBUG or settings.TEST or settings.E2E_TESTING)-POSTHOG_CONNECT_ALLOWED_REGIONS = ("US", "EU", *(("DEV",) if _POSTHOG_CONNECT_ALLOW_DEV else ()))-POSTHOG_CONNECT_DEFAULT_SCOPES = ("task:read", "task:write")-POSTHOG_CONNECT_IDENTITY_SCOPES = ("openid", "email")-# A connection can proxy any request the granted scopes allow, so the user may pick from the full set-# of user-grantable OAuth scopes (the same set the consent screen advertises — excludes internal,-# hidden, and privileged scopes). The real bound is enforced twice more downstream: the target cell's-# OAuthApplication.allowed_scopes at consent time, and the target's per-request scope checks. Identity-# scopes are auto-added and not part of this set.-POSTHOG_CONNECT_GRANTABLE_SCOPES = frozenset(get_oauth_scopes_supported())---def _posthog_connect_target(region: str | None) -> tuple[str, str, str]:- """Resolve (base_url, client_id, client_secret) for a remote target cell.-- Raises NotImplementedError for an unknown or unconfigured region so the connect/refresh- paths fail closed (surfaced to the user as a reconnect error) rather than silently hitting- the wrong cell.- """- normalized = (region or "").upper()- if normalized == "DEV" and not _POSTHOG_CONNECT_ALLOW_DEV:- # Defense in depth: even if a `DEV` region row somehow reaches here in production, refuse to- # resolve it so the backend never POSTs a token exchange to the dev base URL.- raise NotImplementedError("PostHog connect DEV region is only available in dev/test")- targets = {- "US": (- settings.POSTHOG_CONNECT_BASE_URL_US,- settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_US,- settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_US,- ),- "EU": (- settings.POSTHOG_CONNECT_BASE_URL_EU,- settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU,- settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU,- ),- "DEV": (- settings.POSTHOG_CONNECT_BASE_URL_DEV,- settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_DEV,- settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_DEV,- ),- }- if normalized not in targets:- raise NotImplementedError(f"PostHog connect OAuth not supported for region {region!r}")- base_url, client_id, client_secret = targets[normalized]- if not base_url or not client_id or not client_secret:- raise NotImplementedError(f"PostHog connect app not configured for region {normalized}")- return base_url.rstrip("/"), client_id, client_secret---def posthog_connect_base_url(region: str | None) -> str:- """Public base URL of a remote target cell (e.g. https://eu.posthog.com), for callers that- need to reach its API with a `posthog` integration token. Raises for unknown/unconfigured regions."""- base_url, _, _ = _posthog_connect_target(region)- return base_url---class OauthIntegration:- supported_kinds = [- "slack",- "posthog",- "salesforce",- "hubspot",- "google-ads",- "google-analytics",- "google-calendar",- "google-search-console",- "google-sheets",- "snapchat",- "linkedin-ads",- "reddit-ads",- "tiktok-ads",- "bing-ads",- "meta-ads",- "instagram",- "intercom",- "linear",- "clickup",- "jira",- "pardot",- "pinterest-ads",- "stripe",- "resend",- "youtube-analytics",- ]- integration: Integration-- def __str__(self) -> str:- return f"OauthIntegration(integration={self.integration.id}, kind={self.integration.kind}, team={self.integration.team_id})"-- def __init__(self, integration: Integration) -> None:- self.integration = integration-- @classmethod- @cache_for(timedelta(minutes=5))- def oauth_config_for_kind(cls, kind: str, region: str | None = None) -> OauthConfig:- # `region` only applies to the `posthog` remote kind, whose endpoints depend on the- # target cell. cache_for keys on all args, so each (kind, region) pair caches separately;- # every other kind is called without region and keeps its single cached entry.- config = cls._build_oauth_config(kind, region)- fallback = settings.OAUTH_CLIENT_FALLBACKS.get(kind)- if fallback and fallback.get("client_secret"):- config = replace(- config,- client_secret_fallback=fallback["client_secret"],- client_id_fallback=fallback.get("client_id") or config.client_id,- )- return config-- @classmethod- def _build_oauth_config(cls, kind: str, region: str | None = None) -> OauthConfig:- if kind == "posthog":- base_url, client_id, client_secret = _posthog_connect_target(region)- return OauthConfig(- authorize_url=f"{base_url}/oauth/authorize",- token_url=f"{base_url}/oauth/token",- token_info_url=f"{base_url}/oauth/userinfo",- token_info_config_fields=["sub", "email"],- token_revoke_url=f"{base_url}/oauth/revoke",- client_id=client_id,- client_secret=client_secret,- # Default only; authorize_url overrides with the user-selected scopes (plus the- # identity scopes). Token exchange/refresh don't send scope, so this is unused there.- scope=" ".join([*POSTHOG_CONNECT_DEFAULT_SCOPES, *POSTHOG_CONNECT_IDENTITY_SCOPES]),- id_path="sub",- name_path="email",- pkce=True,- )- if kind == "slack":- from_settings = get_instance_settings(- [- "SLACK_APP_CLIENT_ID",- "SLACK_APP_CLIENT_SECRET",- "SLACK_APP_SIGNING_SECRET",- ]- )-- if not from_settings["SLACK_APP_CLIENT_ID"] or not from_settings["SLACK_APP_CLIENT_SECRET"]:- raise NotImplementedError("Slack app not configured")-- return OauthConfig(- authorize_url="https://slack.com/oauth/v2/authorize",- token_url="https://slack.com/api/oauth.v2.access",- client_id=from_settings["SLACK_APP_CLIENT_ID"],- client_secret=from_settings["SLACK_APP_CLIENT_SECRET"],- scope=POSTHOG_SLACK_SCOPE,- id_path="team.id",- name_path="team.name",- )- elif kind == "salesforce":- if not settings.SALESFORCE_CONSUMER_KEY or not settings.SALESFORCE_CONSUMER_SECRET:- raise NotImplementedError("Salesforce app not configured")-- return OauthConfig(- authorize_url="https://login.salesforce.com/services/oauth2/authorize",- token_url="https://login.salesforce.com/services/oauth2/token",- token_revoke_url="https://login.salesforce.com/services/oauth2/revoke",- client_id=settings.SALESFORCE_CONSUMER_KEY,- client_secret=settings.SALESFORCE_CONSUMER_SECRET,- scope="full refresh_token",- id_path="instance_url",- name_path="instance_url",- pkce=True,- )- elif kind == "salesforce-sandbox":- if not settings.SALESFORCE_CONSUMER_KEY or not settings.SALESFORCE_CONSUMER_SECRET:- raise NotImplementedError("Salesforce app not configured")-- return OauthConfig(- authorize_url="https://test.salesforce.com/services/oauth2/authorize",- token_url="https://test.salesforce.com/services/oauth2/token",- token_revoke_url="https://test.salesforce.com/services/oauth2/revoke",- client_id=settings.SALESFORCE_CONSUMER_KEY,- client_secret=settings.SALESFORCE_CONSUMER_SECRET,- scope="full refresh_token",- id_path="instance_url",- name_path="instance_url",- pkce=True,- )- elif kind == "pardot":- if not settings.SALESFORCE_CONSUMER_KEY or not settings.SALESFORCE_CONSUMER_SECRET:- raise NotImplementedError("Salesforce app not configured")-- # Account Engagement (formerly Pardot) authorizes against Salesforce, so this reuses the- # Salesforce connected app rather than registering a second one. It needs its own kind- # because `pardot_api` is not covered by the `full` scope the `salesforce` kind requests:- # a Salesforce integration authorized for the CRM cannot call the Account Engagement API,- # and a token scoped for Account Engagement should not appear in the CRM picker.- return OauthConfig(- authorize_url="https://login.salesforce.com/services/oauth2/authorize",- token_url="https://login.salesforce.com/services/oauth2/token",- token_revoke_url="https://login.salesforce.com/services/oauth2/revoke",- client_id=settings.SALESFORCE_CONSUMER_KEY,- client_secret=settings.SALESFORCE_CONSUMER_SECRET,- scope="pardot_api refresh_token",- id_path="instance_url",- name_path="instance_url",- pkce=True,- )- elif kind == "hubspot":- if not settings.HUBSPOT_APP_CLIENT_ID or not settings.HUBSPOT_APP_CLIENT_SECRET:- raise NotImplementedError("Hubspot app not configured")-- return OauthConfig(- authorize_url="https://app.hubspot.com/oauth/authorize",- token_url="https://api.hubapi.com/oauth/v1/token",- token_info_url="https://api.hubapi.com/oauth/v1/access-tokens/:access_token",- token_info_config_fields=["hub_id", "hub_domain", "user", "user_id", "scopes"],- client_id=settings.HUBSPOT_APP_CLIENT_ID,- client_secret=settings.HUBSPOT_APP_CLIENT_SECRET,- scope="tickets crm.objects.contacts.write sales-email-read crm.objects.companies.read crm.objects.deals.read crm.objects.contacts.read crm.objects.quotes.read crm.objects.companies.write",- additional_authorize_params={- # NOTE: these scopes are only available on certain hubspot plans and as such are optional.- # crm.objects.leads.read is Sales Hub Pro+/Enterprise only — requesting it as a- # mandatory scope would fail the whole authorization for portals that lack it.- # The owners/commerce/product scopes are the same story: the data warehouse- # source offers those tables, but the objects only exist on portals with the- # matching hub, so they stay optional and their tables start deselected.- "optional_scope": (- "analytics.behavioral_events.send behavioral_events.event_definitions.read_write "- "crm.objects.leads.read crm.objects.owners.read crm.objects.line_items.read "- "crm.objects.products.read crm.objects.invoices.read crm.objects.orders.read "- "crm.objects.subscriptions.read crm.objects.commercepayments.read"- )- },- id_path="hub_id",- name_path="hub_domain",- )- elif kind == "google-ads":- if not settings.GOOGLE_ADS_APP_CLIENT_ID or not settings.GOOGLE_ADS_APP_CLIENT_SECRET:- raise NotImplementedError("Google Ads app not configured")-- return OauthConfig(- authorize_url="https://accounts.google.com/o/oauth2/v2/auth",- # forces the consent screen, otherwise we won't receive a refresh token- additional_authorize_params={"access_type": "offline", "prompt": "consent"},- token_info_url="https://openidconnect.googleapis.com/v1/userinfo",- token_info_config_fields=["sub", "email"],- token_url="https://oauth2.googleapis.com/token",- client_id=settings.GOOGLE_ADS_APP_CLIENT_ID,- client_secret=settings.GOOGLE_ADS_APP_CLIENT_SECRET,- scope="https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/userinfo.email",- id_path="sub",- name_path="email",- )- elif kind == "google-analytics":- if not settings.GOOGLE_ANALYTICS_APP_CLIENT_ID or not settings.GOOGLE_ANALYTICS_APP_CLIENT_SECRET:- raise NotImplementedError("Google Analytics app not configured")-- return OauthConfig(- authorize_url="https://accounts.google.com/o/oauth2/v2/auth",- # forces the consent screen, otherwise we won't receive a refresh token- additional_authorize_params={"access_type": "offline", "prompt": "consent"},- token_info_url="https://openidconnect.googleapis.com/v1/userinfo",- token_info_config_fields=["sub", "email"],- token_url="https://oauth2.googleapis.com/token",- client_id=settings.GOOGLE_ANALYTICS_APP_CLIENT_ID,- client_secret=settings.GOOGLE_ANALYTICS_APP_CLIENT_SECRET,- scope="https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/userinfo.email",- id_path="sub",- name_path="email",- )- elif kind == "google-calendar":- if not settings.GOOGLE_CALENDAR_APP_CLIENT_ID or not settings.GOOGLE_CALENDAR_APP_CLIENT_SECRET:- raise NotImplementedError("Google Calendar app not configured")-- return OauthConfig(- authorize_url="https://accounts.google.com/o/oauth2/v2/auth",- # forces the consent screen, otherwise we won't receive a refresh token- additional_authorize_params={"access_type": "offline", "prompt": "consent"},- token_info_url="https://openidconnect.googleapis.com/v1/userinfo",- token_info_config_fields=["sub", "email"],- token_url="https://oauth2.googleapis.com/token",- client_id=settings.GOOGLE_CALENDAR_APP_CLIENT_ID,- client_secret=settings.GOOGLE_CALENDAR_APP_CLIENT_SECRET,- scope="https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/userinfo.email",- id_path="sub",- name_path="email",- )- elif kind == "google-search-console":- if not settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID or not settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET:- raise NotImplementedError("Google Search Console app not configured")-- return OauthConfig(- authorize_url="https://accounts.google.com/o/oauth2/v2/auth",- additional_authorize_params={"access_type": "offline", "prompt": "consent"},- token_info_url="https://openidconnect.googleapis.com/v1/userinfo",- token_info_config_fields=["sub", "email"],- token_url="https://oauth2.googleapis.com/token",- client_id=settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID,- client_secret=settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET,- scope="https://www.googleapis.com/auth/webmasters.readonly https://www.googleapis.com/auth/userinfo.email",- id_path="sub",- name_path="email",- )- elif kind == "google-sheets":- if not settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY or not settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET:- raise NotImplementedError("Google Sheets app not configured")-- return OauthConfig(- authorize_url="https://accounts.google.com/o/oauth2/v2/auth",- # forces the consent screen, otherwise we won't receive a refresh token- additional_authorize_params={"access_type": "offline", "prompt": "consent"},- token_info_url="https://openidconnect.googleapis.com/v1/userinfo",- token_info_config_fields=["sub", "email"],- token_url="https://oauth2.googleapis.com/token",- client_id=settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY,- client_secret=settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET,- scope="https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/userinfo.email",- id_path="sub",- name_path="email",- )- elif kind == "youtube-analytics":- if not settings.YOUTUBE_ANALYTICS_APP_CLIENT_ID or not settings.YOUTUBE_ANALYTICS_APP_CLIENT_SECRET:- raise NotImplementedError("YouTube Analytics app not configured")-- return OauthConfig(- authorize_url="https://accounts.google.com/o/oauth2/v2/auth",- # forces the consent screen, otherwise we won't receive a refresh token- additional_authorize_params={"access_type": "offline", "prompt": "consent"},- token_info_url="https://openidconnect.googleapis.com/v1/userinfo",- token_info_config_fields=["sub", "email"],- token_url="https://oauth2.googleapis.com/token",- client_id=settings.YOUTUBE_ANALYTICS_APP_CLIENT_ID,- client_secret=settings.YOUTUBE_ANALYTICS_APP_CLIENT_SECRET,- # `yt-analytics.readonly` reads the reports; `youtube.readonly` lists the account's- # channels so the user picks one instead of hunting for its ID. Channel reports carry- # no revenue metrics, so `yt-analytics-monetary.readonly` is deliberately not asked for.- scope=(- "https://www.googleapis.com/auth/yt-analytics.readonly "- "https://www.googleapis.com/auth/youtube.readonly "- "https://www.googleapis.com/auth/userinfo.email"- ),- id_path="sub",- name_path="email",- )- elif kind == "snapchat":- if not settings.SNAPCHAT_APP_CLIENT_ID or not settings.SNAPCHAT_APP_CLIENT_SECRET:- raise NotImplementedError("Snapchat app not configured")-- return OauthConfig(- authorize_url="https://accounts.snapchat.com/accounts/oauth2/auth",- token_url="https://accounts.snapchat.com/accounts/oauth2/token",- token_info_url="https://adsapi.snapchat.com/v1/me",- token_info_config_fields=["me.id", "me.email"],- client_id=settings.SNAPCHAT_APP_CLIENT_ID,- client_secret=settings.SNAPCHAT_APP_CLIENT_SECRET,- scope="snapchat-offline-conversions-api snapchat-marketing-api",- id_path="me.id",- name_path="me.email",- )- elif kind == "linkedin-ads":- if not settings.LINKEDIN_APP_CLIENT_ID or not settings.LINKEDIN_APP_CLIENT_SECRET:- raise NotImplementedError("LinkedIn Ads app not configured")-- # Note: We extract user info from id_token JWT instead of calling token_info_url- # because LinkedIn's /v2/userinfo endpoint has intermittent issues returning- # REVOKED_ACCESS_TOKEN errors for valid tokens. See JWT extraction below.- return OauthConfig(- authorize_url="https://www.linkedin.com/oauth/v2/authorization",- token_url="https://www.linkedin.com/oauth/v2/accessToken",- client_id=settings.LINKEDIN_APP_CLIENT_ID,- client_secret=settings.LINKEDIN_APP_CLIENT_SECRET,- scope="r_ads rw_conversions r_ads_reporting openid profile email",- id_path="sub",- name_path="email",- )- elif kind == "bing-ads":- if not settings.BING_ADS_CLIENT_ID or not settings.BING_ADS_CLIENT_SECRET:- raise NotImplementedError("Bing Ads app not configured")-- return OauthConfig(- authorize_url="https://login.microsoftonline.com/common/oauth2/v2.0/authorize",- token_url="https://login.microsoftonline.com/common/oauth2/v2.0/token",- client_id=settings.BING_ADS_CLIENT_ID,- client_secret=settings.BING_ADS_CLIENT_SECRET,- scope="https://ads.microsoft.com/msads.manage offline_access openid profile",- id_path="id",- name_path="userPrincipalName",- )- elif kind == "intercom":- if not settings.INTERCOM_APP_CLIENT_ID or not settings.INTERCOM_APP_CLIENT_SECRET:- raise NotImplementedError("Intercom app not configured")-- return OauthConfig(- authorize_url="https://app.intercom.com/oauth",- token_url="https://api.intercom.io/auth/eagle/token",- token_info_url="https://api.intercom.io/me",- token_info_config_fields=["id", "email", "app.region"],- client_id=settings.INTERCOM_APP_CLIENT_ID,- client_secret=settings.INTERCOM_APP_CLIENT_SECRET,- scope="",- id_path="id",- name_path="email",- )- elif kind == "linear":- if not settings.LINEAR_APP_CLIENT_ID or not settings.LINEAR_APP_CLIENT_SECRET:- raise NotImplementedError("Linear app not configured")-- return OauthConfig(- authorize_url="https://linear.app/oauth/authorize",- additional_authorize_params={"actor": "application"},- token_url="https://api.linear.app/oauth/token",- token_info_url="https://api.linear.app/graphql",- token_info_graphql_query="{ viewer { organization { id name urlKey } } }",- token_info_config_fields=[- "data.viewer.organization.id",- "data.viewer.organization.name",- "data.viewer.organization.urlKey",- ],- client_id=settings.LINEAR_APP_CLIENT_ID,- client_secret=settings.LINEAR_APP_CLIENT_SECRET,- scope="read issues:create",- id_path="data.viewer.organization.id",- name_path="data.viewer.organization.name",- )- elif kind == "meta-ads":- if not settings.META_ADS_APP_CLIENT_ID or not settings.META_ADS_APP_CLIENT_SECRET:- raise NotImplementedError("Meta Ads app not configured")-- return OauthConfig(- authorize_url=f"https://www.facebook.com/{MetaAdsIntegration.api_version}/dialog/oauth",- token_url=f"https://graph.facebook.com/{MetaAdsIntegration.api_version}/oauth/access_token",- token_info_url=f"https://graph.facebook.com/{MetaAdsIntegration.api_version}/me",- token_info_config_fields=["id", "name", "email"],- client_id=settings.META_ADS_APP_CLIENT_ID,- client_secret=settings.META_ADS_APP_CLIENT_SECRET,- scope="ads_read",- id_path="id",- name_path="name",- )- elif kind == "instagram":- if not settings.INSTAGRAM_APP_CLIENT_ID or not settings.INSTAGRAM_APP_CLIENT_SECRET:- raise NotImplementedError("Instagram app not configured")-- # Same Facebook Login endpoints as Meta Ads, and the credentials may even be the same- # Meta app, but the two grants request different scopes so they stay separate kinds.- # The token response carries no account identifier, so id/name come from `/me`.- return OauthConfig(- authorize_url=f"https://www.facebook.com/{InstagramIntegration.api_version}/dialog/oauth",- token_url=f"https://graph.facebook.com/{InstagramIntegration.api_version}/oauth/access_token",- token_info_url=f"https://graph.facebook.com/{InstagramIntegration.api_version}/me",- token_info_config_fields=["id", "name"],- client_id=settings.INSTAGRAM_APP_CLIENT_ID,- client_secret=settings.INSTAGRAM_APP_CLIENT_SECRET,- scope=INSTAGRAM_OAUTH_SCOPE,- id_path="id",- name_path="name",- )- elif kind == "reddit-ads":- if not settings.REDDIT_ADS_CLIENT_ID or not settings.REDDIT_ADS_CLIENT_SECRET:- raise NotImplementedError("Reddit Ads app not configured")-- return OauthConfig(- authorize_url="https://www.reddit.com/api/v1/authorize",- token_url="https://www.reddit.com/api/v1/access_token",- client_id=settings.REDDIT_ADS_CLIENT_ID,- client_secret=settings.REDDIT_ADS_CLIENT_SECRET,- scope="read adsread adsconversions history adsedit",- id_path="reddit_user_id", # We'll extract this from JWT- # ads-api /me returns the human-readable username under the granted ads scopes- # (oauth.reddit.com/api/v1/me would need the extra `identity` scope), wrapped in a- # `data` object. Falls back to the JWT user id when absent.- token_info_url="https://ads-api.reddit.com/api/v3/me",- token_info_config_fields=["data.reddit_username"],- name_path="data.reddit_username",- additional_authorize_params={"duration": "permanent"},- )- elif kind == "tiktok-ads":- if not settings.TIKTOK_ADS_CLIENT_ID or not settings.TIKTOK_ADS_CLIENT_SECRET:- raise NotImplementedError("TikTok Ads app not configured")-- return OauthConfig(- authorize_url="https://business-api.tiktok.com/portal/auth",- token_url="https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/",- client_id=settings.TIKTOK_ADS_CLIENT_ID,- client_secret=settings.TIKTOK_ADS_CLIENT_SECRET,- scope="",- id_path="data.advertiser_ids",- name_path="data.advertiser_ids",- )- elif kind == "clickup":- if not settings.CLICKUP_APP_CLIENT_ID or not settings.CLICKUP_APP_CLIENT_SECRET:- raise NotImplementedError("ClickUp app not configured")-- return OauthConfig(- authorize_url="https://app.clickup.com/api",- token_url="https://api.clickup.com/api/v2/oauth/token",- token_info_url="https://api.clickup.com/api/v2/user",- token_info_config_fields=["user.id", "user.email"],- client_id=settings.CLICKUP_APP_CLIENT_ID,- client_secret=settings.CLICKUP_APP_CLIENT_SECRET,- scope="",- id_path="user.id",- name_path="user.email",- )- elif kind == "jira":- if not settings.ATLASSIAN_APP_CLIENT_ID or not settings.ATLASSIAN_APP_CLIENT_SECRET:- raise NotImplementedError("Atlassian/Jira app not configured")-- return OauthConfig(- authorize_url="https://auth.atlassian.com/authorize",- additional_authorize_params={"audience": "api.atlassian.com", "prompt": "consent"},- token_url="https://auth.atlassian.com/oauth/token",- token_info_url="https://api.atlassian.com/oauth/token/accessible-resources",- token_info_config_fields=[], # Handled specially in integration_from_oauth_response- client_id=settings.ATLASSIAN_APP_CLIENT_ID,- client_secret=settings.ATLASSIAN_APP_CLIENT_SECRET,- scope="read:jira-work write:jira-work offline_access",- id_path="cloud_id",- name_path="site_name",- )- elif kind == "pinterest-ads":- if not settings.PINTEREST_ADS_CLIENT_ID or not settings.PINTEREST_ADS_CLIENT_SECRET:- raise NotImplementedError("Pinterest Ads app not configured")-- return OauthConfig(- authorize_url="https://www.pinterest.com/oauth/",- token_url="https://api.pinterest.com/v5/oauth/token",- token_info_url="https://api.pinterest.com/v5/user_account",- token_info_config_fields=["id", "username", "business_name"],- client_id=settings.PINTEREST_ADS_CLIENT_ID,- client_secret=settings.PINTEREST_ADS_CLIENT_SECRET,- scope="ads:read user_accounts:read",- id_path="id",- name_path="username",- )- elif kind == "stripe":- if not settings.STRIPE_APP_CLIENT_ID or not settings.STRIPE_APP_SECRET_KEY:- raise NotImplementedError("Stripe app not configured")-- client_id = settings.STRIPE_APP_CLIENT_ID- client_secret = settings.STRIPE_APP_SECRET_KEY-- authorize_url = (- settings.STRIPE_APP_OVERRIDE_AUTHORIZE_URL or "https://marketplace.stripe.com/oauth/v2/authorize"- )- return OauthConfig(- authorize_url=authorize_url,- token_url="https://api.stripe.com/v1/oauth/token",- client_id=client_id,- client_secret=client_secret,- scope="",- id_path="stripe_user_id",- name_path="account_name",- )- elif kind == "resend":- if not settings.RESEND_APP_CLIENT_ID or not settings.RESEND_APP_CLIENT_SECRET:- raise NotImplementedError("Resend app not configured")-- # Resend implements OAuth 2.1: PKCE is required, and access tokens are short-lived- # (~15m) JWTs while refresh tokens rotate on every use. We register as a confidential- # client (token_endpoint_auth_method=client_secret_post), so the standard client_secret- # token-exchange/refresh path applies on top of PKCE. `full_access` is the scope needed- # to read the warehouse resources (emails/audiences/contacts/domains/broadcasts).- # The token response carries no account identifier, so id/name are derived from the- # access-token JWT below (see the resend branch in integration_from_oauth_response).- return OauthConfig(- authorize_url="https://resend.com/oauth/authorize",- token_url="https://api.resend.com/oauth/token",- token_revoke_url="https://api.resend.com/oauth/revoke",- client_id=settings.RESEND_APP_CLIENT_ID,- client_secret=settings.RESEND_APP_CLIENT_SECRET,- scope="full_access",- pkce=True,- id_path="resend_account_id",- name_path="resend_account_name",- )-- raise NotImplementedError(f"Oauth config for kind {kind} not implemented")-- @classmethod- def redirect_uri(cls, kind: str) -> str:- # The redirect uri is fixed but should always be https and include the "next" parameter for the frontend to redirect- if settings.DEBUG and settings.NGROK_URL:- return f"{settings.NGROK_URL}/integrations/{kind}/callback"- return f"{settings.SITE_URL.replace('http://', 'https://')}/integrations/{kind}/callback"-- @classmethod- def authorize_url(- cls,- kind: str,- token: str,- next: str = "",- *,- region: str | None = None,- scopes: list[str] | None = None,- team_id: int | None = None,- ) -> str:- oauth_config = cls.oauth_config_for_kind(kind, region)-- # Carry the initiating team through the OAuth round-trip. The fixed callback URL is not- # project-scoped, so without this the SPA re-resolves to the user's default team on- # reload and the integration lands on the wrong project.- state_payload: dict[str, str] = {"next": next, "token": token}- if team_id is not None:- state_payload["team_id"] = str(team_id)-- scope = oauth_config.scope- if kind == "posthog":- # The target cell is the authorization server, so the callback (which runs on the- # connecting cell) needs to know which region to exchange the code against — carry it- # in state. Always append the identity scopes so /oauth/userinfo can name the account.- state_payload["region"] = (region or "").upper()- requested = list(scopes) if scopes else list(POSTHOG_CONNECT_DEFAULT_SCOPES)- scope = " ".join(dict.fromkeys([*requested, *POSTHOG_CONNECT_IDENTITY_SCOPES]))-- if kind == "tiktok-ads":- # TikTok uses different parameter names- query_params = {- "app_id": oauth_config.client_id,- "redirect_uri": cls.redirect_uri(kind),- "state": urlencode(state_payload),- }- else:- query_params = {- "client_id": oauth_config.client_id,- "scope": scope,- "redirect_uri": cls.redirect_uri(kind),- "response_type": "code",- "state": urlencode(state_payload),- **(oauth_config.additional_authorize_params or {}),- }-- if oauth_config.pkce:- # The verifier is cached against the state token so the token exchange —- # a separate request via the frontend callback — can retrieve it.- code_verifier = secrets.token_urlsafe(64)- code_challenge = (- base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).rstrip(b"=").decode()- )- query_params["code_challenge"] = code_challenge- query_params["code_challenge_method"] = "S256"- cache.set(f"oauth_pkce_verifier/{token}", code_verifier, timeout=60 * 5)-- return f"{oauth_config.authorize_url}?{urlencode(query_params)}"-- @classmethod- def integration_from_oauth_response(- cls, kind: str, team_id: int, created_by: User, params: dict[str, str]- ) -> Integration:- region: str | None = None- if kind == "posthog":- # The target region was stashed in state at authorize time; the token exchange must hit- # that same cell. Missing/invalid region fails closed via _posthog_connect_target.- region = (parse_qs(params.get("state", "")).get("region", [""])[0] or "").upper()-- oauth_config = cls.oauth_config_for_kind(kind, region)-- code_verifier: str | None = None- if oauth_config.pkce:- state_token = parse_qs(params.get("state", "")).get("token", [""])[0]- if state_token:- verifier_cache_key = f"oauth_pkce_verifier/{state_token}"- code_verifier = cache.get(verifier_cache_key)- cache.delete(verifier_cache_key) # single-use, per RFC 7636- # Missing verifier still exchanges without PKCE (Salesforce accepts that until it- # requires PKCE). Log it so the gap is visible before we enforce PKCE provider-side.- if not code_verifier:- logger.warning("oauth_pkce_verifier_missing", kind=kind, has_state_token=bool(state_token))- # posthog is a first-party flow we control both ends of — a missing verifier is never- # a legacy-provider compat case here, so fail closed rather than exchanging without PKCE.- if kind == "posthog":- raise ValidationError("Remote authorization failed: missing PKCE verifier. Please retry.")-- # Reddit uses HTTP Basic Auth https://github.com/reddit-archive/reddit/wiki/OAuth2 and requires a User-Agent header- if kind == "reddit-ads":- res = requests.post(- oauth_config.token_url,- auth=HTTPBasicAuth(oauth_config.client_id, oauth_config.client_secret),- data={- "code": params["code"],- "redirect_uri": OauthIntegration.redirect_uri(kind),- "grant_type": "authorization_code",- },- headers={"User-Agent": "PostHog/1.0 by PostHogTeam"},- timeout=10,- )- # Pinterest uses HTTP Basic Auth for token exchange (base64-encoded client_id:client_secret)- elif kind == "pinterest-ads":- res = requests.post(- oauth_config.token_url,- auth=HTTPBasicAuth(oauth_config.client_id, oauth_config.client_secret),- data={- "code": params["code"],- "redirect_uri": OauthIntegration.redirect_uri(kind),- "grant_type": "authorization_code",- },- timeout=10,- )- elif kind == "tiktok-ads":- # TikTok Ads uses JSON request body instead of form data and maps 'code' to 'auth_code'- res = requests.post(- oauth_config.token_url,- json={- "app_id": oauth_config.client_id,- "secret": oauth_config.client_secret,- "auth_code": params["code"],- },- headers={"Content-Type": "application/json"},- timeout=10,- )- elif kind == "stripe":- # Stripe Apps OAuth authenticates with the developer secret key as HTTP Basic- # username and does not accept client_id/redirect_uri in the token-exchange body.- # Connect OAuth (client_id+client_secret in body) is a different system.- res = requests.post(- oauth_config.token_url,- auth=HTTPBasicAuth(oauth_config.client_secret, ""),- data={- "code": params["code"],- "grant_type": "authorization_code",- },- timeout=10,- )- else:- redirect_uri = OauthIntegration.redirect_uri(kind)- res = requests.post(- oauth_config.token_url,- data={- "client_id": oauth_config.client_id,- "client_secret": oauth_config.client_secret,- "code": params["code"],- "redirect_uri": redirect_uri,- "grant_type": "authorization_code",- **({"code_verifier": code_verifier} if code_verifier else {}),- },- timeout=10,- # allow_redirects=False so a misconfigured/compromised token endpoint can't 30x us- # into resending client_secret + authorization code to another origin.- allow_redirects=False,- )-- if kind == "slack":- record_slack_api_response(- res,- source="oauth",- workspace_id=None,- app_id="posthog",- method="POST",- endpoint="oauth.v2.access",- )-- try:- config: dict = res.json()- except ValueError:- # Non-JSON body (e.g. an HTML 502 from a proxy). Keep going so the status-code- # branch below can surface a structured ValidationError to the frontend.- config = {}-- access_token = None- if kind == "tiktok-ads":- # TikTok has a different response format - access_token is nested under 'data'- access_token = config.get("data", {}).get("access_token")- else:- access_token = config.get("access_token")-- if res.status_code != 200 or not access_token:- # Hack to try getting sandbox auth token instead of their salesforce production account- if kind == "salesforce":- oauth_config = cls.oauth_config_for_kind("salesforce-sandbox")- res = requests.post(- oauth_config.token_url,- data={- "client_id": oauth_config.client_id,- "client_secret": oauth_config.client_secret,- "code": params["code"],- "redirect_uri": OauthIntegration.redirect_uri(kind),- "grant_type": "authorization_code",- **({"code_verifier": code_verifier} if code_verifier else {}),- },- timeout=10,- )-- try:- config = res.json()- except ValueError:- config = {}-- if res.status_code != 200 or not config.get("access_token"):- logger.error(f"Oauth error for {kind}", response=res.text)- _raise_oauth_validation_error(kind, res)- else:- # Include request context so on-call can compare what we sent against what- # the merchant authorized with in Stripe. Code prefix only, full grant is- # short-lived but still a credential during its TTL. Never log client_secret.- logger.error(- f"Oauth error for {kind}",- response=res.text,- status_code=res.status_code,- client_id=oauth_config.client_id,- redirect_uri=OauthIntegration.redirect_uri(kind),- code_prefix=str(params.get("code", ""))[:12],- )- # Surface the provider's error to the frontend toast — without this, DRF turns- # the bare Exception into a generic 500 and the user sees "Something went wrong"- # with no actionable detail. ValidationError → 400 with `detail` set.- _raise_oauth_validation_error(kind, res)-- if oauth_config.token_info_url:- # If token info url is given we call it and check the integration id from there- if oauth_config.token_info_graphql_query:- token_info_res = requests.post(- oauth_config.token_info_url,- headers={"Authorization": f"Bearer {config['access_token']}"},- json={"query": oauth_config.token_info_graphql_query},- timeout=10,- # This call carries the access token; don't let a misconfigured/compromised- # provider 30x us into resending it to another origin (matches the exchange/refresh/revoke calls).- allow_redirects=False,- )- else:- token_info_res = requests.get(- oauth_config.token_info_url.replace(":access_token", config["access_token"]),- headers={"Authorization": f"Bearer {config['access_token']}"},- timeout=10,- allow_redirects=False,- )-- if token_info_res.status_code == 200:- data = token_info_res.json()-- # Jira returns an array of accessible resources, extract the first one- if kind == "jira" and isinstance(data, list):- if len(data) > 0:- site = data[0]- config["cloud_id"] = site.get("id")- config["site_name"] = site.get("name")- config["site_url"] = site.get("url")- else:- logger.error(- "Jira OAuth returned empty accessible resources array - user may not have access to any Jira sites",- kind=kind,- )- raise ValidationError(- "No accessible Jira sites found. Please ensure your Atlassian account has access to at least one Jira site."- )- elif oauth_config.token_info_config_fields:- for field in oauth_config.token_info_config_fields:- config[field] = dot_get(data, field)- else:- logger.error(- f"OAuth token_info request failed for {kind}",- token_info_url=oauth_config.token_info_url,- status_code=token_info_res.status_code,- response=token_info_res.text[:500],- )-- integration_id = dot_get(config, oauth_config.id_path)-- # Bing Ads id_token is a JWT, extract user ID from it- if kind == "bing-ads" and not integration_id:- try:- id_token = config.get("id_token")- if id_token:- jwt_data = _decode_jwt_payload(id_token)- if jwt_data:- bing_user_id = jwt_data.get("oid")- bing_username = jwt_data.get("preferred_username")- if bing_user_id:- config["id"] = bing_user_id- config["userPrincipalName"] = bing_username- integration_id = bing_user_id- else:- logger.error("Bing Ads OAuth response missing id_token", config_keys=list(config.keys()))- except Exception:- logger.exception("Failed to decode Bing Ads JWT")-- # Reddit access token is a JWT, extract user ID from it- if kind == "reddit-ads" and not integration_id:- try:- access_token = config.get("access_token")- if access_token:- jwt_data = _decode_jwt_payload(access_token)- if jwt_data:- # Extract user ID from JWT (lid = login ID)- reddit_user_id = jwt_data.get("lid", jwt_data.get("aid"))- if reddit_user_id:- config["reddit_user_id"] = reddit_user_id- integration_id = reddit_user_id- except Exception as e:- logger.exception("Failed to decode Reddit JWT", error=str(e))-- # Resend's token response carries no account identifier, but the access token is a JWT.- # Derive the integration id/name from its claims (`sub` is the account subject; email/name- # are used for a human-readable label when present). Assumes the standard `sub` claim — if- # Resend uses a different claim, the missing-id guard below raises and the user sees a clear- # reconnect error rather than a silently mislabeled integration.- if kind == "resend" and not integration_id:- try:- access_token = config.get("access_token")- if access_token:- jwt_data = _decode_jwt_payload(access_token)- if jwt_data:- resend_account_id = jwt_data.get("sub")- if resend_account_id:- config["resend_account_id"] = resend_account_id- config["resend_account_name"] = (- jwt_data.get("email") or jwt_data.get("name") or f"Resend account {resend_account_id}"- )- integration_id = resend_account_id- else:- logger.error("Resend OAuth response missing access_token", config_keys=list(config.keys()))- except Exception:- logger.exception("Failed to decode Resend JWT")-- # LinkedIn id_token is a JWT, extract user ID and email from it- # This avoids calling /v2/userinfo which has intermittent REVOKED_ACCESS_TOKEN errors- if kind == "linkedin-ads" and not integration_id:- try:- id_token = config.get("id_token")- if id_token:- jwt_data = _decode_jwt_payload(id_token)- if jwt_data:- linkedin_user_id = jwt_data.get("sub")- linkedin_email = jwt_data.get("email")- if linkedin_user_id:- config["sub"] = linkedin_user_id- config["email"] = linkedin_email- integration_id = linkedin_user_id- else:- logger.error("LinkedIn Ads OAuth response missing id_token", config_keys=list(config.keys()))- except Exception:- logger.exception("Failed to decode LinkedIn JWT")-- # Stripe OAuth returns stripe_user_id but no account name — fetch it from the Accounts API- if kind == "stripe" and integration_id:- try:- from stripe import StripeClient # noqa: PLC0415-- stripe_client = StripeClient(oauth_config.client_secret)- account = stripe_client.accounts.retrieve(str(integration_id))- business_profile = getattr(account, "business_profile", None)- business_name = getattr(business_profile, "name", None) if business_profile else None- company = getattr(account, "company", None)- company_name = getattr(company, "name", None) if company else None- account_name = business_name or company_name or getattr(account, "email", None) or str(integration_id)- config["account_name"] = f"{account_name} ({integration_id})"- except Exception:- logger.exception("Failed to fetch Stripe account name")- config["account_name"] = str(integration_id)-- # Persist the target region and namespace the dedup key by it, so the same PostHog account- # connected in two different cells yields two distinct integrations instead of colliding on- # `sub`. `region` also drives config/refresh/revoke lookups for the lifetime of the row.- if kind == "posthog" and integration_id:- config["region"] = region- integration_id = f"{region}:{integration_id}"- # Persist the resource scopes the target actually granted (obj:action only, dropping the- # openid/email identity scopes). The connection proxy uses this to require a caller's own- # token to cover these scopes before it will wield the connection's grant.- config["granted_scopes"] = sorted({s for s in (config.get("scope") or "").split() if ":" in s})-- # TikTok can complete OAuth without the user granting any advertiser account, leaving- # `advertiser_ids` empty. Surface an actionable reconnect message rather than the generic- # "failed to extract integration ID" 500 the guard below would otherwise raise.- if kind == "tiktok-ads" and isinstance(integration_id, list) and len(integration_id) == 0:- raise ValidationError(- "No TikTok ad accounts were authorized. In TikTok, grant access to at least one "- "advertiser account, then reconnect."- )-- if isinstance(integration_id, int):- integration_id = str(integration_id)- elif isinstance(integration_id, list) and len(integration_id) > 0:- integration_id = ",".join(str(item) for item in integration_id)-- if not isinstance(integration_id, str):- raise Exception(f"Oauth error: failed to extract integration ID for {kind}")-- # Handle TikTok's nested response format- if kind == "tiktok-ads":- data = config.pop("data", {})- # Move other data fields to main config for TikTok- config.update(data)- # Best-effort: fetch who authorized this, so it isn't listed as a row of advertiser ids.- try:- user_res = requests.get(- "https://business-api.tiktok.com/open_api/v1.3/user/info/",- headers={"Access-Token": config["access_token"]},- timeout=10,- )- # TikTok answers 200 even when the call failed; the body `code` (0 = OK) is the outcome.- body = user_res.json()- if body.get("code") == 0:- user = body.get("data") or {}- if user.get("email"):- config["user_email"] = user["email"]- if user.get("display_name"):- config["user_display_name"] = user["display_name"]- except Exception:- logger.warning("Failed to fetch TikTok user info for display name")-- sensitive_config: dict = {- "access_token": config.pop("access_token"),- # NOTE: We don't actually use the refresh and id tokens (typically they aren't even provided for this sort of service auth)- # but we ensure they are popped and stored in sensitive config to avoid accidental exposure- "refresh_token": config.pop("refresh_token", None),- "id_token": config.pop("id_token", None),- }-- # Handle case where Salesforce doesn't provide expires_in in initial response- if not config.get("expires_in") and kind in SALESFORCE_OAUTH_KINDS:- # Default to 1 hour for Salesforce if not provided (conservative)- config["expires_in"] = 3600-- # Stripe Apps OAuth tokens don't include expires_in in the response- if not config.get("expires_in") and kind == "stripe":- config["expires_in"] = 3600-- config["refreshed_at"] = int(time.time())-- integration, created = Integration.objects.update_or_create(- team_id=team_id,- kind=kind,- integration_id=integration_id,- defaults={- "config": config,- "sensitive_config": sensitive_config,- "created_by": created_by,- },- )-- if integration.errors:- integration.errors = ""- integration.save()-- if kind == "slack":- # The cached auth verdict in slack_app is per-integration. A- # reconnect mints a new bot token, so any stale ``ok=false`` row- # from the previous token would silently demote this install for- # the remaining cache TTL. Inline-imported to keep the slack_app- # module off the core django.setup() path; wrapped so a broken- # slack_app build can't take down OAuth completion for every- # integration kind.- try:- from products.slack_app.backend.facade.api import ( # noqa: PLC0415- invalidate_slack_integration_auth_state,- )-- invalidate_slack_integration_auth_state(integration.id)- except Exception:- logger.warning(- "slack_app_auth_state_invalidation_on_oauth_failed",- integration_id=integration.id,- exc_info=True,- )-- return integration-- def revoke_token(self) -> None:- """Revoke the OAuth grant at the provider, for kinds with a revoke endpoint.-- Revoking the refresh token also invalidates its access tokens (per RFC 7009 and- Salesforce's revoke semantics), so the provider no longer considers PostHog authorized- after a disconnect. Callers treat this as best-effort — the local deletion proceeds- regardless.- """- region = self.integration.config.get("region") if self.integration.kind == "posthog" else None- oauth_config = self.oauth_config_for_kind(self.integration.kind, region)- if not oauth_config.token_revoke_url:- return-- # Prefer the refresh token: revoking it invalidates the whole grant (and its access- # tokens), so an attacker holding it can't keep minting access tokens after disconnect.- refresh_token = self.integration.sensitive_config.get("refresh_token")- token = refresh_token or self.integration.sensitive_config.get("access_token")- if not token:- return-- revoke_url = oauth_config.token_revoke_url- # Salesforce sandbox integrations are stored under the production kind (the sandbox is- # only a token-exchange fallback), so the static prod revoke URL would miss them. Revoke- # at the validated instance host so a stray write to config can't redirect the token to- # an attacker origin.- if self.integration.kind in SALESFORCE_OAUTH_KINDS:- allowed_host = _salesforce_instance_host(self.integration.config.get("instance_url"))- if allowed_host:- revoke_url = f"{allowed_host}/services/oauth2/revoke"-- data = {"token": token}- if self.integration.kind == "resend":- # Resend registers PostHog as a confidential client (token_endpoint_auth_method=- # client_secret_post) and requires client authentication on revocation. Without it- # the endpoint rejects the request and the grant survives the disconnect. The hint- # tells the provider which token type it received (RFC 7009).- data["client_id"] = oauth_config.client_id- data["client_secret"] = oauth_config.client_secret- data["token_type_hint"] = "refresh_token" if refresh_token else "access_token"-- # allow_redirects=False so a misconfigured/compromised provider can't 30x us into- # resending the token to another host. raise_for_status surfaces a provider rejection- # to the caller's capture_exception instead of it passing silently as a revoke.- response = requests.post(- revoke_url,- data=data,- timeout=10,- allow_redirects=False,- )- response.raise_for_status()-- def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:- # Not all integrations have refresh tokens or expiries, so we just return False if we can't check-- refresh_token = self.integration.sensitive_config.get("refresh_token")- expires_in = self.integration.config.get("expires_in")- refreshed_at = self.integration.config.get("refreshed_at")-- if not refresh_token:- return False-- if not expires_in and self.integration.kind in SALESFORCE_OAUTH_KINDS:- # Salesforce tokens typically last 2-4 hours, we'll assume 1 hour (3600 seconds) to be conservative- expires_in = 3600-- if not expires_in and self.integration.kind == "stripe":- expires_in = 3600-- if not expires_in or not refreshed_at:- return False-- # To be really safe we refresh if its half way through the expiry- time_threshold = time_threshold or timedelta(seconds=expires_in / 2)-- return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()-- def _post_token_refresh(self, oauth_config: OauthConfig, client_id: str, client_secret: str) -> requests.Response:- # Via the property, so a token that picked up an extra encryption layer is peeled back to- # the real one instead of being posted to the provider as ciphertext.- refresh_token = self.integration.refresh_token- if refresh_token is None:- # A grant with no refresh token at all is a caller error, not a provider rejection -- # keep failing loudly rather than posting `None` and reading the 400 back as one.- raise KeyError("refresh_token")- kind = self.integration.kind-- # Reddit uses HTTP Basic Auth for token refresh- if kind == "reddit-ads":- return requests.post(- oauth_config.token_url,- auth=HTTPBasicAuth(client_id, client_secret),- data={"refresh_token": refresh_token, "grant_type": "refresh_token"},- # If I use a standard User-Agent, it will throw a 429 too many requests error- headers={"User-Agent": "PostHog/1.0 by PostHogTeam"},- timeout=10,- )- # Pinterest uses HTTP Basic Auth for token refresh- elif kind == "pinterest-ads":- return requests.post(- oauth_config.token_url,- auth=HTTPBasicAuth(client_id, client_secret),- data={"refresh_token": refresh_token, "grant_type": "refresh_token"},- timeout=10,- )- elif kind == "tiktok-ads":- # Refresh against the Business API app we authorized against, using its app_id/secret and- # JSON body (mirroring the token exchange). The open.tiktokapis.com/v2 endpoint with- # client_key belongs to Login Kit — a different TikTok app family whose credentials this- # integration never holds.- return requests.post(- "https://business-api.tiktok.com/open_api/v1.3/oauth2/refresh_token/",- json={- "app_id": client_id,- "secret": client_secret,- "refresh_token": refresh_token,- "grant_type": "refresh_token",- },- headers={"Content-Type": "application/json"},- timeout=10,- )- elif kind == "bing-ads":- # Microsoft Azure AD requires scope parameter on token refresh- return requests.post(- oauth_config.token_url,- data={- "client_id": client_id,- "client_secret": client_secret,- "refresh_token": refresh_token,- "grant_type": "refresh_token",- "scope": oauth_config.scope,- },- timeout=10,- )- elif kind == "stripe":- # Stripe Apps OAuth: secret as HTTP Basic username, no client_id/client_secret in body.- return requests.post(- oauth_config.token_url,- auth=HTTPBasicAuth(client_secret, ""),- data={"refresh_token": refresh_token, "grant_type": "refresh_token"},- timeout=10,- )- else:- token_url = oauth_config.token_url- # Salesforce sandbox integrations are stored under the production kind (the sandbox- # is only a token-exchange fallback in the OAuth callback), so the static prod- # token URL would refuse a sandbox-issued refresh_token. Refresh at the org's- # own instance host instead. Validate the host before sending client_secret +- # refresh_token so a stray write to config can't exfiltrate the fleet-wide- # Salesforce app secret; fall back to the hardcoded prod URL on rejection.- if kind in SALESFORCE_OAUTH_KINDS:- allowed_host = _salesforce_instance_host(self.integration.config.get("instance_url"))- if allowed_host:- token_url = f"{allowed_host}/services/oauth2/token"-- return requests.post(- token_url,- data={- "client_id": client_id,- "client_secret": client_secret,- "refresh_token": refresh_token,- "grant_type": "refresh_token",- },- timeout=10,- allow_redirects=False,- )-- def _parse_token_refresh_response(self, res: requests.Response) -> dict:- try:- config = res.json()- except ValueError:- # e.g. an HTML error page from a proxy/5xx - still a failed refresh, not an exception- return {}- # TikTok Business API nests the refreshed tokens under `data`, same as the token exchange.- # Lift them to the top level so the generic access_token/refresh_token/expires_in handling reads them.- if self.integration.kind == "tiktok-ads" and isinstance(config.get("data"), dict):- config = {**config, **config["data"]}- return config-- def _record_terminal_unreadable_secret(self) -> None:- logger.error(- "integration_refresh_secret_unreadable",- integration_id=self.integration.pk,- team_id=self.integration.team_id,- kind=self.integration.kind,- )- self.integration.errors = ERROR_TOKEN_REFRESH_FAILED- attempt = record_refresh_failure(self.integration, reason=REFRESH_FAILURE_REASON_UNREADABLE_SECRET)- oauth_refresh_counter.labels(- kind=self.integration.kind,- result="failed",- reason=REFRESH_FAILURE_REASON_UNREADABLE_SECRET,- attempt=attempt,- ).inc()- # `sensitive_config` is deliberately excluded: saving it would re-encrypt the ciphertext- # this integration already can't read, adding another layer to the stored value.- self.integration.save(update_fields=["errors", "config"])-- def refresh_access_token(self):- """- Refresh the access token for the integration if necessary- """- region = self.integration.config.get("region") if self.integration.kind == "posthog" else None- oauth_config = self.oauth_config_for_kind(self.integration.kind, region)-- # Clear out previous token refreshing errors, as they'll be re-set below if another error occurs- self.integration.errors = ""-- res: requests.Response | None = None- config: dict = {}- used_fallback = False- try:- res = self._post_token_refresh(oauth_config, oauth_config.client_id, oauth_config.client_secret)- config = self._parse_token_refresh_response(res)- except UndecryptedIntegrationSecretError:- # The stored refresh token can't be read, so there is nothing to refresh with and no- # later attempt can change that. Go terminal immediately: the sweep stops retrying,- # and the UI shows the reconnect prompt.- self._record_terminal_unreadable_secret()- return- except requests.RequestException as e:- # A network error (timeout, connection reset) is a failed refresh, not a crash. Without- # this the Celery sweep task errors out before recording the failure, so the backoff and- # the TOKEN_REFRESH_FAILED reconnect state are never persisted.- logger.warning(f"Network error on primary credentials for {self}", error=str(e))-- # A rotated or migrated OAuth app leaves users with refresh tokens only the previous- # credentials can refresh. Retry with the fallback pair — including when the primary hit a- # network error — so they keep working until they reconnect.- if (- res is None or res.status_code != 200 or not config.get("access_token")- ) and oauth_config.client_secret_fallback:- try:- res = self._post_token_refresh(- oauth_config,- oauth_config.client_id_fallback or oauth_config.client_id,- oauth_config.client_secret_fallback,- )- config = self._parse_token_refresh_response(res)- used_fallback = True- except requests.RequestException as e:- logger.warning(f"Network error on fallback credentials for {self}", error=str(e))- res = None- config = {}-- if res is None or res.status_code != 200 or not config.get("access_token"):- logger.warning(- f"Failed to refresh token for {self}", response=res.text if res is not None else "network error"- )- self.integration.errors = ERROR_TOKEN_REFRESH_FAILED- reason = (- oauth_refresh_failure_reason(res.status_code, config, kind=self.integration.kind)- if res is not None- else REFRESH_FAILURE_REASON_NETWORK- )- attempt = record_refresh_failure(self.integration, reason=reason)- oauth_refresh_counter.labels(- kind=self.integration.kind, result="failed", reason=reason, attempt=attempt- ).inc()- # A failed refresh leaves `sensitive_config` untouched, so writing it back only risks- # harm: `ignore_decrypt_errors` hands back raw ciphertext for a secret that couldn't be- # decrypted, and saving re-encrypts it, permanently adding a layer to the stored value.- self.integration.save(update_fields=["errors", "config"])- return- else:- logger.info(f"Refreshed access token for {self}")- record_refresh_success(self.integration)- record_oauth_client_used(self.integration, used_fallback=used_fallback)- self.integration.sensitive_config["access_token"] = config["access_token"]-- # Some providers (e.g. Atlassian/Jira) rotate refresh tokens — each- # refresh response includes a new refresh_token and the old one is- # invalidated. Always store the latest one to avoid "invalid refresh- # token" errors on subsequent refreshes.- if config.get("refresh_token"):- self.integration.sensitive_config["refresh_token"] = config["refresh_token"]-- # Handle case where Salesforce/Stripe doesn't provide expires_in in refresh response- expires_in = config.get("expires_in")- if not expires_in and self.integration.kind in SALESFORCE_OAUTH_KINDS:- expires_in = 3600- if not expires_in and self.integration.kind == "stripe":- expires_in = 3600-- self.integration.config["expires_in"] = expires_in- self.integration.config["refreshed_at"] = int(time.time())- reload_integrations_on_workers(self.integration.team_id, [self.integration.id])- oauth_refresh_counter.labels(- kind=self.integration.kind,- result="success_fallback" if used_fallback else "success",- reason="",- attempt="",- ).inc()-- self.integration.save()---class SlackIntegrationError(Exception):- pass---SLACK_INTEGRATION_KINDS: tuple[str, ...] = ("slack",)--SLACK_CHANNELS_PAGE_SIZE = 1000-SLACK_CHANNELS_MAX_PAGES = 10---class SlackIntegration:- integration: Integration-- def __init__(self, integration: Integration) -> None:- if integration.kind not in SLACK_INTEGRATION_KINDS:- raise Exception("SlackIntegration init called with Integration with wrong 'kind'")-- self.integration = integration-- @property- def client(self) -> WebClient:- return WebClient(- self.integration.sensitive_config["access_token"],- source="integration",- workspace_id=self.integration.integration_id,- app_id="posthog",- )-- def async_client(self, session: Optional["aiohttp.ClientSession"] = None) -> "AsyncWebClient":- # slack_sdk's async client imports aiohttp at module scope; this is a models module,- # so a top-level import would put aiohttp on the django.setup() path- from posthog.egress.slack.async_client import SlackAsyncWebClient # noqa: PLC0415-- return SlackAsyncWebClient(- self.integration.sensitive_config["access_token"],- source="integration",- workspace_id=self.integration.integration_id,- app_id="posthog",- session=session,- )-- def granted_scopes(self) -> frozenset[str]:- """OAuth scopes Slack granted this install, stored on Integration.config["scope"]."""- raw = self.integration.config.get("scope") or ""- return frozenset(scope.strip() for scope in raw.split(",") if scope.strip())-- def missing_scopes(self, required: Iterable[str]) -> frozenset[str]:- return frozenset(required) - self.granted_scopes()-- def list_channels(self, should_include_private_channels: bool, authed_user: str) -> list[dict]:- # NOTE: Annoyingly the Slack API has no search so we have to load all channels...- # We load public and private channels separately as when mixed, the Slack API pagination is buggy- public_channels = self._list_channels_by_type("public_channel")- private_channels = self._list_channels_by_type("private_channel", should_include_private_channels, authed_user)- channels = public_channels + private_channels-- return sorted(channels, key=lambda x: x["name"])-- def get_channel_by_id(- self, channel_id: str, should_include_private_channels: bool = False, authed_user: str | None = None- ) -> dict | None:- try:- response = self.client.conversations_info(channel=channel_id, include_num_members=True)- channel = response["channel"]- members_response = self.client.conversations_members(channel=channel_id, limit=channel["num_members"] + 1)- isMember = authed_user in members_response["members"]-- if not isMember:- return None-- isPrivateWithoutAccess = channel["is_private"] and not should_include_private_channels-- return {- "id": channel["id"],- "name": PRIVATE_CHANNEL_WITHOUT_ACCESS if isPrivateWithoutAccess else channel["name"],- "is_private": channel["is_private"],- "is_member": channel.get("is_member", True),- "is_ext_shared": channel["is_ext_shared"],- "is_private_without_access": isPrivateWithoutAccess,- }- except SlackApiError as e:- if e.response["error"] == "channel_not_found":- return None- raise-- def _list_channels_by_type(- self,- type: Literal["public_channel", "private_channel"],- should_include_private_channels: bool = False,- authed_user: str | None = None,- ) -> list[dict]:- max_page = SLACK_CHANNELS_MAX_PAGES- channels = []- cursor = None-- while max_page > 0:- max_page -= 1- if type == "public_channel":- res = self.client.conversations_list(- exclude_archived=True, types=type, limit=SLACK_CHANNELS_PAGE_SIZE, cursor=cursor- )- else:- res = self.client.users_conversations(- exclude_archived=True,- types=type,- limit=SLACK_CHANNELS_PAGE_SIZE,- cursor=cursor,- user=authed_user,- )-- for channel in res["channels"]:- if channel["is_private"] and not should_include_private_channels:- channel["name"] = PRIVATE_CHANNEL_WITHOUT_ACCESS- channel["is_private_without_access"] = True-- channels.extend(res["channels"])- cursor = res["response_metadata"]["next_cursor"]- if not cursor:- break-- return channels-- @classmethod- def validate_request(cls, request: HttpRequest | Request):- slack_config = cls.slack_config()- validate_slack_request(request, slack_config["SLACK_APP_SIGNING_SECRET"])-- @classmethod- @cache_for(timedelta(minutes=5))- def slack_config(cls):- # Span only fires on cache miss (cache_for is process-local in-memory).- # If preflight.slack_config_main is fast in production traces, this span- # will be absent; if it appears, it tells us the DB hit was slow.- with tracer.start_as_current_span("slack_integration.slack_config_db"):- config = get_instance_settings(- [- "SLACK_APP_CLIENT_ID",- "SLACK_APP_CLIENT_SECRET",- "SLACK_APP_SIGNING_SECRET",- ]- )-- return config---@frozen-class SlackRequestSignature:- signature: str- timestamp: str---def sign_slack_request(body: bytes, signing_secret: str) -> SlackRequestSignature:- """Sign a body with the Slack HMAC-SHA256 scheme.-- Used by both prod (PostHog→PostHog cross-region calls that reuse the Slack signing scheme)- and tests. The matching verifier is `validate_slack_request` below.- """- ts = str(int(time.time()))- sig_basestring = f"v0:{ts}:{body.decode('utf-8')}".encode()- signature = "v0=" + hmac.new(signing_secret.encode("utf-8"), sig_basestring, digestmod=hashlib.sha256).hexdigest()- return SlackRequestSignature(signature=signature, timestamp=ts)---def validate_slack_request(request: HttpRequest | Request, signing_secret: str) -> None:- """- Validate a Slack request using HMAC-SHA256 signature verification.- Based on https://api.slack.com/authentication/verifying-requests-from-slack- """- slack_signature = request.headers.get("X-SLACK-SIGNATURE")- slack_time = request.headers.get("X-SLACK-REQUEST-TIMESTAMP")-- if not signing_secret or not slack_signature or not slack_time:- raise SlackIntegrationError("Invalid")-- try:- if time.time() - float(slack_time) > 300:- raise SlackIntegrationError("Expired")- except ValueError:- raise SlackIntegrationError("Invalid")-- sig_basestring = f"v0:{slack_time}:{request.body.decode('utf-8')}"-- my_signature = (- "v0="- + hmac.new(- signing_secret.encode("utf-8"),- sig_basestring.encode("utf-8"),- digestmod=hashlib.sha256,- ).hexdigest()- )-- if not hmac.compare_digest(my_signature, slack_signature):- raise SlackIntegrationError("Invalid")---def google_ads_hierarchy_level(account: dict) -> int:- """Depth of an account below the manager the walk started from. Google's REST responses omit proto3- defaults, so a level-0 account carries no `level` key at all, and deeper ones arrive as strings."""- return int(account.get("level") or 0)---@retry(- stop=stop_after_attempt(3),- wait=wait_fixed(2),- retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError)),- reraise=True,-)-def _google_ads_request(method: str, url: str, **kwargs) -> requests.Response:- """`requests.request` with retries for a transient timeout/connection blip.-- `list_google_ads_accessible_accounts` walks the account hierarchy with a chain of sequential- requests, so a single transient blip on any one of them would otherwise fail the whole walk.- """- return requests.request(method, url, **kwargs)---class GoogleAdsIntegration:- integration: Integration-- def __init__(self, integration: Integration) -> None:- if integration.kind != "google-ads":- raise Exception("GoogleAdsIntegration init called with Integration with wrong 'kind'")-- self.integration = integration-- @property- def client(self) -> WebClient:- return WebClient(self.integration.sensitive_config["access_token"])-- def list_google_ads_conversion_actions(self, customer_id, parent_id=None) -> list[dict]:- response = requests.request(- "POST",- f"https://googleads.googleapis.com/v24/customers/{customer_id}/googleAds:searchStream",- json={- "query": "SELECT conversion_action.id, conversion_action.name FROM conversion_action WHERE conversion_action.status != 'REMOVED'"- },- headers={- "Content-Type": "application/json",- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- "developer-token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,- **({"login-customer-id": parent_id} if parent_id else {}),- },- timeout=10,- )-- if response.status_code == 401:- logger.warning(- "GoogleAdsIntegration: Auth error listing conversion actions",- status_code=response.status_code,- integration_id=self.integration.id,- )- self.integration.errors = ERROR_TOKEN_REFRESH_FAILED- self.integration.save(update_fields=["errors"])- raise ValidationError(- "This integration's authentication is no longer valid. "- "Please reconnect or disconnect this integration and connect a different account."- )-- if response.status_code == 403:- raise ValidationError(- "This integration does not have permission to access this resource. "- "Please check the account permissions on the provider side."- )-- if response.status_code != 200:- capture_exception(- Exception(f"GoogleAdsIntegration: Failed to list ads conversion actions: {response.text}")- )- raise Exception("There was an internal error")-- return response.json()-- # Google Ads manager accounts can have access to other accounts (including other manager accounts).- # Filter out duplicates where a user has direct access and access through a manager account, while prioritizing direct access.- def list_google_ads_accessible_accounts(self) -> list[dict[str, Any]]:- response = _google_ads_request(- "GET",- "https://googleads.googleapis.com/v24/customers:listAccessibleCustomers",- headers={- "Content-Type": "application/json",- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- "developer-token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,- },- timeout=10,- )-- if response.status_code == 401:- logger.warning(- "GoogleAdsIntegration: Auth error listing accessible accounts",- status_code=response.status_code,- integration_id=self.integration.id,- )- self.integration.errors = ERROR_TOKEN_REFRESH_FAILED- self.integration.save(update_fields=["errors"])- raise ValidationError(- "This integration's authentication is no longer valid. "- "Please reconnect or disconnect this integration and connect a different account."- )-- if response.status_code == 403:- raise ValidationError(- "This integration does not have permission to access this resource. "- "Please check the account permissions on the provider side."- )-- if response.status_code != 200:- capture_exception(Exception(f"GoogleAdsIntegration: Failed to list accessible accounts: {response.text}"))- raise Exception("There was an internal error")-- accessible_accounts = response.json()- all_accounts: list[dict[str, Any]] = []-- def dfs(account_id, accounts=None, parent_id=None) -> list[dict]:- if accounts is None:- accounts = []- response = _google_ads_request(- "POST",- f"https://googleads.googleapis.com/v24/customers/{account_id}/googleAds:searchStream",- json={- "query": "SELECT customer_client.descriptive_name, customer_client.client_customer, customer_client.level, customer_client.manager, customer_client.status FROM customer_client WHERE customer_client.level <= 5"- },- headers={- "Content-Type": "application/json",- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- "developer-token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,- **({"login-customer-id": parent_id} if parent_id else {}),- },- timeout=10,- )-- if response.status_code != 200:- return accounts-- # searchStream's REST body is an array of response objects, one per streamed batch.- data = response.json()- results = [row for chunk in data for row in chunk.get("results", [])]-- for nested_account in results:- client = nested_account["customerClient"]- client_id = client["clientCustomer"].split("/")[1]- # `level` is compared numerically: it is absent on the level-0 row and a string ("1", "2")- # below it, so the raw values are not mutually comparable.- client_level = google_ads_hierarchy_level(client)-- # Reject non-enabled accounts before deduping. Otherwise a disabled, shallower sighting- # of an account we already kept as enabled would evict the enabled entry here and then be- # skipped by the status check below, dropping the account from the picker entirely.- if client.get("status") != "ENABLED":- continue-- # One account can be reached from several accessible roots — e.g. a user with access to- # both a manager and one of its clients walks that client twice, once as a root (level 0)- # and once beneath the manager (level 1). Keep the shallowest sighting, whose `parent_id`- # is the account we can authenticate the sync as.- already_seen = [account for account in accounts if account["id"] == client_id]- if already_seen:- if all(google_ads_hierarchy_level(account) <= client_level for account in already_seen):- continue- accounts = [account for account in accounts if account["id"] != client_id]-- accounts.append(- {- "parent_id": parent_id,- "id": client_id,- "level": client.get("level"),- "name": client.get("descriptiveName", "Google Ads account"),- "manager": client.get("manager", False),- }- )-- return accounts-- # A Google login with no accessible Ads accounts gets a 200 with an empty body, so- # `resourceNames` is absent (proto3 omits empty repeated fields) rather than an empty list.- for account in accessible_accounts.get("resourceNames", []):- all_accounts = dfs(account.split("/")[1], all_accounts, account.split("/")[1])-- return all_accounts---def is_unique_service_account_by_organization_id(service_account_email: str, organization_id: str) -> bool:- """Check if the service account is only in one organization.-- This is used as a security measure to block multiple organizations from- impersonating the same service account.-- In the future we may lift this restriction, but initially we want to make sure about- service account ownership with this check. This complements other runtime checks in- batch exports; see `verify_impersonated_service_account_ownership` in- `bigquery_batch_export.py`.- """- same_service_account_integrations = (- Integration.objects.select_related("team__organization")- .filter(kind="google-cloud-service-account", config__service_account_email=service_account_email)- # If private key is present, then we are not impersonating- .exclude(sensitive_config__has_key="private_key")- )- for integration in same_service_account_integrations:- if str(integration.team.organization.id) != organization_id:- return False-- return True---class GoogleCloudServiceAccountIntegration:- integration: Integration-- def __init__(self, integration: Integration) -> None:- self.integration = integration-- @classmethod- def integration_from_service_account(- cls,- team_id: int,- organization_id: str,- service_account_email: str,- project_id: str,- private_key: str | None = None,- private_key_id: str | None = None,- token_uri: str | None = None,- created_by: User | None = None,- ) -> Integration:- if private_key is None:- if not is_unique_service_account_by_organization_id(service_account_email, organization_id):- raise ValidationError("Cannot create Google Cloud service account integration: Invalid service account")-- sensitive_config = {}- is_impersonated = True- if isinstance(private_key, str) and isinstance(private_key_id, str) and isinstance(token_uri, str):- sensitive_config["private_key"] = private_key- sensitive_config["private_key_id"] = private_key_id- sensitive_config["token_uri"] = token_uri-- is_impersonated = False-- variant = "impersonated" if is_impersonated else "key-file"-- integration, _ = Integration.objects.update_or_create(- team_id=team_id,- kind=Integration.IntegrationKind.GOOGLE_CLOUD_SERVICE_ACCOUNT.value,- # Including team_id to allow teams from the same organization to use the- # same service account. Otherwise different teams would overwrite each other.- integration_id=f"{service_account_email}-{team_id}-{variant}",- defaults={- "config": {- "project_id": project_id,- "service_account_email": service_account_email,- },- "sensitive_config": sensitive_config,- "created_by": created_by,- },- )-- if integration.errors:- integration.errors = ""- integration.save()-- return integration-- def has_key(self) -> bool:- """Return if this integration has a key associated with a service account.-- If not, then it is a service account we are meant to impersonate.- """- keys = ("private_key", "private_key_id")- return all(key in self.integration.sensitive_config for key in keys) and all(- self.integration.sensitive_config[key] for key in keys- )-- @property- def project_id(self) -> str:- return self.integration.config["project_id"]-- @property- def service_account_email(self) -> str:- return self.integration.config["service_account_email"]-- @property- def service_account_info(self) -> dict[str, str]:- return {- "private_key": self.integration.sensitive_config["private_key"],- "private_key_id": self.integration.sensitive_config["private_key_id"],- "token_uri": self.integration.sensitive_config["token_uri"],- "client_email": self.service_account_email,- "project_id": self.project_id,- }---class GoogleCloudIntegration:- supported_kinds = ["google-pubsub", "google-cloud-storage"]- integration: Integration-- def __init__(self, integration: Integration) -> None:- self.integration = integration-- @classmethod- def integration_from_key(- cls, kind: str, key_info: dict, team_id: int, created_by: User | None = None- ) -> Integration:- if kind == "google-pubsub":- scope = "https://www.googleapis.com/auth/pubsub"- elif kind == "google-cloud-storage":- scope = "https://www.googleapis.com/auth/devstorage.read_write"- else:- raise NotImplementedError(f"Google Cloud integration kind {kind} not implemented")-- try:- credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])- credentials.refresh(GoogleRequest())- except Exception:- raise ValidationError(f"Failed to authenticate with provided service account key")-- integration, created = Integration.objects.update_or_create(- team_id=team_id,- kind=kind,- integration_id=credentials.service_account_email,- defaults={- "config": {- "expires_in": credentials.expiry.timestamp() - int(time.time()),- "refreshed_at": int(time.time()),- },- "sensitive_config": {- "key_info": key_info,- "access_token": credentials.token,- },- "created_by": created_by,- },- )-- if integration.errors:- integration.errors = ""- integration.save()-- return integration-- def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:- expires_in = self.integration.config.get("expires_in")- refreshed_at = self.integration.config.get("refreshed_at")- if not expires_in or not refreshed_at:- return False-- # To be really safe we refresh if its half way through the expiry- time_threshold = time_threshold or timedelta(seconds=expires_in / 2)-- return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()-- def refresh_access_token(self):- """- Refresh the access token for the integration if necessary- """- if self.integration.kind == "google-pubsub":- scope = "https://www.googleapis.com/auth/pubsub"- elif self.integration.kind == "google-cloud-storage":- scope = "https://www.googleapis.com/auth/devstorage.read_write"- else:- raise NotImplementedError(f"Google Cloud integration kind {self.integration.kind} not implemented")-- key_info = self.integration.sensitive_config.get("key_info", self.integration.sensitive_config)- credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])-- try:- credentials.refresh(GoogleRequest())- except Exception:- record_refresh_failure(self.integration)- self.integration.save(update_fields=["config"])- raise ValidationError(f"Failed to authenticate with provided service account key")-- # Wholesale replacement also clears any refresh backoff state- self.integration.config = {- "expires_in": credentials.expiry.timestamp() - int(time.time()),- "refreshed_at": int(time.time()),- }- # Migrate pre-migration integrations where sensitive_config contains the- # keyfile directly (not nested under "key_info"). Without this, setting- # access_token pollutes the keyfile dict and breaks subsequent refreshes.- if "key_info" not in self.integration.sensitive_config:- self.integration.sensitive_config = {- "key_info": self.integration.sensitive_config,- "access_token": credentials.token,- }- else:- self.integration.sensitive_config["access_token"] = credentials.token- self.integration.save()- reload_integrations_on_workers(self.integration.team_id, [self.integration.id])-- logger.info(f"Refreshed access token for {self}")-- def get_access_token(self) -> str:- if self.access_token_expired():- self.refresh_access_token()- # Fall back to config for pre-migration integrations- return self.integration.sensitive_config.get("access_token") or self.integration.config.get("access_token", "")---class FirebaseIntegration:- integration: Integration-- def __init__(self, integration: Integration) -> None:- if integration.kind != "firebase":- raise Exception("FirebaseIntegration init called with Integration with wrong 'kind'")- self.integration = integration-- @classmethod- def integration_from_key(- cls,- key_info: dict,- team_id: int,- created_by: User | None = None,- push_identity_verification: str | None = None,- push_identity_public_keys: list[str] | None = None,- ) -> "Integration":- scope = "https://www.googleapis.com/auth/firebase.messaging"-- try:- credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])- credentials.refresh(GoogleRequest())- except Exception:- raise ValidationError("Failed to authenticate with provided Firebase service account key")-- project_id = key_info.get("project_id")- if not project_id:- raise ValidationError("Service account key must contain a project_id")-- # Atomic so `preserved_push_config`'s row lock is held through the upsert that follows it.- with transaction.atomic():- integration, created = Integration.objects.update_or_create(- team_id=team_id,- kind="firebase",- integration_id=project_id,- defaults={- "config": {- **preserved_push_config(- team_id, "firebase", project_id, push_identity_verification, push_identity_public_keys- ),- "project_id": project_id,- "expires_in": credentials.expiry.timestamp() - int(time.time()),- "refreshed_at": int(time.time()),- },- "sensitive_config": {- "key_info": key_info,- "access_token": credentials.token,- },- "created_by": created_by,- },- )-- if integration.errors:- integration.errors = ""- integration.save()-- return integration-- @property- def project_id(self) -> str:- return self.integration.config.get("project_id", "")-- def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:- expires_in = self.integration.config.get("expires_in")- refreshed_at = self.integration.config.get("refreshed_at")- if not expires_in or not refreshed_at:- return False-- # To be really safe we refresh if its half way through the expiry- time_threshold = time_threshold or timedelta(seconds=expires_in / 2)- return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()-- def refresh_access_token(self) -> None:- scope = "https://www.googleapis.com/auth/firebase.messaging"- key_info = self.integration.sensitive_config.get("key_info", {})-- credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])-- try:- credentials.refresh(GoogleRequest())- except Exception:- record_refresh_failure(self.integration)- self.integration.save(update_fields=["config"])- raise ValidationError("Failed to authenticate with provided Firebase service account key")-- record_refresh_success(self.integration)- self.integration.config["expires_in"] = credentials.expiry.timestamp() - int(time.time())- self.integration.config["refreshed_at"] = int(time.time())- self.integration.sensitive_config["access_token"] = credentials.token- self.integration.save()- reload_integrations_on_workers(self.integration.team_id, [self.integration.id])-- logger.info(f"Refreshed access token for FirebaseIntegration {self.integration.id}")-- def get_access_token(self) -> str:- if self.access_token_expired():- self.refresh_access_token()- return self.integration.sensitive_config.get("access_token", "")---class ApplePushIntegration:- """- Integration for Apple Push Notification Service (APNS).-- config stores:- - team_id: Apple Developer Team ID- - bundle_id: App bundle identifier (e.g. com.example.app)- - key_id: The Key ID for the .p8 signing key- - environment: "production" or "sandbox" (defaults to "production")-- sensitive_config stores:- - signing_key: The .p8 signing key contents- """-- integration: Integration-- def __init__(self, integration: Integration) -> None:- if integration.kind != "apns":- raise Exception("ApplePushIntegration init called with Integration with wrong 'kind'")- self.integration = integration-- @classmethod- def integration_from_key(- cls,- signing_key: str,- key_id: str,- team_id_apple: str,- bundle_id: str,- team_id: int,- created_by: User | None = None,- environment: str = "production",- push_identity_verification: str | None = None,- push_identity_public_keys: list[str] | None = None,- ) -> "Integration":- if not all([signing_key, key_id, team_id_apple, bundle_id]):- raise ValidationError("All APNS fields are required: signing_key, key_id, team_id_apple, bundle_id")-- if environment not in ("production", "sandbox"):- raise ValidationError("APNS environment must be 'production' or 'sandbox'")-- integration_id = f"{team_id_apple}.{bundle_id}"- # Atomic so `preserved_push_config`'s row lock is held through the upsert that follows it.- with transaction.atomic():- integration, created = Integration.objects.update_or_create(- team_id=team_id,- kind="apns",- integration_id=integration_id,- defaults={- "config": {- **preserved_push_config(- team_id, "apns", integration_id, push_identity_verification, push_identity_public_keys- ),- "team_id": team_id_apple,- "bundle_id": bundle_id,- "key_id": key_id,- "environment": environment,- },- "sensitive_config": {- "signing_key": signing_key,- },- },- )-- if created and created_by is not None:- integration.created_by = created_by- integration.save(update_fields=["created_by"])-- if integration.errors:- integration.errors = ""- integration.save(update_fields=["errors"])-- return integration-- @property- def team_id_apple(self) -> str:- return self.integration.config.get("team_id", "")-- @property- def bundle_id(self) -> str:- return self.integration.config.get("bundle_id", "")-- @property- def key_id(self) -> str:- return self.integration.config.get("key_id", "")-- @property- def signing_key(self) -> str:- return self.integration.sensitive_config.get("signing_key", "")---class LinkedInAdsIntegration:- integration: Integration-- def __init__(self, integration: Integration) -> None:- if integration.kind != "linkedin-ads":- raise Exception("LinkedInAdsIntegration init called with Integration with wrong 'kind'")-- self.integration = integration-- @property- def client(self) -> WebClient:- return WebClient(self.integration.sensitive_config["access_token"])-- def _check_auth_error(self, response: requests.Response, context: str) -> None:- if response.status_code == 401:- logger.warning(- f"LinkedInAdsIntegration: Auth error {context}",- status_code=response.status_code,- integration_id=self.integration.id,- )- self.integration.errors = ERROR_TOKEN_REFRESH_FAILED- self.integration.save(update_fields=["errors"])- raise ValidationError(- "This integration's authentication is no longer valid. "- "Please reconnect or disconnect this integration and connect a different account."- )- if response.status_code == 403:- raise ValidationError(- "This integration does not have permission to access this resource. "- "Please check the account permissions on the provider side."- )-- def list_linkedin_ads_conversion_rules(self, account_id):- response = requests.request(- "GET",- f"https://api.linkedin.com/rest/conversions?q=account&account=urn%3Ali%3AsponsoredAccount%3A{account_id}&fields=conversionMethod%2Cenabled%2Ctype%2Cname%2Cid%2Ccampaigns%2CattributionType",- headers={- "Content-Type": "application/json",- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- "LinkedIn-Version": "202607",- },- timeout=10,- )-- self._check_auth_error(response, "listing conversion rules")- return response.json()-- def list_linkedin_ads_accounts(self) -> dict:- response = requests.request(- "GET",- "https://api.linkedin.com/rest/adAccounts?q=search",- headers={- "Content-Type": "application/json",- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- "LinkedIn-Version": "202607",- },- timeout=10,- )-- self._check_auth_error(response, "listing ad accounts")- return response.json()---class ClickUpIntegration:- integration: Integration-- def __init__(self, integration: Integration) -> None:- if integration.kind != "clickup":- raise Exception("ClickUpIntegration init called with Integration with wrong 'kind'")-- self.integration = integration-- def _check_auth_error(self, response: requests.Response, context: str) -> None:- if response.status_code == 401:- logger.warning(- f"ClickUpIntegration: Auth error {context}",- status_code=response.status_code,- integration_id=self.integration.id,- )- self.integration.errors = ERROR_TOKEN_REFRESH_FAILED- self.integration.save(update_fields=["errors"])- raise ValidationError(- "This integration's authentication is no longer valid. "- "Please reconnect or disconnect this integration and connect a different account."- )- if response.status_code == 403:- raise ValidationError(- "This integration does not have permission to access this resource. "- "Please check the account permissions on the provider side."- )-- def list_clickup_spaces(self, workspace_id):- response = requests.request(- "GET",- f"https://api.clickup.com/api/v2/team/{workspace_id}/space",- headers={- "Content-Type": "application/json",- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- },- timeout=10,- )-- self._check_auth_error(response, "listing spaces")- if response.status_code != 200:- capture_exception(Exception(f"ClickUpIntegration: Failed to list spaces: {response.text}"))- raise Exception("There was an internal error")-- return response.json()-- def list_clickup_folderless_lists(self, space_id):- response = requests.request(- "GET",- f"https://api.clickup.com/api/v2/space/{space_id}/list",- headers={- "Content-Type": "application/json",- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- },- timeout=10,- )-- self._check_auth_error(response, "listing lists")- if response.status_code != 200:- capture_exception(Exception(f"ClickUpIntegration: Failed to list lists: {response.text}"))- raise Exception("There was an internal error")-- return response.json()-- def list_clickup_folders(self, space_id):- response = requests.request(- "GET",- f"https://api.clickup.com/api/v2/space/{space_id}/folder",- headers={- "Content-Type": "application/json",- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- },- timeout=10,- )-- self._check_auth_error(response, "listing folders")- if response.status_code != 200:- capture_exception(Exception(f"ClickUpIntegration: Failed to list folders: {response.text}"))- raise Exception("There was an internal error")-- return response.json()-- def list_clickup_workspaces(self) -> dict:- response = requests.request(- "GET",- "https://api.clickup.com/api/v2/team",- headers={"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}"},- timeout=10,- )-- self._check_auth_error(response, "listing workspaces")- if response.status_code != 200:- capture_exception(Exception(f"ClickUpIntegration: Failed to list workspaces: {response.text}"))- raise Exception("There was an internal error")-- return response.json()---class EmailIntegration:- integration: Integration-- def __init__(self, integration: Integration) -> None:- if integration.kind != "email":- raise Exception("EmailIntegration init called with Integration with wrong 'kind'")- self.integration = integration-- @property- def ses_provider(self) -> SESProvider:- return SESProvider()-- @classmethod- def create_native_integration(- cls, config: dict, team_id: int, organization_id: str, created_by: User | None = None- ) -> Integration:- email_address: str = config["email"].lower()- name: str = config["name"]- domain: str = email_address.split("@")[1]- mail_from_subdomain: str = config.get("mail_from_subdomain", "feedback")- provider: str = config.get("provider", "ses")-- if domain in free_email_domains_list or domain in disposable_email_domains_list:- raise ValidationError(f"Email domain {domain} is not supported. Please use a custom domain.")-- # Check if any other integration already exists in a different team with the same domain,- # if so, ensure this team is part of the same organization. If not, we block creation.- same_domain_integrations = Integration.objects.filter(kind="email", config__domain=domain)- for integration in same_domain_integrations:- if str(integration.team.organization.id) != str(organization_id):- raise ValidationError(- f"An email integration with domain {domain} already exists in another organization. Try a different domain or contact support if you believe this is a mistake."- )-- # Create domain in the appropriate provider- if provider == "ses":- ses = SESProvider()- org_team_ids = list(Team.objects.filter(organization_id=organization_id).values_list("id", flat=True))- ses.create_email_domain(- domain,- mail_from_subdomain=mail_from_subdomain,- team_id=team_id,- org_team_ids=org_team_ids,- )- elif provider == "maildev" and settings.DEBUG:- pass- else:- raise ValueError(f"Invalid provider: must be 'ses'")-- integration, created = Integration.objects.update_or_create(- team_id=team_id,- kind="email",- integration_id=email_address,- defaults={- "config": {- "email": email_address,- "domain": domain,- "mail_from_subdomain": mail_from_subdomain,- "name": name,- "provider": provider,- "verified": True if provider == "maildev" else False,- },- "created_by": created_by,- },- )-- if integration.errors:- integration.errors = ""- integration.save()-- return integration-- def update_native_integration(self, config: dict, team_id: int) -> Integration:- provider = self.integration.config.get("provider")- domain = self.integration.config.get("domain")- # Only name and mail_from_subdomain can be updated- name: str = config.get("name", self.integration.config.get("name"))- mail_from_subdomain: str = config.get(- "mail_from_subdomain", self.integration.config.get("mail_from_subdomain", "feedback")- )-- # Update domain in the appropriate provider- if provider == "ses":- ses = SESProvider()- ses.update_mail_from_subdomain(domain, mail_from_subdomain=mail_from_subdomain)- elif provider == "maildev" and settings.DEBUG:- pass- else:- raise ValueError(f"Invalid provider: must be 'ses'")-- self.integration.config.update(- {- "name": name,- "mail_from_subdomain": mail_from_subdomain,- }- )- self.integration.save()-- return self.integration-- def verify(self):- domain = self.integration.config.get("domain")- provider = self.integration.config.get("provider", "ses")- mail_from_subdomain = self.integration.config.get("mail_from_subdomain", "feedback")-- # Use the appropriate provider for verification- if provider == "ses":- verification_result = self.ses_provider.verify_email_domain(- domain, mail_from_subdomain=mail_from_subdomain, team_id=self.integration.team_id- )- elif provider == "maildev":- verification_result = {- "status": "success",- "dnsRecords": MAILDEV_MOCK_DNS_RECORDS,- }- else:- raise ValueError(f"Invalid provider: {provider}")-- if verification_result.get("status") == "success":- # We can validate all other integrations with the same domain and provider- all_integrations_for_domain = Integration.objects.filter(- team_id=self.integration.team_id,- kind="email",- config__domain=domain,- config__provider=provider,- )- for integration in all_integrations_for_domain:- integration.config["verified"] = True- integration.save()-- reload_integrations_on_workers(- self.integration.team_id, [integration.id for integration in all_integrations_for_domain]- )-- return verification_result---class LinearIntegration:- integration: Integration-- def __init__(self, integration: Integration) -> None:- if integration.kind != "linear":- raise Exception("LinearIntegration init called with Integration with wrong 'kind'")-- self.integration = integration-- def url_key(self) -> str:- return dot_get(self.integration.config, "data.viewer.organization.urlKey")-- def list_teams(self) -> list[dict]:- body = self.query(f"{{ teams {{ nodes {{ id name }} }} }}")- teams = dot_get(body, "data.teams.nodes")- return teams-- def create_issue(self, attachment_url: str, config: dict[str, str]) -> dict[str, str]:- title: str = config.pop("title")- description: str = config.pop("description")- linear_team_id = config.pop("team_id")-- issue_create_query = """- mutation IssueCreate($title: String!, $description: String!, $teamId: String!) {- issueCreate(input: { title: $title, description: $description, teamId: $teamId }) {- success- issue { identifier }- }- }- """- body = self.query(- issue_create_query,- variables={"title": title, "description": description, "teamId": linear_team_id},- )- linear_issue_id = dot_get(body, "data.issueCreate.issue.identifier")- # Linear reports failures in a 200 body; without this check a failed create would- # persist a reference with id None. Nothing was created, so raising is safe.- if body.get("errors") or not linear_issue_id:- raise ValidationError("Failed to create the Linear issue")-- # Best-effort: the Linear issue already exists at this point, so failing the whole- # create over a missing back-link would produce duplicate issues on retry.- try:- self.create_attachment(linear_issue_id, attachment_url)- except ValidationError:- logger.warning("linear_issue_attachment_failed", issue_id=linear_issue_id)-- return {"id": linear_issue_id}-- def create_attachment(self, issue_id: str, url: str) -> None:- """Attach a PostHog issue link to a Linear issue (shows as a back-link in Linear).-- Raises on failure: Linear reports errors in the GraphQL body with HTTP 200,- and the mutation itself can report success=false.- """- link_attachment_query = """- mutation AttachmentCreate($issueId: String!, $title: String!, $url: String!) {- attachmentCreate(input: { issueId: $issueId, title: $title, url: $url }) {- success- }- }- """- body = self.query(- link_attachment_query,- variables={"issueId": issue_id, "title": "PostHog issue", "url": url},- )- if body.get("errors") or not dot_get(body, "data.attachmentCreate.success"):- raise ValidationError("Failed to attach the PostHog link to the Linear issue")-- def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:- """Search existing Linear issues by title / identifier for the link-existing flow."""- search_query = """- query SearchIssues($term: String!, $first: Int!) {- searchIssues(term: $term, first: $first) {- nodes { identifier title url }- }- }- """- body = self.query(search_query, variables={"term": query, "first": limit})- if body.get("errors") or dot_get(body, "data.searchIssues") is None:- raise ValidationError("Failed to search Linear issues")- nodes = dot_get(body, "data.searchIssues.nodes") or []- results: list[dict[str, Any]] = []- for node in nodes:- identifier = node.get("identifier")- if not identifier:- continue- results.append(- {- "id": identifier,- "title": node.get("title") or identifier,- "url": node.get("url") or "",- # Matches the shape LinearIntegration.create_issue stores.- "external_context": {"id": identifier},- }- )- return results-- def query(self, query: str, variables: dict[str, Any] | None = None) -> dict[str, Any]:- response = requests.post(- "https://api.linear.app/graphql",- headers={"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}"},- json={"query": query, "variables": variables or {}},- timeout=10,- )- return response.json()---class JiraIntegration:- integration: Integration-- def __init__(self, integration: Integration) -> None:- if integration.kind != "jira":- raise Exception("JiraIntegration init called with Integration with wrong 'kind'")-- self.integration = integration-- def cloud_id(self) -> str | None:- """Get the Atlassian cloud ID from the integration config"""- return dot_get(self.integration.config, "cloud_id")-- def site_name(self) -> str | None:- """Get the Jira site name from the integration config"""- return dot_get(self.integration.config, "site_name")-- def site_url(self) -> str:- """Get the Jira site URL from the integration config"""- return dot_get(self.integration.config, "site_url", "")-- def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:- """Check if the Atlassian access token has expired or is close to expiring"""- refresh_token = self.integration.sensitive_config.get("refresh_token")- expires_in = self.integration.config.get("expires_in")- refreshed_at = self.integration.config.get("refreshed_at")-- if not refresh_token:- return False-- if not expires_in or not refreshed_at:- return False-- # To be safe we refresh if it's halfway through the expiry- time_threshold = time_threshold or timedelta(seconds=expires_in / 2)-- return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()-- def refresh_access_token(self) -> None:- """Refresh the Atlassian access token using the refresh token"""- oauth_integration = OauthIntegration(self.integration)- oauth_integration.refresh_access_token()-- def _ensure_token_valid(self) -> None:- """Proactively refresh token if it's close to expiring to avoid intermittent 401s"""- try:- if self.access_token_expired():- self.refresh_access_token()- except Exception:- logger.warning("JiraIntegration: token refresh pre-check failed", exc_info=True)-- def _raise_create_issue_error(self, response: requests.Response, response_body: Any) -> NoReturn:- properties: dict[str, Any] = {- "jira_status_code": response.status_code,- "jira_response_content_type": response.headers.get("Content-Type"),- "integration_id": self.integration.id,- "team_id": self.integration.team_id,- }- if isinstance(response_body, dict):- properties.update(- {- "jira_error_messages": response_body.get("errorMessages"),- "jira_field_errors": response_body.get("errors"),- "jira_response_keys": list(response_body.keys()),- }- )-- capture_exception(Exception("Jira issue creation failed"), additional_properties=properties)- raise ValidationError("Could not create the Jira issue. Check the project's issue settings and try again.")-- def list_projects(self) -> list[dict]:- """List all Jira projects accessible to the user"""- cloud_id = self.cloud_id()- if not cloud_id:- raise ValidationError("Jira integration missing cloud_id - the integration may not be properly configured")-- self._ensure_token_valid()-- response = requests.get(- f"https://api.atlassian.com/ex/jira/{cloud_id}/rest/api/3/project/search",- headers={- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- "Accept": "application/json",- },- timeout=10,- )- body = response.json()- projects = body.get("values", [])- return [{"id": p["id"], "key": p["key"], "name": p["name"]} for p in projects]-- def create_issue(self, config: dict[str, str]) -> dict[str, str]:- """Create a Jira issue and return the issue key"""- cloud_id = self.cloud_id()- if not cloud_id:- raise ValidationError("Jira integration missing cloud_id - the integration may not be properly configured")-- self._ensure_token_valid()-- title = config.get("title")- description = config.get("description")- project_key = config.get("project_key")-- # Jira uses Atlassian Document Format (ADF) for description- payload = {- "fields": {- "project": {"key": project_key},- "summary": title,- "description": {- "type": "doc",- "version": 1,- "content": [- {- "type": "paragraph",- "content": [{"type": "text", "text": description}],- }- ],- },- "issuetype": {"name": "Task"},- }- }-- response = requests.post(- f"https://api.atlassian.com/ex/jira/{cloud_id}/rest/api/3/issue",- headers={- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- "Accept": "application/json",- "Content-Type": "application/json",- },- json=payload,- timeout=10,- )-- try:- issue = response.json()- except ValueError:- issue = None-- if response.status_code != 201:- self._raise_create_issue_error(response, issue)-- if not isinstance(issue, dict) or not issue.get("key"):- self._raise_create_issue_error(response, issue)-- return {"key": issue["key"], "id": issue.get("id", "")}-- def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:- """Search existing Jira issues for the link-existing flow.-- Uses Jira's purpose-built issue picker endpoint, which matches on summary and- issue key without us having to build (and escape) a JQL string from user input.- """- cloud_id = self.cloud_id()- if not cloud_id:- raise ValidationError("Jira integration missing cloud_id - the integration may not be properly configured")-- self._ensure_token_valid()-- response = requests.get(- f"https://api.atlassian.com/ex/jira/{cloud_id}/rest/api/3/issue/picker",- headers={- "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",- "Accept": "application/json",- },- # Without currentJQL the picker only returns history suggestions (issues the- # user recently viewed); this constant JQL makes it search all accessible issues.- params={"query": query, "currentJQL": "order by created DESC", "showSubTasks": "true"},- timeout=10,- )- if response.status_code != 200:- raise ValidationError(f"Failed to search Jira issues (status {response.status_code})")- body = response.json()-- site_url = self.site_url()- results: list[dict[str, Any]] = []- seen_keys: set[str] = set()- for section in body.get("sections", []) or []:- for issue in section.get("issues", []) or []:- key = issue.get("key")- if not key or key in seen_keys:- continue- seen_keys.add(key)- results.append(- {- "id": str(issue.get("id", "")),- "title": issue.get("summaryText") or issue.get("summary") or key,- "url": f"{site_url}/browse/{key}" if site_url else "",- # Matches the shape JiraIntegration.create_issue stores.- "external_context": {"key": key, "id": str(issue.get("id", ""))},- }- )- if len(results) >= limit:- return results- return results---# Default branches change rarely; a multi-hour TTL is plenty to avoid hitting-# GitHub on every paginated branch request while keeping the window in which a-# renamed default branch stays stale tolerably short.-GITHUB_DEFAULT_BRANCH_CACHE_TTL_SECONDS = 60 * 60 * 6-GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS = 30---@dataclass(frozen=True)-class GitHubUserAuthorization:- """Outcome of a successful GitHub App user authorization code exchange."""-- gh_id: int- gh_login: str- access_token: str = field(repr=False)- refresh_token: str | None = field(repr=False)- access_token_expires_in: int | None- refresh_token_expires_in: int | None---@dataclass(frozen=True)-class GitHubInstallationAccess:- """Installation-level access token response for a GitHub App installation."""-- installation_id: str- installation_info: dict[str, Any]- access_token: str = field(repr=False)- token_expires_at: str # ISO datetime returned by GitHub, e.g. "2024-01-01T14:00:00Z"- repository_selection: str---class GitHubInstallationAccessFetchError(Exception):- def __init__(self, code: str) -> None:- self.code = code- super().__init__(code)---def invalidate_github_repository_caches_for_installation(installation_id: str | int) -> None:- """Affects both team Integration and personal UserIntegration rows."""- from posthog.models.user_integration import UserIntegration-- installation_id_str = str(installation_id)- Integration.objects.filter(kind="github", integration_id=installation_id_str).update(- repository_cache_updated_at=None- )- UserIntegration.objects.filter(- kind=UserIntegration.IntegrationKind.GITHUB,- integration_id=installation_id_str,- ).update(repository_cache_updated_at=None)---def github_account_type(owner_type: str | None) -> str | None:- """Normalize GitHub's account ``type`` ("Organization" / "User") to org vs personal."""- if owner_type == "Organization":- return "organization"- if owner_type == "User":- return "personal"- return None---class GitHubIntegration(GitHubIntegrationBase):- integration: Integration-- @classmethod- def fetch_installation_access(cls, installation_id: str) -> GitHubInstallationAccess:- try:- installation_info = cls.client_request(f"installations/{installation_id}").json()- access_token_response = cls.client_request(- f"installations/{installation_id}/access_tokens", method="POST"- ).json()- except Exception as exc:- raise GitHubInstallationAccessFetchError("installation_fetch_failed") from exc-- installation_access_token = access_token_response.get("token")- token_expires_at = access_token_response.get("expires_at")- if not installation_access_token or not token_expires_at:- raise GitHubInstallationAccessFetchError("installation_token_failed")-- return GitHubInstallationAccess(- installation_id=installation_id,- installation_info=installation_info,- access_token=installation_access_token,- token_expires_at=token_expires_at,- repository_selection=access_token_response.get("repository_selection", "selected"),- )-- @classmethod- def integration_from_installation_id(- cls, installation_id: str, team_id: int, created_by: User | None = None- ) -> Integration:- installation_access = cls.fetch_installation_access(installation_id)- now = int(time.time())- expires_in = int(datetime.fromisoformat(installation_access.token_expires_at).timestamp() - now)-- config = {- "installation_id": installation_id,- "expires_in": expires_in,- "refreshed_at": now,- "repository_selection": installation_access.repository_selection,- "account": {- "type": dot_get(installation_access.installation_info, "account.type", None),- "name": dot_get(installation_access.installation_info, "account.login", installation_id),- },- }- # See GitHubIntegrationBase.refresh_access_token for why permissions are persisted.- permissions = installation_access.installation_info.get("permissions")- if isinstance(permissions, dict):- config["permissions"] = permissions-- sensitive_config = {"access_token": installation_access.access_token}-- integration, created = Integration.objects.update_or_create(- team_id=team_id,- kind="github",- integration_id=installation_id,- defaults={- "config": config,- "sensitive_config": sensitive_config,- "created_by": created_by,- },- )-- if integration.errors:- integration.errors = ""- integration.save()-- # Every other kind reports this from IntegrationSerializer.create(). GitHub also gets created- # through its App installation callback and through agentic provisioning, which never reach- # that serializer, so this is the one place every GitHub connect passes through.- # IntegrationSerializer.create() skips github for the same reason: its own github branch ends- # up here, and reporting in both would count one connection twice.- if created and created_by is not None:- from posthog.event_usage import ( # noqa: PLC0415 — posthog.event_usage imports posthog.models- report_user_action,- )-- owner_type = dot_get(installation_access.installation_info, "account.type", None)- try:- report_user_action(- created_by,- "integration created",- {- "integration_kind": "github",- "is_overwrite": False,- "repo_owner_type": owner_type,- "account_type": github_account_type(owner_type),- },- team=integration.team,- )- except Exception:- # The integration row is already committed. Raising here would report a connection- # that actually succeeded as a failure.- logger.exception("github_integration: failed to report integration created")-- invalidate_github_repository_caches_for_installation(installation_id)-- return integration-- @classmethod- def github_login_from_code(cls, code: str) -> str | None:- result = cls.github_user_from_code(code)- return result.gh_login if result else None-- @classmethod- def github_user_from_code(cls, code: str, *, redirect_uri: str | None = None) -> "GitHubUserAuthorization | None":- """Exchange an OAuth code from the GitHub App user authorization flow.-- Pass ``redirect_uri`` when the user was sent to ``/login/oauth/authorize`` with- the same redirect URI (required by GitHub for the token exchange in that flow).-- Returns a :class:`GitHubUserAuthorization` with the user's id/login plus the- user-to-server access/refresh tokens and their expirations, or ``None`` if- the exchange fails or the response lacks an id/login.- """- client_id = settings.GITHUB_APP_CLIENT_ID- client_secret = settings.GITHUB_APP_CLIENT_SECRET- if not client_id or not client_secret:- logger.warning("GitHubIntegration: GITHUB_APP_CLIENT_ID/SECRET not configured, cannot exchange code")- return None-- token_body: dict[str, str] = {- "client_id": client_id,- "client_secret": client_secret,- "code": code,- }- if redirect_uri is not None:- token_body["redirect_uri"] = redirect_uri-- token_response = requests.post(- "https://github.com/login/oauth/access_token",- json=token_body,- headers={"Accept": "application/json"},- timeout=10,- )- token_data = token_response.json()- access_token = token_data.get("access_token")- if not access_token:- logger.warning(- "GitHubIntegration: code exchange returned no access_token",- status_code=token_response.status_code,- error=token_data.get("error"),- error_description=token_data.get("error_description"),- error_uri=token_data.get("error_uri"),- )- return None-- # Identity-blind: a fresh user OAuth token with no installation budget behind it.- user_response = github_request(- "GET",- "https://api.github.com/user",- source="integration",- headers={"Authorization": f"Bearer {access_token}"},- timeout=10,- )- if user_response.status_code != 200:- logger.warning("GitHubIntegration: /user request failed", status_code=user_response.status_code)- return None-- payload = user_response.json()- gh_id = payload.get("id")- gh_login = payload.get("login")- if gh_id is None or not gh_login:- return None- access_expires_in = token_data.get("expires_in")- refresh_expires_in = token_data.get("refresh_token_expires_in")- return GitHubUserAuthorization(- gh_id=int(gh_id),- gh_login=str(gh_login),- access_token=str(access_token),- refresh_token=token_data.get("refresh_token") or None,- access_token_expires_in=int(access_expires_in) if access_expires_in is not None else None,- refresh_token_expires_in=int(refresh_expires_in) if refresh_expires_in is not None else None,- )-- @classmethod- def first_for_team_repository(- cls,- team_id: int,- repository: str,- *,- source: str | None = None,- priority: Priority | None = None,- ) -> "GitHubIntegration | None":- """First GitHub integration for the team whose installation can access ``repository`` (``owner/name``).-- ``repository`` reaches us from team-writable content (e.g. artefact payloads), and the access- check below interpolates it into an authenticated ``GET /repos/{repository}``. Reject anything- that isn't a plain ``owner/repo`` first, so a crafted value (``owner/repo/contents/x?ref=y``)- can't steer that authenticated request to a different GitHub endpoint as a probe.- """- if not _is_safe_github_repo_path(repository):- return None- for integration in Integration.objects.filter(team_id=team_id, kind="github").order_by("id"):- github = cls(integration, source=source, priority=priority)- if github.installation_can_access_repository(repository):- return github- return None-- def __init__(- self, integration: Integration, *, source: str | None = None, priority: Priority | None = None- ) -> None:- if integration.kind != "github":- raise Exception("GitHubIntegration init called with Integration with wrong 'kind'")- self.integration = integration- if source is not None:- self.source = source- if priority is not None:- self.priority = priority-- def _on_token_refresh_failed(self, response: requests.Response) -> None:- logger.warning(f"Failed to refresh token for {self}", response=response.text)- self.integration.errors = ERROR_TOKEN_REFRESH_FAILED- # A permanently-gone installation (uninstalled/suspended) drops expires_in/refreshed_at so the- # every-minute beat loop stops re-minting it; the errors + config change persist in one save.- self._disarm_proactive_refresh_if_installation_gone(response)- reason = REFRESH_FAILURE_REASON_HTTP_5XX if response.status_code >= 500 else REFRESH_FAILURE_REASON_OTHER- attempt = record_refresh_failure(self.integration, reason=reason)- oauth_refresh_counter.labels(kind=self.integration.kind, result="failed", reason=reason, attempt=attempt).inc()- self.integration.save()-- def _on_token_refreshed(self) -> None:- logger.info(f"Refreshed access token for {self}")- self.integration.errors = ""- record_refresh_success(self.integration)- reload_integrations_on_workers(self.integration.team_id, [self.integration.id])- oauth_refresh_counter.labels(kind=self.integration.kind, result="success", reason="", attempt="").inc()-- @database_sync_to_async- def list_cached_repositories_async(- self, *, search: str = "", limit: int = 100, offset: int = 0- ) -> tuple[list[dict], bool]:- return self.list_cached_repositories(search=search, limit=limit, offset=offset)-- def create_issue(self, config: dict[str, Any]):- title: str = config.pop("title")- body: str = config.pop("body")- repository: str = config.pop("repository")- labels = config.pop("labels", None)-- repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"- json_body: dict[str, Any] = {"title": title, "body": body}- if labels:- json_body["labels"] = labels-- response = self.api_request(- "POST",- f"/repos/{repo_path}/issues",- endpoint="/repos/{owner}/{repo}/issues",- json_body=json_body,- )- if response.status_code != 201:- raise GitHubIntegrationError(- f"GitHubIntegration: failed to create issue in {repo_path}: {response.text[:300]}",- status_code=response.status_code,- )- issue = response.json()-- return {"number": issue["number"], "repository": repository}-- def search_issues(self, repository: str, query: str, *, limit: int = 25) -> list[dict[str, Any]]:- """Search existing GitHub issues in a repository for the link-existing flow."""- repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"- if not _is_safe_github_repo_path(repo_path):- raise GitHubIntegrationError(f"GitHubIntegration: invalid repository path {repo_path!r}")-- # `repository` is stored bare in external_context so build_external_issue_url can re-prefix- # the org, matching what create_issue persists.- repository_name = repo_path.split("/", 1)[1]-- # Quote the user's text so search syntax in it (qualifiers like repo:, operators like OR)- # is matched literally instead of rewriting the query, which would fill the result page- # with foreign matches and hide valid ones.- search_term = query.replace("\\", " ").replace('"', " ").strip()- q = f'repo:{repo_path} "{search_term}" in:title type:issue' if search_term else f"repo:{repo_path} type:issue"-- response = self.api_request(- "GET",- "/search/issues",- endpoint="/search/issues",- params={"q": q, "per_page": limit},- )- if response.status_code != 200:- raise GitHubIntegrationError(- f"GitHubIntegration: failed to search issues in {repo_path}: {response.text[:300]}",- status_code=response.status_code,- )-- results: list[dict[str, Any]] = []- for issue in response.json().get("items", []) or []:- number = issue.get("number")- if number is None:- continue- # The issues search API returns pull requests too; those aren't linkable issues.- if issue.get("pull_request"):- continue- # Search-syntax operators in the user's query (e.g. "foo OR bar") can escape the- # repo: qualifier, so drop anything that isn't actually from the chosen repository.- repository_url = issue.get("repository_url") or ""- if not repository_url.lower().endswith(f"/repos/{repo_path.lower()}"):- continue- results.append(- {- "id": str(number),- "title": issue.get("title") or f"#{number}",- "url": issue.get("html_url") or "",- # Matches the shape GitHubIntegration.create_issue stores.- "external_context": {"repository": repository_name, "number": number},- }- )- return results-- def create_branch(self, repository: str, branch_name: str, base_branch: str | None = None) -> dict[str, Any]:- """Create a new branch from a base branch."""- org = self.organization()-- # Get the SHA of the base branch (default to repository's default branch)- if not base_branch:- base_branch = self.get_default_branch(repository)-- # Get the SHA of the base branch- ref_response = self.api_request(- "GET",- f"/repos/{org}/{repository}/git/ref/heads/{base_branch}",- endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",- )-- if ref_response.status_code != 200:- return {- "success": False,- "error": f"Failed to get base branch {base_branch}: {ref_response.text}",- }-- base_sha = ref_response.json()["object"]["sha"]-- # Create the new branch- response = self.api_request(- "POST",- f"/repos/{org}/{repository}/git/refs",- endpoint="/repos/{owner}/{repo}/git/refs",- json_body={- "ref": f"refs/heads/{branch_name}",- "sha": base_sha,- },- )-- if response.status_code == 201:- branch_data = response.json()- return {- "success": True,- "branch_name": branch_name,- "sha": branch_data["object"]["sha"],- "ref": branch_data["ref"],- }- else:- return {- "success": False,- "error": f"Failed to create branch: {response.text}",- "status_code": response.status_code,- }-- def commit_files_to_branch(- self,- repository: str,- branch_name: str,- base_branch: str,- files: Mapping[str, str],- commit_message: str,- replace_directory: str | None = None,- ) -> dict[str, Any]:- """Point ``branch_name`` at a single commit on top of ``base_branch`` writing every file in- ``files`` (repo-relative path → text content).-- Prefer this over ``create_branch`` plus one ``update_file`` per file when the files only make- sense together: the commit object is built before the branch reference exists, so a failure- part way through leaves nothing in the repository, and reviewers get one commit rather than- one per file. An existing branch is force-updated to the new commit, discarding whatever was- on it — callers republishing generated content want exactly that, callers collaborating on a- branch do not.-- ``replace_directory`` makes the commit *replace* that directory with exactly the files given- under it, instead of merging them into whatever ``base_branch`` already holds there. Without- it a path that existed on the base and is absent from ``files`` survives, because the tree is- built on the base tree: a caller republishing a generated directory would keep shipping files- it has since deleted or renamed. Files outside the directory are still merged as usual.- """- if not files:- return {"success": False, "error": "No files to commit"}-- org = self.organization()-- base_ref_response = self.api_request(- "GET",- f"/repos/{org}/{repository}/git/ref/heads/{base_branch}",- endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",- )- if base_ref_response.status_code != 200:- return {- "success": False,- "error": f"Failed to get base branch {base_branch}: {base_ref_response.text}",- "status_code": base_ref_response.status_code,- }- base_sha = base_ref_response.json()["object"]["sha"]-- base_commit_response = self.api_request(- "GET",- f"/repos/{org}/{repository}/git/commits/{base_sha}",- endpoint="/repos/{owner}/{repo}/git/commits/{commit_sha}",- )- if base_commit_response.status_code != 200:- return {- "success": False,- "error": f"Failed to read base commit {base_sha}: {base_commit_response.text}",- "status_code": base_commit_response.status_code,- }- base_tree_sha = base_commit_response.json()["tree"]["sha"]-- # Inline `content` lets GitHub create the blobs as part of the tree, so no separate blob- # round trip per file. 100644 is a non-executable file.- def blob_entries(paths: Mapping[str, str]) -> list[dict[str, str]]:- return [- {"path": path, "mode": "100644", "type": "blob", "content": content} for path, content in paths.items()- ]-- entries: list[dict[str, str]] = []- if replace_directory:- prefix = replace_directory.rstrip("/") + "/"- inside = {path[len(prefix) :]: content for path, content in files.items() if path.startswith(prefix)}- # Built with no base_tree, so this tree holds the given files and nothing else. Pointing- # the directory entry at it swaps the whole subtree in one step, which is what makes a- # path the caller dropped disappear rather than survive from the base tree.- subtree_response = self.api_request(- "POST",- f"/repos/{org}/{repository}/git/trees",- endpoint="/repos/{owner}/{repo}/git/trees",- json_body={"tree": blob_entries(inside)},- )- if subtree_response.status_code != 201:- return {- "success": False,- "error": f"Failed to create tree for {replace_directory}: {subtree_response.text}",- "status_code": subtree_response.status_code,- }- entries.append(- {- "path": replace_directory.rstrip("/"),- "mode": "040000",- "type": "tree",- "sha": subtree_response.json()["sha"],- }- )- entries.extend(blob_entries({p: c for p, c in files.items() if not p.startswith(prefix)}))- else:- entries = blob_entries(files)-- tree_response = self.api_request(- "POST",- f"/repos/{org}/{repository}/git/trees",- endpoint="/repos/{owner}/{repo}/git/trees",- json_body={"base_tree": base_tree_sha, "tree": entries},- )- if tree_response.status_code != 201:- return {- "success": False,- "error": f"Failed to create tree: {tree_response.text}",- "status_code": tree_response.status_code,- }-- commit_response = self.api_request(- "POST",- f"/repos/{org}/{repository}/git/commits",- endpoint="/repos/{owner}/{repo}/git/commits",- json_body={- "message": commit_message,- "tree": tree_response.json()["sha"],- "parents": [base_sha],- },- )- if commit_response.status_code != 201:- return {- "success": False,- "error": f"Failed to create commit: {commit_response.text}",- "status_code": commit_response.status_code,- }- commit_sha = commit_response.json()["sha"]-- create_ref_response = self.api_request(- "POST",- f"/repos/{org}/{repository}/git/refs",- endpoint="/repos/{owner}/{repo}/git/refs",- json_body={"ref": f"refs/heads/{branch_name}", "sha": commit_sha},- )- if create_ref_response.status_code == 201:- return {"success": True, "branch_name": branch_name, "commit_sha": commit_sha, "created_branch": True}-- # 422 is what GitHub returns for a reference that already exists; move it instead.- if create_ref_response.status_code != 422:- return {- "success": False,- "error": f"Failed to create branch {branch_name}: {create_ref_response.text}",- "status_code": create_ref_response.status_code,- }-- update_ref_response = self.api_request(- "PATCH",- f"/repos/{org}/{repository}/git/refs/heads/{branch_name}",- endpoint="/repos/{owner}/{repo}/git/refs/heads/{branch}",- json_body={"sha": commit_sha, "force": True},- )- if update_ref_response.status_code != 200:- return {- "success": False,- "error": f"Failed to update branch {branch_name}: {update_ref_response.text}",- "status_code": update_ref_response.status_code,- }- return {"success": True, "branch_name": branch_name, "commit_sha": commit_sha, "created_branch": False}-- def delete_branch(self, repository: str, branch_name: str, expected_sha: str | None = None) -> dict[str, Any]:- """Delete a branch reference. A branch that is already gone counts as success.-- ``expected_sha`` makes the delete conditional: the ref is read first and left alone when it- has moved on, which is what a caller cleaning up its own failed write wants on a branch name- that is shared by construction. GitHub has no conditional delete, so this narrows the race- rather than closing it.- """- org = self.organization()-- if expected_sha is not None:- head_response = self.api_request(- "GET",- f"/repos/{org}/{repository}/git/ref/heads/{branch_name}",- endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",- )- if head_response.status_code == 404:- return {"success": True, "branch_name": branch_name}- if head_response.status_code != 200:- return {- "success": False,- "error": f"Failed to read branch {branch_name}: {head_response.text}",- "status_code": head_response.status_code,- }- if head_response.json()["object"]["sha"] != expected_sha:- return {"success": True, "branch_name": branch_name, "skipped": True}-- response = self.api_request(- "DELETE",- f"/repos/{org}/{repository}/git/refs/heads/{branch_name}",- endpoint="/repos/{owner}/{repo}/git/refs/heads/{branch}",- )- if response.status_code in (204, 404):- return {"success": True, "branch_name": branch_name}- # GitHub answers a delete with 422 both for a reference that is already gone and for one it- # refused to remove, so the status alone can't tell "done" from "still there". Read the ref- # back: absent is the success the caller wanted, present is a branch it has to hear about.- if response.status_code == 422:- recheck_response = self.api_request(- "GET",- f"/repos/{org}/{repository}/git/ref/heads/{branch_name}",- endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",- )- if recheck_response.status_code == 404:- return {"success": True, "branch_name": branch_name}- return {- "success": False,- "error": f"Failed to delete branch {branch_name}: {response.text}",- "status_code": response.status_code,- }-- def get_diff(- self,- repository: str,- target_branch: str,- base_branch: str,- target_sha: str | None = None,- base_sha: str | None = None,- ) -> dict[str, Any]:- """Return the unified diff of one branch/commit against another for ``repository``.-- ``repository`` may be ``owner/name`` or a bare name (resolved against the installation's- org). The diff is ``base...target``: ``target_branch`` compared against ``base_branch``.- A SHA, when supplied, pins that side to an exact commit; otherwise the side tracks the- branch tip (``None`` means "use latest"). The branch is what's used when no SHA pins the- point — diffing branch tips keeps the result useful as a branch keeps moving (e.g. after PR- babysitting or customer tweaks), which a single pinned commit would not.-- Uses the GitHub compare API with the ``diff`` media type, so the response body is raw- unified-diff text. Repository / ref / SHA values come from team-writable artefact content,- so they're validated before interpolation — a crafted value could otherwise redirect the- authenticated request to a different GitHub endpoint.- """- repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"-- if not _is_safe_github_repo_path(repo_path):- return {"success": False, "error": f"Invalid repository '{repository}'.", "status_code": 400}- for ref in (target_branch, base_branch):- if not _is_safe_github_ref(ref):- return {"success": False, "error": f"Invalid branch '{ref}'.", "status_code": 400}- for sha in (target_sha, base_sha):- if sha is not None and not _is_safe_github_sha(sha):- return {"success": False, "error": f"Invalid commit SHA '{sha}'.", "status_code": 400}-- # Pin to the SHA when we have one, else compare branch tips. Both sides are now built from- # validated values, so the compare path can't be steered off-endpoint.- base_ref = base_sha or base_branch- target_ref = target_sha or target_branch-- try:- response = self.api_request(- "GET",- f"/repos/{repo_path}/compare/{base_ref}...{target_ref}",- endpoint="/repos/{owner}/{repo}/compare/{basehead}",- headers={"Accept": "application/vnd.github.diff"},- )- except GitHubIntegrationError:- # Don't let a slow/unreachable GitHub hang a worker or 500 the caller.- return {"success": False, "error": "Could not reach GitHub.", "status_code": 502}- if response.status_code != 200:- return {"success": False, "error": response.text, "status_code": response.status_code}- # Cap the diff we return: a branch touching generated/vendored files can produce a diff of- # many MB, which would bloat the JSON response and worker memory. Truncate with a marker so- # the consumer can tell the diff was cut rather than silently showing a partial diff.- diff_text = response.text- truncated = len(diff_text) > _MAX_DIFF_CHARS- if truncated:- diff_text = diff_text[:_MAX_DIFF_CHARS] + "\n\n… diff truncated (too large to display in full) …\n"- return {"success": True, "diff": diff_text, "truncated": truncated}-- def update_file(- self, repository: str, file_path: str, content: str, commit_message: str, branch: str, sha: str | None = None- ) -> dict[str, Any]:- """Create or update a file in the repository."""- org = self.organization()-- # If no SHA provided, try to get existing file's SHA- if not sha:- get_response = self.api_request(- "GET",- f"/repos/{org}/{repository}/contents/{file_path}",- endpoint="/repos/{owner}/{repo}/contents/{path}",- params={"ref": branch},- )- if get_response.status_code == 200:- sha = get_response.json()["sha"]-- encoded_content = base64.b64encode(content.encode("utf-8")).decode("utf-8")-- data = {- "message": commit_message,- "content": encoded_content,- "branch": branch,- }-- if sha:- data["sha"] = sha-- response = self.api_request(- "PUT",- f"/repos/{org}/{repository}/contents/{file_path}",- endpoint="/repos/{owner}/{repo}/contents/{path}",- json_body=data,- )-- if response.status_code in [200, 201]:- commit_data = response.json()- return {- "success": True,- "commit_sha": commit_data["commit"]["sha"],- "file_sha": commit_data["content"]["sha"],- "html_url": commit_data["commit"]["html_url"],- }- else:- return {- "success": False,- "error": f"Failed to update file: {response.text}",- "status_code": response.status_code,- }-- def get_file_contents(self, repository: str, file_path: str, ref: str | None = None) -> dict[str, Any] | None:- """Read a file's decoded text and blob SHA at ``ref`` (default branch when omitted).-- Returns ``{"content": str, "sha": str}``, or ``None`` when the file does not- exist — a missing file is a normal state, not an error. The SHA lets a caller- pass it straight to ``update_file`` for a conflict-safe write. Counterpart to- ``update_file``, kept here so URL and token handling stay inside the client.- """- repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"-- response = self.api_request(- "GET",- f"/repos/{repo_path}/contents/{file_path}",- endpoint="/repos/{owner}/{repo}/contents/{path}",- params={"ref": ref} if ref else None,- )- if response.status_code == 404:- return None- if response.status_code != 200:- raise GitHubIntegrationError(- f"Failed to read {file_path} from {repository}: {response.text}",- status_code=response.status_code,- )- payload = response.json()- return {"content": base64.b64decode(payload["content"]).decode("utf-8"), "sha": payload["sha"]}-- def create_pull_request(- self, repository: str, title: str, body: str, head_branch: str, base_branch: str | None = None- ) -> dict[str, Any]:- """Create a pull request."""- org = self.organization()-- if not base_branch:- base_branch = self.get_default_branch(repository)-- response = self.api_request(- "POST",- f"/repos/{org}/{repository}/pulls",- endpoint="/repos/{owner}/{repo}/pulls",- json_body={- "title": title,- "body": body,- "head": head_branch,- "base": base_branch,- },- )-- if response.status_code == 201:- pr_data = response.json()- return {- "success": True,- "pr_number": pr_data["number"],- "pr_url": pr_data["html_url"],- "pr_id": pr_data["id"],- "state": pr_data["state"],- }- else:- return {- "success": False,- "error": f"Failed to create pull request: {response.text}",- "status_code": response.status_code,- }-- def get_branch_info(self, repository: str, branch_name: str) -> dict[str, Any]:- """Get information about a specific branch."""- org = self.organization()-- response = self.api_request(- "GET",- f"/repos/{org}/{repository}/branches/{branch_name}",- endpoint="/repos/{owner}/{repo}/branches/{branch}",- )-- if response.status_code == 200:- branch_data = response.json()- return {- "success": True,- "exists": True,- "branch_name": branch_data["name"],- "commit_sha": branch_data["commit"]["sha"],- "protected": branch_data.get("protected", False),- }- elif response.status_code == 404:- return {- "success": True,- "exists": False,- "branch_name": branch_name,- }- else:- return {- "success": False,- "error": f"Failed to get branch info: {response.text}",- "status_code": response.status_code,- }-- def list_pull_requests(self, repository: str, state: str = "open") -> dict[str, Any]:- """List pull requests for a repository."""- org = self.organization()-- params: dict[str, str | int] = {"state": state, "per_page": 100}- response = self.api_request(- "GET",- f"/repos/{org}/{repository}/pulls",- endpoint="/repos/{owner}/{repo}/pulls",- params=params,- )-- if response.status_code == 200:- prs = response.json()- return {- "success": True,- "pull_requests": [- {- "number": pr["number"],- "title": pr["title"],- "url": pr["html_url"],- "state": pr["state"],- "head_branch": pr["head"]["ref"],- "base_branch": pr["base"]["ref"],- "created_at": pr["created_at"],- "updated_at": pr["updated_at"],- }- for pr in prs- ],- }- else:- return {- "success": False,- "error": f"Failed to list pull requests: {response.text}",- "status_code": response.status_code,- }---class GitLabIntegrationError(Exception):- pass---class GitLabIntegration:- integration: Integration-- @staticmethod- def get(hostname: str, endpoint: str, project_access_token: str) -> dict:- url = f"{hostname}/api/v4/{endpoint}"- allowed, error = is_url_allowed(url)- if not allowed:- raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")-- response = requests.get(- url,- headers={"PRIVATE-TOKEN": project_access_token},- # disallow redirects to prevent SSRF on redirected host- allow_redirects=False,- timeout=10,- )-- return response.json()-- @staticmethod- def post(hostname: str, endpoint: str, project_access_token: str, json: dict) -> dict:- url = f"{hostname}/api/v4/{endpoint}"- allowed, error = is_url_allowed(url)- if not allowed:- raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")-- response = requests.post(- url,- json=json,- headers={"PRIVATE-TOKEN": project_access_token},- # disallow redirects to prevent SSRF on redirected host- allow_redirects=False,- timeout=10,- )-- return response.json()-- @classmethod- def create_integration(cls, hostname, project_id, project_access_token, team_id, user) -> Integration:- project = cls.get(hostname, f"projects/{project_id}", project_access_token)-- integration = Integration.objects.create(- team_id=team_id,- kind=Integration.IntegrationKind.GITLAB,- integration_id=project.get("name_with_namespace"),- config={- "hostname": hostname,- "path_with_namespace": project.get("path_with_namespace"),- "project_id": project.get("id"),- },- sensitive_config={"access_token": project_access_token},- created_by=user,- )-- return integration-- def __init__(self, integration: Integration) -> None:- if integration.kind != "gitlab":- raise Exception("GitLabIntegration init called with Integration with wrong 'kind'")- self.integration = integration-- @property- def project_path(self) -> str:- return dot_get(self.integration.config, "path_with_namespace")-- @property- def hostname(self) -> str:- return dot_get(self.integration.config, "hostname")-- def create_issue(self, config: dict[str, str]):- title: str = config.pop("title")- description: str = config.pop("body")-- hostname = self.integration.config.get("hostname")- project_id = self.integration.config.get("project_id")- access_token = self.integration.sensitive_config.get("access_token")-- issue = GitLabIntegration.post(- hostname,- f"projects/{project_id}/issues",- access_token,- {- "title": title,- "description": description,- "labels": "posthog",- },- )-- return {"issue_id": issue["iid"]}-- def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:- """Search existing GitLab issues in the connected project for the link-existing flow."""- hostname = self.integration.config.get("hostname")- project_id = self.integration.config.get("project_id")- access_token = self.integration.sensitive_config.get("access_token")-- url = f"{hostname}/api/v4/projects/{project_id}/issues"- allowed, error = is_url_allowed(url)- if not allowed:- raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")-- params: dict[str, str | int] = {"search": query, "per_page": limit, "in": "title"}- response = requests.get(- url,- headers={"PRIVATE-TOKEN": access_token},- params=params,- allow_redirects=False,- timeout=10,- )- if response.status_code != 200:- raise GitLabIntegrationError(- f"GitLabIntegration: failed to search issues: {response.text[:300]}",- )- issues = response.json()- if not isinstance(issues, list):- return []-- results: list[dict[str, Any]] = []- for issue in issues:- iid = issue.get("iid")- if iid is None:- continue- results.append(- {- "id": str(iid),- "title": issue.get("title") or f"#{iid}",- "url": issue.get("web_url") or "",- # Matches the shape GitLabIntegration.create_issue stores.- "external_context": {"issue_id": iid},- }- )- return results---class MetaGraphIntegration:- """Token handling shared by the Meta Graph OAuth kinds (Meta Ads, Instagram).-- Meta issues no refresh token: a long-lived user access token is swapped for a fresh one- through the `fb_exchange_token` grant, which is why these kinds sit outside the generic- `OauthIntegration` refresh sweep and refresh on use instead.- """-- integration: Integration- kind: str = ""- api_version: str = "v25.0"-- def __init__(self, integration: Integration) -> None:- if integration.kind != self.kind:- raise Exception(f"{type(self).__name__} init called with Integration with wrong 'kind'")- self.integration = integration-- def refresh_access_token(self):- oauth_config = OauthIntegration.oauth_config_for_kind(self.integration.kind)-- # skip refresh if more than 7 days until expiry- if self.integration.config.get("expires_in") and self.integration.config.get("refreshed_at"):- if (- time.time()- < self.integration.config.get("refreshed_at") + self.integration.config.get("expires_in") - 604800- ):- return-- res = requests.post(- oauth_config.token_url,- data={- "client_id": oauth_config.client_id,- "client_secret": oauth_config.client_secret,- "fb_exchange_token": self.integration.sensitive_config["access_token"],- "grant_type": "fb_exchange_token",- "set_token_expires_in_60_days": True,- },- timeout=10,- )-- try:- config: dict = res.json()- except ValueError:- config = {}-- if res.status_code != 200 or not config.get("access_token"):- logger.warning(f"Failed to refresh token for {self}", response=res.text)- self.integration.errors = ERROR_TOKEN_REFRESH_FAILED- reason = oauth_refresh_failure_reason(res.status_code, config, kind=self.integration.kind)- attempt = record_refresh_failure(self.integration, reason=reason)- oauth_refresh_counter.labels(- kind=self.integration.kind, result="failed", reason=reason, attempt=attempt- ).inc()- else:- logger.info(f"Refreshed access token for {self}")- record_refresh_success(self.integration)- self.integration.sensitive_config["access_token"] = config["access_token"]- self.integration.errors = ""- self.integration.config["expires_in"] = config.get("expires_in")- self.integration.config["refreshed_at"] = int(time.time())- # not used in CDP yet- # reload_integrations_on_workers(self.integration.team_id, [self.integration.id])- oauth_refresh_counter.labels(kind=self.integration.kind, result="success", reason="", attempt="").inc()- self.integration.save()---class MetaAdsIntegration(MetaGraphIntegration):- kind = "meta-ads"---class InstagramIntegration(MetaGraphIntegration):- kind = "instagram"---class TwilioIntegration:- integration: Integration- twilio_provider: TwilioProvider-- def __init__(self, integration: Integration) -> None:- if integration.kind != "twilio":- raise Exception("TwilioIntegration init called with Integration with wrong 'kind'")- self.integration = integration- self.twilio_provider = TwilioProvider(- account_sid=self.integration.config["account_sid"],- auth_token=self.integration.sensitive_config["auth_token"],- )-- def list_twilio_phone_numbers(self) -> list[dict]:- twilio_phone_numbers = self.twilio_provider.get_phone_numbers()-- if not twilio_phone_numbers:- raise Exception(f"There was an internal error")-- return twilio_phone_numbers-- def integration_from_keys(self) -> Integration:- account_info = self.twilio_provider.get_account_info()-- if not account_info.get("sid"):- raise ValidationError({"account_info": "Failed to get account info"})-- integration, created = Integration.objects.update_or_create(- team_id=self.integration.team_id,- kind="twilio",- integration_id=account_info["sid"],- defaults={- "config": {- "account_sid": account_info["sid"],- },- "sensitive_config": {- "auth_token": self.integration.sensitive_config["auth_token"],- },- "created_by": self.integration.created_by,- },- )- if integration.errors:- integration.errors = ""- integration.save()-- return integration---ANTHROPIC_MANAGED_AGENTS_BETA_HEADER = "managed-agents-2026-04-01"-ANTHROPIC_DEFAULT_INTEGRATION_ID_PREFIX = "workspace-"-ANTHROPIC_WORKSPACE_LABEL_MAX_LENGTH = 100-ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT = 100-# 5s connect / 15s read are aggressive enough to keep gunicorn workers from-# being pinned for ~minutes on a slow Anthropic upstream while still leaving-# headroom for normal API latency.-ANTHROPIC_CLIENT_TIMEOUT_SECONDS = 15.0---class AnthropicIntegrationError(Exception):- """Raised when the AnthropicIntegration is constructed with an invalid Integration row."""---def _build_anthropic_client(api_key: str) -> "Anthropic":- # Tight timeouts and no SDK-side retries: we don't want a slow upstream to- # multiply request time by 3 (default `max_retries=2`) inside a Django worker.- from anthropic import Anthropic # noqa: PLC0415-- return Anthropic(api_key=api_key, timeout=ANTHROPIC_CLIENT_TIMEOUT_SECONDS, max_retries=0)---class AnthropicIntegration:- integration: Integration- _client: "Anthropic"-- def __init__(self, integration: Integration) -> None:- if integration.kind != Integration.IntegrationKind.ANTHROPIC.value:- # Internal misuse, not a user-input issue.- raise AnthropicIntegrationError(- f"AnthropicIntegration init called with Integration kind={integration.kind!r}"- )- self.integration = integration- api_key = integration.sensitive_config.get("api_key")- if not api_key:- raise AnthropicIntegrationError(f"Anthropic integration {integration.id} is missing 'api_key'")- self._client = _build_anthropic_client(api_key)-- @staticmethod- def validate_key(api_key: str) -> None:- # Validate by hitting the actual managed-agents surface so a key without- # beta access fails at create time instead of silently failing later.- from anthropic import ( # noqa: PLC0415- APIConnectionError,- APIStatusError,- AuthenticationError,- PermissionDeniedError,- )-- try:- client = _build_anthropic_client(api_key)- client.get(- "/v1/agents",- cast_to=dict[str, object],- options={- "headers": {"anthropic-beta": ANTHROPIC_MANAGED_AGENTS_BETA_HEADER},- "params": {"limit": 1},- },- )- except AuthenticationError:- raise ValidationError({"api_key": "Invalid Anthropic API key"})- except PermissionDeniedError:- raise ValidationError(- {- "api_key": (- "Anthropic API key is missing required permissions. Make sure the key has access to the "- "Managed Agents beta in your Anthropic console."- )- }- )- except APIConnectionError:- logger.warning("anthropic_validate_key_connection_error", exc_info=True)- raise ValidationError(- {"api_key": "Could not reach Anthropic to validate the API key. Check your network and try again."}- )- except APIStatusError as e:- logger.warning("anthropic_validate_key_status_error", status_code=e.status_code, exc_info=True)- raise ValidationError(- {"api_key": f"Anthropic returned an error validating the API key (HTTP {e.status_code})."}- )-- def _managed_agents_get(self, path: str, params: dict[str, Any] | None = None) -> dict:- return self._client.get(- path,- cast_to=dict[str, object],- options={- "headers": {"anthropic-beta": ANTHROPIC_MANAGED_AGENTS_BETA_HEADER},- "params": params or {},- },- )-- def _list_managed_agents_resource(self, path: str, after: str | None, limit: int) -> tuple[list[dict], str | None]:- params: dict[str, Any] = {"limit": min(max(int(limit), 1), ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT)}- if after:- params["after"] = after- response = self._managed_agents_get(path, params=params)- raw_data = response.get("data", [])- data: list[dict] = [item for item in raw_data if isinstance(item, dict)] if isinstance(raw_data, list) else []- next_cursor = response.get("next_cursor")- return data, next_cursor if isinstance(next_cursor, str) else None-- def list_managed_agents(- self, after: str | None = None, limit: int = ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT- ) -> tuple[list[dict], str | None]:- return self._list_managed_agents_resource("/v1/agents", after=after, limit=limit)-- def list_managed_agent_environments(- self, after: str | None = None, limit: int = ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT- ) -> tuple[list[dict], str | None]:- return self._list_managed_agents_resource("/v1/environments", after=after, limit=limit)-- def list_managed_agent_vaults(- self, after: str | None = None, limit: int = ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT- ) -> tuple[list[dict], str | None]:- return self._list_managed_agents_resource("/v1/vaults", after=after, limit=limit)-- @classmethod- def integration_from_key(- cls,- api_key: str,- team_id: int,- created_by: User,- workspace_label: str | None = None,- force: bool = False,- ) -> Integration:- cls.validate_key(api_key)-- anthropic_kind: str = Integration.IntegrationKind.ANTHROPIC.value- integration_id = workspace_label or f"{ANTHROPIC_DEFAULT_INTEGRATION_ID_PREFIX}{team_id}"- config: dict[str, Any] = {}- if workspace_label:- config["workspace_label"] = workspace_label-- if force:- integration, _ = Integration.objects.update_or_create(- team_id=team_id,- kind=anthropic_kind,- integration_id=integration_id,- defaults={- "config": config,- "sensitive_config": {"api_key": api_key},- "created_by": created_by,- "errors": "",- },- )- return integration-- try:- # Wrap in a savepoint so the unique-constraint IntegrityError below- # aborts only the INSERT, not the surrounding transaction (e.g. the- # outer DRF request atomic block, or the test wrapper).- with transaction.atomic():- return Integration.objects.create(- team_id=team_id,- kind=anthropic_kind,- integration_id=integration_id,- config=config,- sensitive_config={"api_key": api_key},- created_by=created_by,- errors="",- )- except IntegrityError:- raise ValidationError(- {- "config": (- f"An integration with id '{integration_id}' already exists for this team. Choose a different "- "workspace label, delete the existing integration and try again, or set 'force' to true to overwrite the existing integration."- )- }- )---class DatabricksIntegrationError(Exception):- """Error raised when the Databricks integration is not valid."""-- pass---class DatabricksIntegration:- """A Databricks integration.-- The recommended way to connect to Databricks is via OAuth machine-to-machine (M2M) authentication.- See: https://docs.databricks.com/aws/en/dev-tools/python-sql-connector#oauth-machine-to-machine-m2m-authentication-- This works quite differently to regular user-to-machine OAuth as it does not require a real-time user sign in and- consent flow: Instead, the user creates a service principal and provided us with the client ID and client secret to authenticate.-- Attributes:- integration: The integration object.- server_hostname: the Server Hostname value for user's all-purpose compute or SQL warehouse.- client_id: the service principal's UUID or Application ID value.- client_secret: the Secret value for the service principal's OAuth secret.- """-- integration: Integration- server_hostname: str- client_id: str- client_secret: str-- def __init__(self, integration: Integration) -> None:- if integration.kind != Integration.IntegrationKind.DATABRICKS.value:- raise DatabricksIntegrationError("Integration provided is not a Databricks integration")- self.integration = integration-- try:- self.server_hostname = self.integration.config["server_hostname"]- self.client_id = self.integration.sensitive_config["client_id"]- self.client_secret = self.integration.sensitive_config["client_secret"]- except KeyError as e:- raise DatabricksIntegrationError(f"Databricks integration is not valid: {str(e)} missing")-- @classmethod- def integration_from_config(- cls, team_id: int, server_hostname: str, client_id: str, client_secret: str, created_by: User | None = None- ) -> Integration:- # first, validate the host- cls.validate_host(server_hostname)-- config = {- "server_hostname": server_hostname,- }- sensitive_config = {- "client_id": client_id,- "client_secret": client_secret,- }- integration, _ = Integration.objects.update_or_create(- team_id=team_id,- kind=Integration.IntegrationKind.DATABRICKS.value,- integration_id=server_hostname, # Use server_hostname as unique identifier- defaults={- "config": config,- "sensitive_config": sensitive_config,- "created_by": created_by,- },- )- if integration.errors:- integration.errors = ""- integration.save()-- return integration-- @staticmethod- def validate_host(server_hostname: str):- """Validate the Databricks host.-- We check the value is a bare hostname (not a full URL) and that it passes our shared SSRF- guard (rejects unresolvable hosts, internal IPs, cloud-metadata hosts, and internal domain- patterns). This is a quick check (testing connectivity to a SQL warehouse requires a- warehouse http_path in addition to these parameters so it not possible to perform a full- test here).- """- # we expect a hostname, not a full URL- if server_hostname.startswith("http"):- raise DatabricksIntegrationError(- f"Databricks integration is not valid: 'server_hostname' should not be a full URL"- )-- # Databricks is always https, so reuse the shared URL allowlist as the SSRF guard.- allowed, _reason = is_url_allowed(f"https://{server_hostname}")- if not allowed:- raise DatabricksIntegrationError(- f"Databricks integration error: could not validate hostname '{server_hostname}'"- )---class AzureBlobIntegrationError(Exception):- pass---class AzureBlobIntegration:- """Wraps Integration model to provide encrypted credential storage for Azure Blob Storage.-- Attributes:- integration: The underlying Integration model instance.- connection_string: The decrypted Azure Storage connection string.- """-- integration: Integration- connection_string: str-- def __init__(self, integration: Integration) -> None:- if integration.kind != Integration.IntegrationKind.AZURE_BLOB.value:- raise AzureBlobIntegrationError(- f"Integration provided is not an Azure Blob integration (got kind='{integration.kind}')"- )- self.integration = integration-- try:- self.connection_string = self.integration.sensitive_config["connection_string"]- except KeyError:- raise AzureBlobIntegrationError("Azure Blob integration is missing required field: 'connection_string'")-- @classmethod- def integration_from_config(- cls,- team_id: int,- connection_string: str,- created_by: "User | None" = None,- ) -> Integration:- account_name = cls._extract_account_name(connection_string)- if not account_name:- raise AzureBlobIntegrationError(- "Could not extract AccountName from connection string. "- "Ensure it contains 'AccountName=<your-account-name>;'"- )-- config: dict[str, str] = {}- sensitive_config = {- "connection_string": connection_string,- }-- integration, created = Integration.objects.update_or_create(- team_id=team_id,- kind=Integration.IntegrationKind.AZURE_BLOB.value,- integration_id=account_name,- defaults={- "config": config,- "sensitive_config": sensitive_config,- "created_by": created_by,- },- )-- if integration.errors:- integration.errors = ""- integration.save()-- return integration-- @staticmethod- def _extract_account_name(connection_string: str) -> str | None:- for part in connection_string.split(";"):- part = part.strip()- if part.startswith("AccountName="):- return part.split("=", 1)[1]- return None---class IntegrationError(Exception):- """Error raised when an integration or its inputs are not valid."""-- pass---_AWSKindType = Literal[Integration.IntegrationKind.AWS_REDSHIFT, Integration.IntegrationKind.AWS_S3]---def _read_aws_credentials(integration: Integration) -> AWSKeyPair:- try:- # SAFETY: Safety is delegated to the integration which must guarantee- # sensitive_config keys are correctly assigned.- return AWSKeyPair.unsafe_from_strings(- integration.sensitive_config["aws_access_key_id"], integration.sensitive_config["aws_secret_access_key"]- )- except KeyError as e:- raise IntegrationError(f"Integration is not valid: {str(e)} missing")---def _create_unique_aws_integration(- *,- team_id: int,- kind: _AWSKindType,- name: str,- account_id: str,- credentials: AWSKeyPair,- created_by: "User | None",-) -> Integration:- """Create an AWS integration from credentials and an account."""- return _create_unique_named_integration(- team_id=team_id,- kind=kind,- name=name,- config={"name": name, "aws_account_id": account_id},- sensitive_config={- "aws_access_key_id": credentials.access_key_id,- "aws_secret_access_key": credentials.secret_access_key,- },- created_by=created_by,- )---class DuplicateNameError(IntegrationError):- pass---def _create_unique_named_integration(- *,- team_id: int,- kind: str,- name: str,- config: dict[str, str],- sensitive_config: dict[str, str],- created_by: "User | None",-) -> Integration:- """Create an integration, rejecting a name already taken for this team and kind.-- Unlike most integrations, `name` is a free-form user-supplied identifier rather than one derived- from the external connection (an OAuth account id, service-account email, etc.). So we create- rather than upsert and raise a 400 error, on conflicts.- """- try:- # Savepoint so the unique-constraint IntegrityError aborts only this INSERT, not the- # surrounding transaction (e.g. the test wrapper, or any outer atomic block).- with transaction.atomic():- return Integration.objects.create(- team_id=team_id,- kind=kind,- integration_id=name,- config=config,- sensitive_config=sensitive_config,- created_by=created_by,- )- except IntegrityError:- raise DuplicateNameError(f"An integration named '{name}' already exists")---def is_unique_aws_role_by_organization_id(aws_role_arn: str, organization_id: str) -> bool:- """Check if the AWS role is only in one organization.-- This is used as a security measure to block multiple organizations from- assuming the same role.-- In the future we may lift this restriction, but initially we want to make sure about- AWS role ownership with this check. This complements other runtime checks in- batch exports; see `get_credentials_using_user_aws_role` in- `s3_batch_export.py`.- """- has_same_aws_role_integrations = (- Integration.objects.select_related("team__organization")- .filter(- kind__in=(Integration.IntegrationKind.AWS_S3, Integration.IntegrationKind.AWS_REDSHIFT),- config__aws_role_arn=aws_role_arn,- )- .exclude(team__organization_id=organization_id)- ).exists()-- if has_same_aws_role_integrations:- return False-- return True---def _return_non_empty_str_from_config(- config: Mapping,- key: str,- friendly_name: str,- kind: str,-) -> str:- if (value := config.get(key)) is not None and isinstance(value, str) and len(value) > 0:- return value- raise IntegrationError(f"{friendly_name} is required for {kind} integration")---def _return_non_empty_str_from_config_for_aws(config: Mapping, key: str, friendly_name: str) -> str:- return _return_non_empty_str_from_config(config, key, friendly_name=friendly_name, kind="AWS")---def validate_aws_credentials(aws_access_key_id: str, aws_secret_access_key: str) -> str:- """Validate AWS credentials via STS GetCallerIdentity, returning the AWS account id.-- GetCallerIdentity requires no IAM permissions, so it verifies the credentials are valid- without assuming any particular S3 policy. It hits the fixed global AWS STS endpoint, so- there is no user-controlled endpoint and no SSRF surface (unlike S3-compatible).-- This runs synchronously on the request thread, so the timeout budget is kept tight:- a single attempt (no retry) bounds the worst case at ~10s (connect + read) if STS is- unreachable, rather than blocking the worker while botocore retries.- """- import boto3 # noqa: PLC0415 — keeps botocore off the module import path (startup time)- from botocore.config import Config # noqa: PLC0415- from botocore.exceptions import BotoCoreError, ClientError # noqa: PLC0415-- client = boto3.client(- "sts",- aws_access_key_id=aws_access_key_id,- aws_secret_access_key=aws_secret_access_key,- config=Config(connect_timeout=5, read_timeout=5, retries={"max_attempts": 1}),- )- try:- identity = client.get_caller_identity()- except ClientError as e:- message = e.response.get("Error", {}).get("Message") or str(e)- raise IntegrationError(f"AWS credentials are not valid: {message}")- except BotoCoreError as e:- raise IntegrationError(f"Could not validate AWS credentials: {e}")-- return identity["Account"]---class AWSRoleBasedIntegration:- """An AWS integration storing a customer's AWS role."""-- integration: Integration- aws_role_arn: str-- integration_kind: ClassVar[_AWSKindType]-- def __init__(self, integration: Integration) -> None:- if integration.kind != self.integration_kind:- raise IntegrationError(- "Integration provided is not the expected AWS integration "- f"(got kind='{integration.kind}', expected kind='{self.integration_kind}')"- )- self.integration = integration- try:- self.aws_role_arn = integration.config["aws_role_arn"]- except KeyError:- raise IntegrationError("AWS integration is not valid: 'aws_role_arn' missing")-- @classmethod- def integration_from_config(- cls,- team_id: int,- organization_id: str,- created_by: "User | None" = None,- **config,- ) -> Integration:- name = _return_non_empty_str_from_config_for_aws(config, "name", "A name")- aws_role_arn = _return_non_empty_str_from_config_for_aws(config, "aws_role_arn", "A valid role ARN")-- if not is_unique_aws_role_by_organization_id(aws_role_arn, organization_id):- raise ValidationError("Cannot create AWS integration: Invalid role")-- return _create_unique_named_integration(- team_id=team_id,- kind=cls.integration_kind,- name=name,- config={"name": name, "aws_role_arn": aws_role_arn},- sensitive_config={},- created_by=created_by,- )---class AWSS3RoleBasedIntegration(AWSRoleBasedIntegration):- """An AWS S3 integration storing a customer's AWS role."""-- integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_S3]] = Integration.IntegrationKind.AWS_S3---class AWSRedshiftRoleBasedIntegration(AWSRoleBasedIntegration):- """An AWS Redshift integration storing a customer's AWS role."""-- integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_REDSHIFT]] = (- Integration.IntegrationKind.AWS_REDSHIFT- )---class AWSCredentialsIntegration:- """AWS integration for any service that requires storing long-lived AWS credentials.-- Unlike `S3CompatibleIntegration` it has no `endpoint_url` because an AWS- integration must never be pointed at an arbitrary endpoint (SSRF boundary).- """-- integration: Integration- credentials: AWSKeyPair-- integration_kind: ClassVar[_AWSKindType]-- def __init__(self, integration: Integration) -> None:- if integration.kind != self.integration_kind:- raise IntegrationError(- "Integration provided is not the expected AWS integration "- f"(got kind='{integration.kind}', expected kind='{self.integration_kind}')"- )- self.integration = integration- self.credentials = _read_aws_credentials(integration)-- @property- def aws_account_id(self) -> str | None:- """The AWS account id resolved from the credentials at create time, if available."""- return self.integration.config.get("aws_account_id")-- @property- def aws_access_key_id(self) -> str:- return self.credentials.access_key_id-- @property- def aws_secret_access_key(self) -> str:- return self.credentials.secret_access_key-- @classmethod- def integration_from_config(- cls,- team_id: int,- created_by: "User | None" = None,- **config,- ) -> Integration:- name = _return_non_empty_str_from_config_for_aws(config, "name", "A name")- aws_access_key_id = _return_non_empty_str_from_config_for_aws(- config,- "aws_access_key_id",- "Access key ID",- )- aws_secret_access_key = _return_non_empty_str_from_config_for_aws(- config, "aws_secret_access_key", "Secret access key"- )-- # Fail fast on invalid/expired credentials, and capture the (non-sensitive) account id.- account_id = validate_aws_credentials(aws_access_key_id, aws_secret_access_key)-- # SAFETY: We check that each value is non-empty and str type, and, by- # validating the credentials directly with AWS, we ensure each of these- # values is what they say they are. This call is safe.- credentials = AWSKeyPair.unsafe_from_strings(aws_access_key_id, aws_secret_access_key)-- # `name` is the unencrypted, frontend-visible identifier — never an AWS credential, which is- # treated as a secret. The account id is non-sensitive and kept for display/debugging.- return _create_unique_aws_integration(- team_id=team_id,- kind=cls.integration_kind,- name=name,- account_id=account_id,- credentials=credentials,- created_by=created_by,- )---class AWSS3Integration(AWSCredentialsIntegration):- """An AWS S3 integration storing reusable AWS credentials.-- Holds only credentials; bucket, region, prefix and other export-specific settings stay on the- batch export destination config, so one credential can be reused across many buckets/regions.- """-- integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_S3]] = Integration.IntegrationKind.AWS_S3---class AWSRedshiftIntegration(AWSCredentialsIntegration):- """An AWS Redshift integration storing reusable AWS credentials."""-- integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_REDSHIFT]] = (- Integration.IntegrationKind.AWS_REDSHIFT- )---def _return_non_empty_str_from_config_for_s3_compatible(config: Mapping, key: str, friendly_name: str) -> str:- return _return_non_empty_str_from_config(config, key, friendly_name=friendly_name, kind="S3-compatible")---class S3CompatibleIntegration:- """An S3-compatible storage integration (Cloudflare R2, DigitalOcean Spaces, Hetzner, etc.).-- Holds the same credentials as `AwsS3Integration` plus the provider `endpoint_url` (non-sensitive),- since credentials are bound to a specific S3-compatible provider. `integration_from_config`- SSRF-validates `endpoint_url`, so callers don't have to.-- bucket, region, prefix and other export-specific settings stay on the batch export destination- config, so one credential can be reused across many buckets/regions.- """-- integration: Integration- credentials: AWSKeyPair- endpoint_url: str-- def __init__(self, integration: Integration) -> None:- if integration.kind != Integration.IntegrationKind.S3_COMPATIBLE:- raise IntegrationError(- f"Integration provided is not an S3-compatible integration (got kind='{integration.kind}')"- )- self.integration = integration- self.credentials = _read_aws_credentials(integration)- try:- self.endpoint_url = integration.config["endpoint_url"]- except KeyError:- raise IntegrationError("S3-compatible integration is missing required field: 'endpoint_url'")-- @property- def aws_access_key_id(self) -> str:- return self.credentials.access_key_id-- @property- def aws_secret_access_key(self) -> str:- return self.credentials.secret_access_key-- @classmethod- def integration_from_config(- cls,- team_id: int,- created_by: "User | None" = None,- **config,- ) -> Integration:- name = _return_non_empty_str_from_config_for_s3_compatible(- config,- "name",- friendly_name="A name",- )- aws_access_key_id = _return_non_empty_str_from_config_for_s3_compatible(- config, "aws_access_key_id", "Access key ID"- )- aws_secret_access_key = _return_non_empty_str_from_config_for_s3_compatible(- config, "aws_secret_access_key", "Secret access key"- )- endpoint_url = _return_non_empty_str_from_config_for_s3_compatible(config, "endpoint_url", "Endpoint URL")-- # SSRF protection — credentials must not be testable against an attacker-controlled endpoint.- allowed, error = is_url_allowed(endpoint_url)- if not allowed:- raise IntegrationError(f"Invalid endpoint URL: {error}")-- return _create_unique_named_integration(- team_id=team_id,- kind=Integration.IntegrationKind.S3_COMPATIBLE,- name=name,- config={"name": name, "endpoint_url": endpoint_url},- sensitive_config={- "aws_access_key_id": aws_access_key_id,- "aws_secret_access_key": aws_secret_access_key,- },- created_by=created_by,- )---class StripeIntegration:- integration: Integration-- # Every endpoint services/stripe-app/src/posthog/client.ts calls, and nothing else.- # This token is readable by every member of the customer's Stripe account, so anything- # granted here is granted to all of them. Read-only by design; do not add a write scope.- SCOPES: str = " ".join(- [- "customer_journey:read",- "experiment:read",- "feature_flag:read",- "insight:read",- "query:read",- ]- )-- def __init__(self, integration: Integration) -> None:- if integration.kind != "stripe":- raise ValueError(f"Expected stripe integration, got {integration.kind}")- self.integration = integration-- def _stripe_client(self) -> "StripeClient | None":- # Returns None when the required env vars are missing so callers can skip Stripe- # API calls without raising past their per-secret error handling.- from stripe import StripeClient # noqa: PLC0415-- try:- oauth_config = OauthIntegration.oauth_config_for_kind("stripe")- except NotImplementedError as e:- capture_exception(- e,- {- "stripe_user_id": self.integration.integration_id,- },- )- return None- return StripeClient(oauth_config.client_secret)-- def write_posthog_secrets(self, team_id: int, created_by: "User") -> None:- """Write PostHog OAuth tokens to Stripe's Secret Store so the Stripe App can call PostHog APIs."""-- oauth_app = self._get_posthog_oauth_app()- if not oauth_app:- logger.warning("PostHog OAuth app not found, cannot write secrets to Stripe")- return-- access_token_value = generate_random_oauth_access_token(None)- access_token = OAuthAccessToken.objects.create(- application=oauth_app,- token=access_token_value,- user=created_by,- expires=timezone.now() + timedelta(days=14),- scope=self.SCOPES,- scoped_teams=[team_id],- )-- refresh_token_value = generate_random_oauth_refresh_token(None)- OAuthRefreshToken.objects.create(- application=oauth_app,- token=refresh_token_value,- user=created_by,- access_token=access_token,- scoped_teams=[team_id],- )-- stripe_user_id = self.integration.integration_id- if not stripe_user_id:- raise ValueError("Missing stripe_user_id on integration")-- region = get_instance_region() or "us"-- secrets = {- "posthog_region": region.lower(),- "posthog_access_token": access_token_value,- "posthog_refresh_token": refresh_token_value,- "posthog_project_id": str(team_id),- "posthog_oauth_client_id": oauth_app.client_id,- }-- client = self._stripe_client()- if client is None:- return-- for name, payload in secrets.items():- try:- client.apps.secrets.create(- params={- "scope": {"type": "account"},- "name": name,- "payload": payload,- },- options={"stripe_account": stripe_user_id},- )- except Exception as e:- capture_exception(- e,- {- "secret_name": name,- "stripe_user_id": stripe_user_id,- },- )-- def clear_posthog_secrets(self) -> None:- """Best-effort clear of PostHog secrets from Stripe and revoke local OAuth tokens."""- stripe_user_id = self.integration.integration_id- if not stripe_user_id:- raise ValueError("Missing stripe_user_id on integration")-- client = self._stripe_client()- if client is None:- self._destroy_posthog_oauth_tokens()- return-- for name in (- "posthog_region",- "posthog_access_token",- "posthog_refresh_token",- "posthog_project_id",- "posthog_oauth_client_id",- ):- try:- client.apps.secrets.delete_where(- params={- "scope": {"type": "account"},- "name": name,- },- options={"stripe_account": stripe_user_id},- )- except Exception as e:- capture_exception(- e,- {- "secret_name": name,- "stripe_user_id": stripe_user_id,- },- )-- self._destroy_posthog_oauth_tokens()-- def _destroy_posthog_oauth_tokens(self) -> None:- """Delete the local OAuth access and refresh tokens created for this Stripe integration."""- oauth_app = self._get_posthog_oauth_app()- if not oauth_app:- return-- team_id = self.integration.team_id- access_tokens = OAuthAccessToken.objects.filter(- application=oauth_app,- scoped_teams__contains=[team_id],- )- # Delete refresh tokens first since their FK to access_token is SET_NULL- OAuthRefreshToken.objects.filter(access_token__in=access_tokens).delete()- access_tokens.delete()-- def _get_posthog_oauth_app(self):- if settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID:- return OAuthApplication.objects.filter(client_id=settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID).first()-- return None---class Credentials(NamedTuple):- """PostgreSQL credentials."""-- user: str- password: str---class Authority(NamedTuple):- """PostgreSQL authority parameters."""-- host: str- port: int---MISSING_CERT_PATH = "/tmp/posthog/batch-exports/MISSING.crt"---class TLS(NamedTuple):- """PostgreSQL TLS parameters.-- NOTE: If a root CA file exists in the default '~/.postgresql/root.crt' path libpq- treats `sslmode='require'` as `sslmode='verify-ca'`.-- **This is not what we want**-- If a user has not provided a root certificate (by setting `ssl_root_cert` to the- cert's contents) or asked to use the system store explicitly (by setting- `ssl_root_cert='system'`, in version >=16), then whatever is present in the default- path should not be used.-- This could be a problem if, for example, another application or library or- dependency bundled in the same container ships with a default cert.-- For this reason we require `ssl_root_cert` to not be `None` (as that would translate- to the default path), and it defaults to an application-scoped path under `/tmp/`.- """-- ssl_mode: Literal["prefer", "require", "verify-ca", "verify-full"]- ssl_root_cert: str | Literal["system"] = MISSING_CERT_PATH---_PostgreSQLServerKindType = Literal[Integration.IntegrationKind.AWS_REDSHIFT, Integration.IntegrationKind.POSTGRESQL]---class PostgreSQLServerIntegration:- """Base class for any integration targetting a PostgreSQL-server."""-- integration: Integration- integration_kind: ClassVar[_PostgreSQLServerKindType]-- def __init__(self, integration: Integration) -> None:- if integration.kind != self.integration_kind:- raise IntegrationError(- "Integration provided is not the expected PostgreSQL server integration "- f"(got kind='{integration.kind}', expected kind='{self.integration_kind}')"- )-- self.integration = integration-- @classmethod- def integration_from_config(- cls,- team_id: int,- created_by: User | None = None,- **config,- ) -> Integration:- from products.batch_exports.backend.api.batch_export import resolve_and_validate_host-- host = _return_non_empty_str_from_config(config, "host", friendly_name="Host", kind=cls.integration_kind)- try:- resolve_and_validate_host(host)- except ValueError:- raise IntegrationError(f"Provided host '{host}' is not valid")-- port = config.get("port", None)- try:- port = int(port) # type: ignore- except (TypeError, ValueError):- raise IntegrationError("Port must be an integer")-- if port > 65535 or port < 0:- raise IntegrationError(f"A valid port is required for an {cls.integration_kind} integration")-- user = _return_non_empty_str_from_config(- config,- "user",- friendly_name="A username",- kind=cls.integration_kind,- )- password = _return_non_empty_str_from_config(- config,- "password",- friendly_name="A password",- kind=cls.integration_kind,- )-- ssl_mode = config.get("ssl_mode", "require")- if ssl_mode not in ("require", "verify-ca", "verify-full"):- raise IntegrationError("SSL mode must be one of: require, verify-ca, verify-full")-- ssl_root_cert = config.get("ssl_root_cert", None)- if ssl_mode in ("verify-ca", "verify-full"):- if not ssl_root_cert:- raise IntegrationError("SSL root certificate must be provided when verifying server certificates")- if not isinstance(ssl_root_cert, str):- raise IntegrationError("SSL root certificate must be a string")-- integration, _ = Integration.objects.update_or_create(- team_id=team_id,- kind=cls.integration_kind,- integration_id=f"{team_id}-{host}-{port}-{user}",- defaults={- "config": {- "host": host,- "port": port,- "user": user,- "ssl_mode": ssl_mode,- "ssl_root_cert": ssl_root_cert,- },- "sensitive_config": {- "password": password,- },- "created_by": created_by,- },- )-- if integration.errors:- integration.errors = ""- integration.save()-- return integration-- def authority(self) -> Authority:- return Authority(self.integration.config["host"], self.integration.config["port"])-- def credentials(self) -> Credentials:- return Credentials(self.integration.config["user"], self.integration.sensitive_config["password"])-- def tls(self) -> TLS:- if (ssl_root_cert := self.integration.config.get("ssl_root_cert", None)) is not None:- return TLS(- ssl_mode=self.integration.config["ssl_mode"],- ssl_root_cert=ssl_root_cert,- )- else:- # Preserve the default ssl_root_cert if one was not provided- return TLS(ssl_mode=self.integration.config["ssl_mode"])---class PostgreSQLIntegration(PostgreSQLServerIntegration):- integration_kind: ClassVar[Literal[Integration.IntegrationKind.POSTGRESQL]] = Integration.IntegrationKind.POSTGRESQL---class RedshiftIntegration(PostgreSQLServerIntegration):- integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_REDSHIFT]] = (- Integration.IntegrationKind.AWS_REDSHIFT- )---@receiver(models.signals.post_delete, sender=Integration)-def cleanup_ses_identity_on_integration_delete(sender: Any, instance: Integration, **kwargs: Any) -> None:- # A post_delete signal (rather than viewset perform_destroy) so SES identities are- # also cleaned up when integrations die via cascade, e.g. project or org deletion.- # Leaving the identity behind permanently blocks the domain for every other- # organization via the foreign-tenant guard in SESProvider.create_email_domain.- if instance.kind != "email" or instance.config.get("provider") != "ses":- return- domain = instance.config.get("domain")- if not domain:- return-- from posthog.tasks.integrations import (- delete_ses_identity_if_unused, # noqa: PLC0415 - breaks circular import with the tasks module- )-- transaction.on_commit(lambda: delete_ses_identity_if_unused.delay(domain))---class SnowflakeIntegrationError(Exception):- """Error raised when a Snowflake integration is not valid."""-- pass---# A Snowflake account identifier: an alphanumeric first character followed by alphanumerics, dots,-# hyphens and underscores.-_SNOWFLAKE_ACCOUNT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")---class SnowflakeIntegration:- """A Snowflake integration storing reusable Snowflake credentials.-- Holds the account, user, and authentication material (a password, or a key-pair) needed to- connect to Snowflake. Database, warehouse, schema, table name and role stay on the batch export- destination config, so one credential can be reused across many exports.-- Supports both of Snowflake's authentication types:- - "password": `password` in sensitive_config.- - "keypair": `private_key` (PEM) plus optional `private_key_passphrase` in sensitive_config.-- Rather than using an auto-generated ID (e.g. '{account}-{user}-{auth_type}'), we use a- user-provided name, similarly to how we do for S3 integrations. The benefits of this approach- are:- - a user can create multiple integrations for the same account, allowing for credential rotation- - we don't overwrite an existing integration if creating an integration for the same account,- so existing exports can continue to use the old credentials- - a human-readable name in the UI- """-- integration: Integration- account: str- user: str- authentication_type: str-- def __init__(self, integration: Integration) -> None:- if integration.kind != Integration.IntegrationKind.SNOWFLAKE:- raise SnowflakeIntegrationError(- f"Integration provided is not a Snowflake integration (got kind='{integration.kind}')"- )- self.integration = integration- try:- self.account = integration.config["account"]- self.user = integration.config["user"]- self.authentication_type = integration.config["authentication_type"]- except KeyError as e:- raise SnowflakeIntegrationError(f"Snowflake integration is not valid: {str(e)} missing")-- @property- def password(self) -> str | None:- return self.integration.sensitive_config.get("password")-- @property- def private_key(self) -> str | None:- return self.integration.sensitive_config.get("private_key")-- @property- def private_key_passphrase(self) -> str | None:- return self.integration.sensitive_config.get("private_key_passphrase")-- @staticmethod- def validate_account(account: str) -> None:- """Validate the Snowflake account identifier format.-- Snowflake has no user-supplied host: the connector derives the host from the account, always- on a fixed Snowflake-owned domain suffix, so there is no SSRF surface as there is for- Databricks or S3-compatible. We validate the identifier's shape to reject URLs and arbitrary- hosts (for example, anything with a scheme, `/`, `@`, `:`, `#`, or whitespace).- """- if not _SNOWFLAKE_ACCOUNT_RE.fullmatch(account):- raise SnowflakeIntegrationError(- f"Snowflake integration is not valid: invalid account identifier '{account}'"- )-- @classmethod- def integration_from_config(- cls,- team_id: int,- name: str,- account: str,- user: str,- authentication_type: str,- password: str | None = None,- private_key: str | None = None,- private_key_passphrase: str | None = None,- created_by: User | None = None,- ) -> Integration:- if not (name and account and user):- raise SnowflakeIntegrationError("Name, account, and user must be provided")- if not all(isinstance(value, str) for value in (name, account, user, authentication_type)):- raise SnowflakeIntegrationError("Name, account, user, and authentication type must be strings")- if not all(- value is None or isinstance(value, str) for value in (password, private_key, private_key_passphrase)- ):- raise SnowflakeIntegrationError("Password, private key, and private key passphrase must be strings")-- cls.validate_account(account)-- sensitive_config: dict[str, str] = {}- if authentication_type == "password":- if not password:- raise SnowflakeIntegrationError("Password is required for password authentication")- sensitive_config["password"] = password- elif authentication_type == "keypair":- if not private_key:- raise SnowflakeIntegrationError("Private key is required for key-pair authentication")- sensitive_config["private_key"] = private_key- if private_key_passphrase:- sensitive_config["private_key_passphrase"] = private_key_passphrase- else:- raise SnowflakeIntegrationError(f"Invalid authentication type: {authentication_type}")-- # `name` is the unencrypted, frontend-visible identifier — never a credential. Unlike most- # integrations, it is a free-form user-supplied name rather than one derived from the- # connection, so we create rather than upsert: re-using a name is a 400, not a silent- # overwrite of an unrelated credential set.- try:- # Savepoint so the unique-constraint IntegrityError aborts only this INSERT, not the- # surrounding transaction.- with transaction.atomic():- return Integration.objects.create(- team_id=team_id,- kind=Integration.IntegrationKind.SNOWFLAKE,- integration_id=name,- config={- "name": name,- "account": account,- "user": user,- "authentication_type": authentication_type,- },- sensitive_config=sensitive_config,- created_by=created_by,- )- except IntegrityError:- raise SnowflakeIntegrationError(f"An integration named '{name}' already exists")diff --git a/posthog/models/integration/__init__.py b/posthog/models/integration/__init__.pynew file mode 100644index 000000000000..567c3dcf2654--- /dev/null+++ b/posthog/models/integration/__init__.py@@ -0,0 +1,248 @@+"""Integration model and per-provider business logic, one module per concern.++Hundreds of call sites do `from posthog.models.integration import X`, so this package+re-exports the full public surface — the one place `no-init-reexports.yaml` allows it.+Internal cross-module references and mock patches must target the defining submodule+directly (e.g. `posthog.models.integration.slack.SlackIntegration`), never this shim.+"""++from .anthropic import (+ ANTHROPIC_CLIENT_TIMEOUT_SECONDS,+ ANTHROPIC_DEFAULT_INTEGRATION_ID_PREFIX,+ ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT,+ ANTHROPIC_MANAGED_AGENTS_BETA_HEADER,+ ANTHROPIC_WORKSPACE_LABEL_MAX_LENGTH,+ AnthropicIntegration,+ AnthropicIntegrationError,+)+from .aws import (+ AWSCredentialsIntegration,+ AWSRedshiftIntegration,+ AWSRedshiftRoleBasedIntegration,+ AWSRoleBasedIntegration,+ AWSS3Integration,+ AWSS3RoleBasedIntegration,+ DuplicateNameError,+ S3CompatibleIntegration,+ is_unique_aws_role_by_organization_id,+ validate_aws_credentials,+)+from .azure_blob import AzureBlobIntegration, AzureBlobIntegrationError+from .clickup import ClickUpIntegration+from .common import ERROR_TOKEN_REFRESH_FAILED, META_GRAPH_API_VERSION, IntegrationError, dot_get+from .databricks import DatabricksIntegration, DatabricksIntegrationError+from .email import EmailIntegration, cleanup_ses_identity_on_integration_delete+from .github import (+ GITHUB_DEFAULT_BRANCH_CACHE_TTL_SECONDS,+ GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,+ GitHubInstallationAccess,+ GitHubInstallationAccessFetchError,+ GitHubIntegration,+ GitHubIntegrationError,+ GitHubUserAuthorization,+ github_account_type,+ invalidate_github_repository_caches_for_installation,+)+from .gitlab import GitLabIntegration, GitLabIntegrationError+from .google_ads import GoogleAdsIntegration, google_ads_hierarchy_level+from .google_cloud import (+ GoogleCloudIntegration,+ GoogleCloudServiceAccountIntegration,+ is_unique_service_account_by_organization_id,+)+from .jira import JiraIntegration+from .linear import LinearIntegration+from .linkedin_ads import LinkedInAdsIntegration+from .meta import InstagramIntegration, MetaAdsIntegration, MetaGraphIntegration+from .model import (+ Integration,+ IntegrationManager,+ IntegrationQuerySet,+ UndecryptedIntegrationSecretError,+ aget_integration_by_id,+ defer_repository_cache_fields,+ integration_secret_decrypt_counter,+)+from .oauth import (+ INSTAGRAM_OAUTH_SCOPE,+ POSTHOG_CONNECT_ALLOWED_REGIONS,+ POSTHOG_CONNECT_DEFAULT_SCOPES,+ POSTHOG_CONNECT_GRANTABLE_SCOPES,+ POSTHOG_CONNECT_IDENTITY_SCOPES,+ POSTHOG_CONNECT_KIND,+ POSTHOG_SLACK_SCOPE,+ SALESFORCE_OAUTH_KINDS,+ OauthConfig,+ OauthIntegration,+ posthog_connect_base_url,+)+from .postgres import (+ MISSING_CERT_PATH,+ TLS,+ Authority,+ Credentials,+ PostgreSQLIntegration,+ PostgreSQLServerIntegration,+ RedshiftIntegration,+)+from .push import (+ CONFIG_PUSH_IDENTITY_PUBLIC_KEYS,+ CONFIG_PUSH_IDENTITY_VERIFICATION,+ MAX_PUSH_IDENTITY_PUBLIC_KEYS,+ PUSH_IDENTITY_VERIFICATION_MODES,+ ApplePushIntegration,+ FirebaseIntegration,+ preserved_push_config,+)+from .refresh_tracking import (+ CONFIG_LEGACY_OAUTH_CLIENT,+ REFRESH_BACKOFF_BASE_SECONDS,+ REFRESH_BACKOFF_MAX_SECONDS,+ REFRESH_FAILURE_REASON_HTTP_5XX,+ REFRESH_FAILURE_REASON_INVALID_CLIENT,+ REFRESH_FAILURE_REASON_INVALID_GRANT,+ REFRESH_FAILURE_REASON_NETWORK,+ REFRESH_FAILURE_REASON_OTHER,+ REFRESH_FAILURE_REASON_RATE_LIMITED,+ REFRESH_FAILURE_REASON_UNREADABLE_SECRET,+ REFRESH_TERMINAL_FAILURE_COUNT,+ issuing_oauth_client_ids,+ oauth_refresh_counter,+ oauth_refresh_failure_reason,+ oauth_refresh_terminal_counter,+ record_oauth_client_used,+ record_refresh_failure,+ record_refresh_success,+ refresh_backoff_active,+)+from .slack import (+ PRIVATE_CHANNEL_WITHOUT_ACCESS,+ SLACK_CHANNELS_MAX_PAGES,+ SLACK_CHANNELS_PAGE_SIZE,+ SLACK_INTEGRATION_KINDS,+ SlackIntegration,+ SlackIntegrationError,+ SlackRequestSignature,+ sign_slack_request,+ validate_slack_request,+)+from .snowflake import SnowflakeIntegration, SnowflakeIntegrationError+from .stripe import StripeIntegration+from .twilio import TwilioIntegration++__all__ = [+ "UndecryptedIntegrationSecretError",+ "integration_secret_decrypt_counter",+ "IntegrationQuerySet",+ "IntegrationManager",+ "Integration",+ "defer_repository_cache_fields",+ "aget_integration_by_id",+ "IntegrationError",+ "META_GRAPH_API_VERSION",+ "dot_get",+ "ERROR_TOKEN_REFRESH_FAILED",+ "oauth_refresh_counter",+ "oauth_refresh_terminal_counter",+ "REFRESH_BACKOFF_BASE_SECONDS",+ "REFRESH_BACKOFF_MAX_SECONDS",+ "REFRESH_TERMINAL_FAILURE_COUNT",+ "CONFIG_LEGACY_OAUTH_CLIENT",+ "REFRESH_FAILURE_REASON_INVALID_GRANT",+ "REFRESH_FAILURE_REASON_INVALID_CLIENT",+ "REFRESH_FAILURE_REASON_HTTP_5XX",+ "REFRESH_FAILURE_REASON_NETWORK",+ "REFRESH_FAILURE_REASON_RATE_LIMITED",+ "REFRESH_FAILURE_REASON_OTHER",+ "REFRESH_FAILURE_REASON_UNREADABLE_SECRET",+ "oauth_refresh_failure_reason",+ "record_refresh_failure",+ "record_refresh_success",+ "record_oauth_client_used",+ "issuing_oauth_client_ids",+ "refresh_backoff_active",+ "CONFIG_PUSH_IDENTITY_VERIFICATION",+ "PUSH_IDENTITY_VERIFICATION_MODES",+ "CONFIG_PUSH_IDENTITY_PUBLIC_KEYS",+ "MAX_PUSH_IDENTITY_PUBLIC_KEYS",+ "preserved_push_config",+ "FirebaseIntegration",+ "ApplePushIntegration",+ "INSTAGRAM_OAUTH_SCOPE",+ "OauthConfig",+ "POSTHOG_SLACK_SCOPE",+ "SALESFORCE_OAUTH_KINDS",+ "POSTHOG_CONNECT_KIND",+ "POSTHOG_CONNECT_ALLOWED_REGIONS",+ "POSTHOG_CONNECT_DEFAULT_SCOPES",+ "POSTHOG_CONNECT_IDENTITY_SCOPES",+ "POSTHOG_CONNECT_GRANTABLE_SCOPES",+ "posthog_connect_base_url",+ "OauthIntegration",+ "PRIVATE_CHANNEL_WITHOUT_ACCESS",+ "SlackIntegrationError",+ "SLACK_INTEGRATION_KINDS",+ "SLACK_CHANNELS_PAGE_SIZE",+ "SLACK_CHANNELS_MAX_PAGES",+ "SlackIntegration",+ "SlackRequestSignature",+ "sign_slack_request",+ "validate_slack_request",+ "google_ads_hierarchy_level",+ "GoogleAdsIntegration",+ "is_unique_service_account_by_organization_id",+ "GoogleCloudServiceAccountIntegration",+ "GoogleCloudIntegration",+ "LinkedInAdsIntegration",+ "ClickUpIntegration",+ "EmailIntegration",+ "cleanup_ses_identity_on_integration_delete",+ "LinearIntegration",+ "JiraIntegration",+ "GITHUB_DEFAULT_BRANCH_CACHE_TTL_SECONDS",+ "GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS",+ "GitHubUserAuthorization",+ "GitHubInstallationAccess",+ "GitHubInstallationAccessFetchError",+ "invalidate_github_repository_caches_for_installation",+ "github_account_type",+ "GitHubIntegration",+ "GitHubIntegrationError",+ "GitLabIntegrationError",+ "GitLabIntegration",+ "MetaGraphIntegration",+ "MetaAdsIntegration",+ "InstagramIntegration",+ "TwilioIntegration",+ "ANTHROPIC_MANAGED_AGENTS_BETA_HEADER",+ "ANTHROPIC_DEFAULT_INTEGRATION_ID_PREFIX",+ "ANTHROPIC_WORKSPACE_LABEL_MAX_LENGTH",+ "ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT",+ "ANTHROPIC_CLIENT_TIMEOUT_SECONDS",+ "AnthropicIntegrationError",+ "AnthropicIntegration",+ "DatabricksIntegrationError",+ "DatabricksIntegration",+ "AzureBlobIntegrationError",+ "AzureBlobIntegration",+ "DuplicateNameError",+ "is_unique_aws_role_by_organization_id",+ "validate_aws_credentials",+ "AWSRoleBasedIntegration",+ "AWSS3RoleBasedIntegration",+ "AWSRedshiftRoleBasedIntegration",+ "AWSCredentialsIntegration",+ "AWSS3Integration",+ "AWSRedshiftIntegration",+ "S3CompatibleIntegration",+ "StripeIntegration",+ "Credentials",+ "Authority",+ "MISSING_CERT_PATH",+ "TLS",+ "PostgreSQLServerIntegration",+ "PostgreSQLIntegration",+ "RedshiftIntegration",+ "SnowflakeIntegrationError",+ "SnowflakeIntegration",+]diff --git a/posthog/models/integration/anthropic.py b/posthog/models/integration/anthropic.pynew file mode 100644index 000000000000..c9da24e6b05a--- /dev/null+++ b/posthog/models/integration/anthropic.py@@ -0,0 +1,194 @@+"""Anthropic Managed Agents integration."""++from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from anthropic import Anthropic++from django.db import transaction++import structlog+from rest_framework.exceptions import ValidationError++from posthog.models.user import User+from posthog.models.utils import IntegrityError++from . import model++logger = structlog.get_logger(__name__)+++ANTHROPIC_MANAGED_AGENTS_BETA_HEADER = "managed-agents-2026-04-01"++ANTHROPIC_DEFAULT_INTEGRATION_ID_PREFIX = "workspace-"++ANTHROPIC_WORKSPACE_LABEL_MAX_LENGTH = 100++ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT = 100++# 5s connect / 15s read are aggressive enough to keep gunicorn workers from+# being pinned for ~minutes on a slow Anthropic upstream while still leaving+# headroom for normal API latency.+ANTHROPIC_CLIENT_TIMEOUT_SECONDS = 15.0+++class AnthropicIntegrationError(Exception):+ """Raised when the AnthropicIntegration is constructed with an invalid Integration row."""+++def _build_anthropic_client(api_key: str) -> "Anthropic":+ # Tight timeouts and no SDK-side retries: we don't want a slow upstream to+ # multiply request time by 3 (default `max_retries=2`) inside a Django worker.+ from anthropic import Anthropic # noqa: PLC0415++ return Anthropic(api_key=api_key, timeout=ANTHROPIC_CLIENT_TIMEOUT_SECONDS, max_retries=0)+++class AnthropicIntegration:+ integration: model.Integration+ _client: "Anthropic"++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != model.Integration.IntegrationKind.ANTHROPIC.value:+ # Internal misuse, not a user-input issue.+ raise AnthropicIntegrationError(+ f"AnthropicIntegration init called with Integration kind={integration.kind!r}"+ )+ self.integration = integration+ api_key = integration.sensitive_config.get("api_key")+ if not api_key:+ raise AnthropicIntegrationError(f"Anthropic integration {integration.id} is missing 'api_key'")+ self._client = _build_anthropic_client(api_key)++ @staticmethod+ def validate_key(api_key: str) -> None:+ # Validate by hitting the actual managed-agents surface so a key without+ # beta access fails at create time instead of silently failing later.+ from anthropic import ( # noqa: PLC0415+ APIConnectionError,+ APIStatusError,+ AuthenticationError,+ PermissionDeniedError,+ )++ try:+ client = _build_anthropic_client(api_key)+ client.get(+ "/v1/agents",+ cast_to=dict[str, object],+ options={+ "headers": {"anthropic-beta": ANTHROPIC_MANAGED_AGENTS_BETA_HEADER},+ "params": {"limit": 1},+ },+ )+ except AuthenticationError:+ raise ValidationError({"api_key": "Invalid Anthropic API key"})+ except PermissionDeniedError:+ raise ValidationError(+ {+ "api_key": (+ "Anthropic API key is missing required permissions. Make sure the key has access to the "+ "Managed Agents beta in your Anthropic console."+ )+ }+ )+ except APIConnectionError:+ logger.warning("anthropic_validate_key_connection_error", exc_info=True)+ raise ValidationError(+ {"api_key": "Could not reach Anthropic to validate the API key. Check your network and try again."}+ )+ except APIStatusError as e:+ logger.warning("anthropic_validate_key_status_error", status_code=e.status_code, exc_info=True)+ raise ValidationError(+ {"api_key": f"Anthropic returned an error validating the API key (HTTP {e.status_code})."}+ )++ def _managed_agents_get(self, path: str, params: dict[str, Any] | None = None) -> dict:+ return self._client.get(+ path,+ cast_to=dict[str, object],+ options={+ "headers": {"anthropic-beta": ANTHROPIC_MANAGED_AGENTS_BETA_HEADER},+ "params": params or {},+ },+ )++ def _list_managed_agents_resource(self, path: str, after: str | None, limit: int) -> tuple[list[dict], str | None]:+ params: dict[str, Any] = {"limit": min(max(int(limit), 1), ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT)}+ if after:+ params["after"] = after+ response = self._managed_agents_get(path, params=params)+ raw_data = response.get("data", [])+ data: list[dict] = [item for item in raw_data if isinstance(item, dict)] if isinstance(raw_data, list) else []+ next_cursor = response.get("next_cursor")+ return data, next_cursor if isinstance(next_cursor, str) else None++ def list_managed_agents(+ self, after: str | None = None, limit: int = ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT+ ) -> tuple[list[dict], str | None]:+ return self._list_managed_agents_resource("/v1/agents", after=after, limit=limit)++ def list_managed_agent_environments(+ self, after: str | None = None, limit: int = ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT+ ) -> tuple[list[dict], str | None]:+ return self._list_managed_agents_resource("/v1/environments", after=after, limit=limit)++ def list_managed_agent_vaults(+ self, after: str | None = None, limit: int = ANTHROPIC_MANAGED_AGENT_LIST_PAGE_LIMIT+ ) -> tuple[list[dict], str | None]:+ return self._list_managed_agents_resource("/v1/vaults", after=after, limit=limit)++ @classmethod+ def integration_from_key(+ cls,+ api_key: str,+ team_id: int,+ created_by: User,+ workspace_label: str | None = None,+ force: bool = False,+ ) -> model.Integration:+ cls.validate_key(api_key)++ anthropic_kind: str = model.Integration.IntegrationKind.ANTHROPIC.value+ integration_id = workspace_label or f"{ANTHROPIC_DEFAULT_INTEGRATION_ID_PREFIX}{team_id}"+ config: dict[str, Any] = {}+ if workspace_label:+ config["workspace_label"] = workspace_label++ if force:+ integration, _ = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind=anthropic_kind,+ integration_id=integration_id,+ defaults={+ "config": config,+ "sensitive_config": {"api_key": api_key},+ "created_by": created_by,+ "errors": "",+ },+ )+ return integration++ try:+ # Wrap in a savepoint so the unique-constraint IntegrityError below+ # aborts only the INSERT, not the surrounding transaction (e.g. the+ # outer DRF request atomic block, or the test wrapper).+ with transaction.atomic():+ return model.Integration.objects.create(+ team_id=team_id,+ kind=anthropic_kind,+ integration_id=integration_id,+ config=config,+ sensitive_config={"api_key": api_key},+ created_by=created_by,+ errors="",+ )+ except IntegrityError:+ raise ValidationError(+ {+ "config": (+ f"An integration with id '{integration_id}' already exists for this team. Choose a different "+ "workspace label, delete the existing integration and try again, or set 'force' to true to overwrite the existing integration."+ )+ }+ )diff --git a/posthog/models/integration/aws.py b/posthog/models/integration/aws.pynew file mode 100644index 000000000000..583950bd51ef--- /dev/null+++ b/posthog/models/integration/aws.py@@ -0,0 +1,376 @@+"""AWS role/credential-based integrations (S3, Redshift, S3-compatible endpoints)."""++from collections.abc import Mapping+from typing import ClassVar, Literal++from django.db import transaction++from rest_framework.exceptions import ValidationError++from posthog.credentials import AWSKeyPair+from posthog.models.user import User+from posthog.models.utils import IntegrityError+from posthog.security.url_validation import is_url_allowed++from . import common, model++_AWSKindType = Literal[model.Integration.IntegrationKind.AWS_REDSHIFT, model.Integration.IntegrationKind.AWS_S3]+++def _read_aws_credentials(integration: model.Integration) -> AWSKeyPair:+ try:+ # SAFETY: Safety is delegated to the integration which must guarantee+ # sensitive_config keys are correctly assigned.+ return AWSKeyPair.unsafe_from_strings(+ integration.sensitive_config["aws_access_key_id"], integration.sensitive_config["aws_secret_access_key"]+ )+ except KeyError as e:+ raise common.IntegrationError(f"Integration is not valid: {str(e)} missing")+++def _create_unique_aws_integration(+ *,+ team_id: int,+ kind: _AWSKindType,+ name: str,+ account_id: str,+ credentials: AWSKeyPair,+ created_by: "User | None",+) -> model.Integration:+ """Create an AWS integration from credentials and an account."""+ return _create_unique_named_integration(+ team_id=team_id,+ kind=kind,+ name=name,+ config={"name": name, "aws_account_id": account_id},+ sensitive_config={+ "aws_access_key_id": credentials.access_key_id,+ "aws_secret_access_key": credentials.secret_access_key,+ },+ created_by=created_by,+ )+++class DuplicateNameError(common.IntegrationError):+ pass+++def _create_unique_named_integration(+ *,+ team_id: int,+ kind: str,+ name: str,+ config: dict[str, str],+ sensitive_config: dict[str, str],+ created_by: "User | None",+) -> model.Integration:+ """Create an integration, rejecting a name already taken for this team and kind.++ Unlike most integrations, `name` is a free-form user-supplied identifier rather than one derived+ from the external connection (an OAuth account id, service-account email, etc.). So we create+ rather than upsert and raise a 400 error, on conflicts.+ """+ try:+ # Savepoint so the unique-constraint IntegrityError aborts only this INSERT, not the+ # surrounding transaction (e.g. the test wrapper, or any outer atomic block).+ with transaction.atomic():+ return model.Integration.objects.create(+ team_id=team_id,+ kind=kind,+ integration_id=name,+ config=config,+ sensitive_config=sensitive_config,+ created_by=created_by,+ )+ except IntegrityError:+ raise DuplicateNameError(f"An integration named '{name}' already exists")+++def is_unique_aws_role_by_organization_id(aws_role_arn: str, organization_id: str) -> bool:+ """Check if the AWS role is only in one organization.++ This is used as a security measure to block multiple organizations from+ assuming the same role.++ In the future we may lift this restriction, but initially we want to make sure about+ AWS role ownership with this check. This complements other runtime checks in+ batch exports; see `get_credentials_using_user_aws_role` in+ `s3_batch_export.py`.+ """+ has_same_aws_role_integrations = (+ model.Integration.objects.select_related("team__organization")+ .filter(+ kind__in=(model.Integration.IntegrationKind.AWS_S3, model.Integration.IntegrationKind.AWS_REDSHIFT),+ config__aws_role_arn=aws_role_arn,+ )+ .exclude(team__organization_id=organization_id)+ ).exists()++ if has_same_aws_role_integrations:+ return False++ return True+++def _return_non_empty_str_from_config_for_aws(config: Mapping, key: str, friendly_name: str) -> str:+ return common._return_non_empty_str_from_config(config, key, friendly_name=friendly_name, kind="AWS")+++def validate_aws_credentials(aws_access_key_id: str, aws_secret_access_key: str) -> str:+ """Validate AWS credentials via STS GetCallerIdentity, returning the AWS account id.++ GetCallerIdentity requires no IAM permissions, so it verifies the credentials are valid+ without assuming any particular S3 policy. It hits the fixed global AWS STS endpoint, so+ there is no user-controlled endpoint and no SSRF surface (unlike S3-compatible).++ This runs synchronously on the request thread, so the timeout budget is kept tight:+ a single attempt (no retry) bounds the worst case at ~10s (connect + read) if STS is+ unreachable, rather than blocking the worker while botocore retries.+ """+ import boto3 # noqa: PLC0415 — keeps botocore off the module import path (startup time)+ from botocore.config import Config # noqa: PLC0415+ from botocore.exceptions import BotoCoreError, ClientError # noqa: PLC0415++ client = boto3.client(+ "sts",+ aws_access_key_id=aws_access_key_id,+ aws_secret_access_key=aws_secret_access_key,+ config=Config(connect_timeout=5, read_timeout=5, retries={"max_attempts": 1}),+ )+ try:+ identity = client.get_caller_identity()+ except ClientError as e:+ message = e.response.get("Error", {}).get("Message") or str(e)+ raise common.IntegrationError(f"AWS credentials are not valid: {message}")+ except BotoCoreError as e:+ raise common.IntegrationError(f"Could not validate AWS credentials: {e}")++ return identity["Account"]+++class AWSRoleBasedIntegration:+ """An AWS integration storing a customer's AWS role."""++ integration: model.Integration+ aws_role_arn: str++ integration_kind: ClassVar[_AWSKindType]++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != self.integration_kind:+ raise common.IntegrationError(+ "Integration provided is not the expected AWS integration "+ f"(got kind='{integration.kind}', expected kind='{self.integration_kind}')"+ )+ self.integration = integration+ try:+ self.aws_role_arn = integration.config["aws_role_arn"]+ except KeyError:+ raise common.IntegrationError("AWS integration is not valid: 'aws_role_arn' missing")++ @classmethod+ def integration_from_config(+ cls,+ team_id: int,+ organization_id: str,+ created_by: "User | None" = None,+ **config,+ ) -> model.Integration:+ name = _return_non_empty_str_from_config_for_aws(config, "name", "A name")+ aws_role_arn = _return_non_empty_str_from_config_for_aws(config, "aws_role_arn", "A valid role ARN")++ if not is_unique_aws_role_by_organization_id(aws_role_arn, organization_id):+ raise ValidationError("Cannot create AWS integration: Invalid role")++ return _create_unique_named_integration(+ team_id=team_id,+ kind=cls.integration_kind,+ name=name,+ config={"name": name, "aws_role_arn": aws_role_arn},+ sensitive_config={},+ created_by=created_by,+ )+++class AWSS3RoleBasedIntegration(AWSRoleBasedIntegration):+ """An AWS S3 integration storing a customer's AWS role."""++ integration_kind: ClassVar[Literal[model.Integration.IntegrationKind.AWS_S3]] = (+ model.Integration.IntegrationKind.AWS_S3+ )+++class AWSRedshiftRoleBasedIntegration(AWSRoleBasedIntegration):+ """An AWS Redshift integration storing a customer's AWS role."""++ integration_kind: ClassVar[Literal[model.Integration.IntegrationKind.AWS_REDSHIFT]] = (+ model.Integration.IntegrationKind.AWS_REDSHIFT+ )+++class AWSCredentialsIntegration:+ """AWS integration for any service that requires storing long-lived AWS credentials.++ Unlike `S3CompatibleIntegration` it has no `endpoint_url` because an AWS+ integration must never be pointed at an arbitrary endpoint (SSRF boundary).+ """++ integration: model.Integration+ credentials: AWSKeyPair++ integration_kind: ClassVar[_AWSKindType]++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != self.integration_kind:+ raise common.IntegrationError(+ "Integration provided is not the expected AWS integration "+ f"(got kind='{integration.kind}', expected kind='{self.integration_kind}')"+ )+ self.integration = integration+ self.credentials = _read_aws_credentials(integration)++ @property+ def aws_account_id(self) -> str | None:+ """The AWS account id resolved from the credentials at create time, if available."""+ return self.integration.config.get("aws_account_id")++ @property+ def aws_access_key_id(self) -> str:+ return self.credentials.access_key_id++ @property+ def aws_secret_access_key(self) -> str:+ return self.credentials.secret_access_key++ @classmethod+ def integration_from_config(+ cls,+ team_id: int,+ created_by: "User | None" = None,+ **config,+ ) -> model.Integration:+ name = _return_non_empty_str_from_config_for_aws(config, "name", "A name")+ aws_access_key_id = _return_non_empty_str_from_config_for_aws(+ config,+ "aws_access_key_id",+ "Access key ID",+ )+ aws_secret_access_key = _return_non_empty_str_from_config_for_aws(+ config, "aws_secret_access_key", "Secret access key"+ )++ # Fail fast on invalid/expired credentials, and capture the (non-sensitive) account id.+ account_id = validate_aws_credentials(aws_access_key_id, aws_secret_access_key)++ # SAFETY: We check that each value is non-empty and str type, and, by+ # validating the credentials directly with AWS, we ensure each of these+ # values is what they say they are. This call is safe.+ credentials = AWSKeyPair.unsafe_from_strings(aws_access_key_id, aws_secret_access_key)++ # `name` is the unencrypted, frontend-visible identifier — never an AWS credential, which is+ # treated as a secret. The account id is non-sensitive and kept for display/debugging.+ return _create_unique_aws_integration(+ team_id=team_id,+ kind=cls.integration_kind,+ name=name,+ account_id=account_id,+ credentials=credentials,+ created_by=created_by,+ )+++class AWSS3Integration(AWSCredentialsIntegration):+ """An AWS S3 integration storing reusable AWS credentials.++ Holds only credentials; bucket, region, prefix and other export-specific settings stay on the+ batch export destination config, so one credential can be reused across many buckets/regions.+ """++ integration_kind: ClassVar[Literal[model.Integration.IntegrationKind.AWS_S3]] = (+ model.Integration.IntegrationKind.AWS_S3+ )+++class AWSRedshiftIntegration(AWSCredentialsIntegration):+ """An AWS Redshift integration storing reusable AWS credentials."""++ integration_kind: ClassVar[Literal[model.Integration.IntegrationKind.AWS_REDSHIFT]] = (+ model.Integration.IntegrationKind.AWS_REDSHIFT+ )+++def _return_non_empty_str_from_config_for_s3_compatible(config: Mapping, key: str, friendly_name: str) -> str:+ return common._return_non_empty_str_from_config(config, key, friendly_name=friendly_name, kind="S3-compatible")+++class S3CompatibleIntegration:+ """An S3-compatible storage integration (Cloudflare R2, DigitalOcean Spaces, Hetzner, etc.).++ Holds the same credentials as `AwsS3Integration` plus the provider `endpoint_url` (non-sensitive),+ since credentials are bound to a specific S3-compatible provider. `integration_from_config`+ SSRF-validates `endpoint_url`, so callers don't have to.++ bucket, region, prefix and other export-specific settings stay on the batch export destination+ config, so one credential can be reused across many buckets/regions.+ """++ integration: model.Integration+ credentials: AWSKeyPair+ endpoint_url: str++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != model.Integration.IntegrationKind.S3_COMPATIBLE:+ raise common.IntegrationError(+ f"Integration provided is not an S3-compatible integration (got kind='{integration.kind}')"+ )+ self.integration = integration+ self.credentials = _read_aws_credentials(integration)+ try:+ self.endpoint_url = integration.config["endpoint_url"]+ except KeyError:+ raise common.IntegrationError("S3-compatible integration is missing required field: 'endpoint_url'")++ @property+ def aws_access_key_id(self) -> str:+ return self.credentials.access_key_id++ @property+ def aws_secret_access_key(self) -> str:+ return self.credentials.secret_access_key++ @classmethod+ def integration_from_config(+ cls,+ team_id: int,+ created_by: "User | None" = None,+ **config,+ ) -> model.Integration:+ name = _return_non_empty_str_from_config_for_s3_compatible(+ config,+ "name",+ friendly_name="A name",+ )+ aws_access_key_id = _return_non_empty_str_from_config_for_s3_compatible(+ config, "aws_access_key_id", "Access key ID"+ )+ aws_secret_access_key = _return_non_empty_str_from_config_for_s3_compatible(+ config, "aws_secret_access_key", "Secret access key"+ )+ endpoint_url = _return_non_empty_str_from_config_for_s3_compatible(config, "endpoint_url", "Endpoint URL")++ # SSRF protection — credentials must not be testable against an attacker-controlled endpoint.+ allowed, error = is_url_allowed(endpoint_url)+ if not allowed:+ raise common.IntegrationError(f"Invalid endpoint URL: {error}")++ return _create_unique_named_integration(+ team_id=team_id,+ kind=model.Integration.IntegrationKind.S3_COMPATIBLE,+ name=name,+ config={"name": name, "endpoint_url": endpoint_url},+ sensitive_config={+ "aws_access_key_id": aws_access_key_id,+ "aws_secret_access_key": aws_secret_access_key,+ },+ created_by=created_by,+ )diff --git a/posthog/models/integration/azure_blob.py b/posthog/models/integration/azure_blob.pynew file mode 100644index 000000000000..7342ff76b6d8--- /dev/null+++ b/posthog/models/integration/azure_blob.py@@ -0,0 +1,77 @@+"""Azure Blob Storage integration."""++from posthog.models.user import User++from . import model+++class AzureBlobIntegrationError(Exception):+ pass+++class AzureBlobIntegration:+ """Wraps Integration model to provide encrypted credential storage for Azure Blob Storage.++ Attributes:+ integration: The underlying Integration model instance.+ connection_string: The decrypted Azure Storage connection string.+ """++ integration: model.Integration+ connection_string: str++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != model.Integration.IntegrationKind.AZURE_BLOB.value:+ raise AzureBlobIntegrationError(+ f"Integration provided is not an Azure Blob integration (got kind='{integration.kind}')"+ )+ self.integration = integration++ try:+ self.connection_string = self.integration.sensitive_config["connection_string"]+ except KeyError:+ raise AzureBlobIntegrationError("Azure Blob integration is missing required field: 'connection_string'")++ @classmethod+ def integration_from_config(+ cls,+ team_id: int,+ connection_string: str,+ created_by: "User | None" = None,+ ) -> model.Integration:+ account_name = cls._extract_account_name(connection_string)+ if not account_name:+ raise AzureBlobIntegrationError(+ "Could not extract AccountName from connection string. "+ "Ensure it contains 'AccountName=<your-account-name>;'"+ )++ config: dict[str, str] = {}+ sensitive_config = {+ "connection_string": connection_string,+ }++ integration, created = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind=model.Integration.IntegrationKind.AZURE_BLOB.value,+ integration_id=account_name,+ defaults={+ "config": config,+ "sensitive_config": sensitive_config,+ "created_by": created_by,+ },+ )++ if integration.errors:+ integration.errors = ""+ integration.save()++ return integration++ @staticmethod+ def _extract_account_name(connection_string: str) -> str | None:+ for part in connection_string.split(";"):+ part = part.strip()+ if part.startswith("AccountName="):+ return part.split("=", 1)[1]+ return Nonediff --git a/posthog/models/integration/clickup.py b/posthog/models/integration/clickup.pynew file mode 100644index 000000000000..d7133ec3cb2d--- /dev/null+++ b/posthog/models/integration/clickup.py@@ -0,0 +1,109 @@+"""ClickUp integration."""++import requests+import structlog+from rest_framework.exceptions import ValidationError++from posthog.exceptions_capture import capture_exception++from . import common, model++logger = structlog.get_logger(__name__)+++class ClickUpIntegration:+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "clickup":+ raise Exception("ClickUpIntegration init called with Integration with wrong 'kind'")++ self.integration = integration++ def _check_auth_error(self, response: requests.Response, context: str) -> None:+ if response.status_code == 401:+ logger.warning(+ f"ClickUpIntegration: Auth error {context}",+ status_code=response.status_code,+ integration_id=self.integration.id,+ )+ self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILED+ self.integration.save(update_fields=["errors"])+ raise ValidationError(+ "This integration's authentication is no longer valid. "+ "Please reconnect or disconnect this integration and connect a different account."+ )+ if response.status_code == 403:+ raise ValidationError(+ "This integration does not have permission to access this resource. "+ "Please check the account permissions on the provider side."+ )++ def list_clickup_spaces(self, workspace_id):+ response = requests.request(+ "GET",+ f"https://api.clickup.com/api/v2/team/{workspace_id}/space",+ headers={+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ },+ timeout=10,+ )++ self._check_auth_error(response, "listing spaces")+ if response.status_code != 200:+ capture_exception(Exception(f"ClickUpIntegration: Failed to list spaces: {response.text}"))+ raise Exception("There was an internal error")++ return response.json()++ def list_clickup_folderless_lists(self, space_id):+ response = requests.request(+ "GET",+ f"https://api.clickup.com/api/v2/space/{space_id}/list",+ headers={+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ },+ timeout=10,+ )++ self._check_auth_error(response, "listing lists")+ if response.status_code != 200:+ capture_exception(Exception(f"ClickUpIntegration: Failed to list lists: {response.text}"))+ raise Exception("There was an internal error")++ return response.json()++ def list_clickup_folders(self, space_id):+ response = requests.request(+ "GET",+ f"https://api.clickup.com/api/v2/space/{space_id}/folder",+ headers={+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ },+ timeout=10,+ )++ self._check_auth_error(response, "listing folders")+ if response.status_code != 200:+ capture_exception(Exception(f"ClickUpIntegration: Failed to list folders: {response.text}"))+ raise Exception("There was an internal error")++ return response.json()++ def list_clickup_workspaces(self) -> dict:+ response = requests.request(+ "GET",+ "https://api.clickup.com/api/v2/team",+ headers={"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}"},+ timeout=10,+ )++ self._check_auth_error(response, "listing workspaces")+ if response.status_code != 200:+ capture_exception(Exception(f"ClickUpIntegration: Failed to list workspaces: {response.text}"))+ raise Exception("There was an internal error")++ return response.json()diff --git a/posthog/models/integration/common.py b/posthog/models/integration/common.pynew file mode 100644index 000000000000..49074c5df0aa--- /dev/null+++ b/posthog/models/integration/common.py@@ -0,0 +1,60 @@+"""Low-level helpers shared by several provider modules (config parsing, JWT decoding)."""++import json+import base64+from collections.abc import Mapping+from typing import Any+++class IntegrationError(Exception):+ """Error raised when an integration or its inputs are not valid."""++ pass+++# Shared between meta.py (token refresh) and oauth.py (authorize/token-exchange URLs), which+# would otherwise import each other to read it off MetaGraphIntegration.+META_GRAPH_API_VERSION = "v25.0"+++def _decode_jwt_payload(token: str) -> dict | None:+ """+ Decode JWT payload without signature verification.++ Used to extract claims from OAuth tokens (id_token, access_token) where+ we trust the token source (received directly from provider over HTTPS).++ Returns None if JWT doesn't have enough parts. Raises on decode errors+ so callers can log exceptions with full traceback.+ """+ parts = token.split(".")+ if len(parts) < 2:+ return None+ payload = parts[1]+ # Handle missing base64 padding+ decoded = base64.urlsafe_b64decode(payload + "===")+ return json.loads(decoded)+++def dot_get(d: Any, path: str, default: Any = None) -> Any:+ if path in d and d[path] is not None:+ return d[path]+ for key in path.split("."):+ if not isinstance(d, dict):+ return default+ d = d.get(key, default)+ return d+++ERROR_TOKEN_REFRESH_FAILED = "TOKEN_REFRESH_FAILED"+++def _return_non_empty_str_from_config(+ config: Mapping,+ key: str,+ friendly_name: str,+ kind: str,+) -> str:+ if (value := config.get(key)) is not None and isinstance(value, str) and len(value) > 0:+ return value+ raise IntegrationError(f"{friendly_name} is required for {kind} integration")diff --git a/posthog/models/integration/databricks.py b/posthog/models/integration/databricks.pynew file mode 100644index 000000000000..eed068b6e436--- /dev/null+++ b/posthog/models/integration/databricks.py@@ -0,0 +1,99 @@+"""Databricks integration."""++from posthog.models.user import User+from posthog.security.url_validation import is_url_allowed++from . import model+++class DatabricksIntegrationError(Exception):+ """Error raised when the Databricks integration is not valid."""++ pass+++class DatabricksIntegration:+ """A Databricks integration.++ The recommended way to connect to Databricks is via OAuth machine-to-machine (M2M) authentication.+ See: https://docs.databricks.com/aws/en/dev-tools/python-sql-connector#oauth-machine-to-machine-m2m-authentication++ This works quite differently to regular user-to-machine OAuth as it does not require a real-time user sign in and+ consent flow: Instead, the user creates a service principal and provided us with the client ID and client secret to authenticate.++ Attributes:+ integration: The integration object.+ server_hostname: the Server Hostname value for user's all-purpose compute or SQL warehouse.+ client_id: the service principal's UUID or Application ID value.+ client_secret: the Secret value for the service principal's OAuth secret.+ """++ integration: model.Integration+ server_hostname: str+ client_id: str+ client_secret: str++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != model.Integration.IntegrationKind.DATABRICKS.value:+ raise DatabricksIntegrationError("Integration provided is not a Databricks integration")+ self.integration = integration++ try:+ self.server_hostname = self.integration.config["server_hostname"]+ self.client_id = self.integration.sensitive_config["client_id"]+ self.client_secret = self.integration.sensitive_config["client_secret"]+ except KeyError as e:+ raise DatabricksIntegrationError(f"Databricks integration is not valid: {str(e)} missing")++ @classmethod+ def integration_from_config(+ cls, team_id: int, server_hostname: str, client_id: str, client_secret: str, created_by: User | None = None+ ) -> model.Integration:+ # first, validate the host+ cls.validate_host(server_hostname)++ config = {+ "server_hostname": server_hostname,+ }+ sensitive_config = {+ "client_id": client_id,+ "client_secret": client_secret,+ }+ integration, _ = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind=model.Integration.IntegrationKind.DATABRICKS.value,+ integration_id=server_hostname, # Use server_hostname as unique identifier+ defaults={+ "config": config,+ "sensitive_config": sensitive_config,+ "created_by": created_by,+ },+ )+ if integration.errors:+ integration.errors = ""+ integration.save()++ return integration++ @staticmethod+ def validate_host(server_hostname: str):+ """Validate the Databricks host.++ We check the value is a bare hostname (not a full URL) and that it passes our shared SSRF+ guard (rejects unresolvable hosts, internal IPs, cloud-metadata hosts, and internal domain+ patterns). This is a quick check (testing connectivity to a SQL warehouse requires a+ warehouse http_path in addition to these parameters so it not possible to perform a full+ test here).+ """+ # we expect a hostname, not a full URL+ if server_hostname.startswith("http"):+ raise DatabricksIntegrationError(+ f"Databricks integration is not valid: 'server_hostname' should not be a full URL"+ )++ # Databricks is always https, so reuse the shared URL allowlist as the SSRF guard.+ allowed, _reason = is_url_allowed(f"https://{server_hostname}")+ if not allowed:+ raise DatabricksIntegrationError(+ f"Databricks integration error: could not validate hostname '{server_hostname}'"+ )diff --git a/posthog/models/integration/email.py b/posthog/models/integration/email.pynew file mode 100644index 000000000000..9a2ef92ed60a--- /dev/null+++ b/posthog/models/integration/email.py@@ -0,0 +1,175 @@+"""Native email-sending integration (SES / maildev) and its cleanup signal."""++from typing import Any++from django.conf import settings+from django.db import models, transaction+from django.dispatch import receiver++from disposable_email_domains import blocklist as disposable_email_domains_list+from free_email_domains import whitelist as free_email_domains_list+from rest_framework.exceptions import ValidationError++from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.plugins.plugin_server_api import reload_integrations_on_workers++from products.workflows.backend.providers import MAILDEV_MOCK_DNS_RECORDS, SESProvider++from . import model+++class EmailIntegration:+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "email":+ raise Exception("EmailIntegration init called with Integration with wrong 'kind'")+ self.integration = integration++ @property+ def ses_provider(self) -> SESProvider:+ return SESProvider()++ @classmethod+ def create_native_integration(+ cls, config: dict, team_id: int, organization_id: str, created_by: User | None = None+ ) -> model.Integration:+ email_address: str = config["email"].lower()+ name: str = config["name"]+ domain: str = email_address.split("@")[1]+ mail_from_subdomain: str = config.get("mail_from_subdomain", "feedback")+ provider: str = config.get("provider", "ses")++ if domain in free_email_domains_list or domain in disposable_email_domains_list:+ raise ValidationError(f"Email domain {domain} is not supported. Please use a custom domain.")++ # Check if any other integration already exists in a different team with the same domain,+ # if so, ensure this team is part of the same organization. If not, we block creation.+ same_domain_integrations = model.Integration.objects.filter(kind="email", config__domain=domain)+ for integration in same_domain_integrations:+ if str(integration.team.organization.id) != str(organization_id):+ raise ValidationError(+ f"An email integration with domain {domain} already exists in another organization. Try a different domain or contact support if you believe this is a mistake."+ )++ # Create domain in the appropriate provider+ if provider == "ses":+ ses = SESProvider()+ org_team_ids = list(Team.objects.filter(organization_id=organization_id).values_list("id", flat=True))+ ses.create_email_domain(+ domain,+ mail_from_subdomain=mail_from_subdomain,+ team_id=team_id,+ org_team_ids=org_team_ids,+ )+ elif provider == "maildev" and settings.DEBUG:+ pass+ else:+ raise ValueError(f"Invalid provider: must be 'ses'")++ integration, created = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind="email",+ integration_id=email_address,+ defaults={+ "config": {+ "email": email_address,+ "domain": domain,+ "mail_from_subdomain": mail_from_subdomain,+ "name": name,+ "provider": provider,+ "verified": True if provider == "maildev" else False,+ },+ "created_by": created_by,+ },+ )++ if integration.errors:+ integration.errors = ""+ integration.save()++ return integration++ def update_native_integration(self, config: dict, team_id: int) -> model.Integration:+ provider = self.integration.config.get("provider")+ domain = self.integration.config.get("domain")+ # Only name and mail_from_subdomain can be updated+ name: str = config.get("name", self.integration.config.get("name"))+ mail_from_subdomain: str = config.get(+ "mail_from_subdomain", self.integration.config.get("mail_from_subdomain", "feedback")+ )++ # Update domain in the appropriate provider+ if provider == "ses":+ ses = SESProvider()+ ses.update_mail_from_subdomain(domain, mail_from_subdomain=mail_from_subdomain)+ elif provider == "maildev" and settings.DEBUG:+ pass+ else:+ raise ValueError(f"Invalid provider: must be 'ses'")++ self.integration.config.update(+ {+ "name": name,+ "mail_from_subdomain": mail_from_subdomain,+ }+ )+ self.integration.save()++ return self.integration++ def verify(self):+ domain = self.integration.config.get("domain")+ provider = self.integration.config.get("provider", "ses")+ mail_from_subdomain = self.integration.config.get("mail_from_subdomain", "feedback")++ # Use the appropriate provider for verification+ if provider == "ses":+ verification_result = self.ses_provider.verify_email_domain(+ domain, mail_from_subdomain=mail_from_subdomain, team_id=self.integration.team_id+ )+ elif provider == "maildev":+ verification_result = {+ "status": "success",+ "dnsRecords": MAILDEV_MOCK_DNS_RECORDS,+ }+ else:+ raise ValueError(f"Invalid provider: {provider}")++ if verification_result.get("status") == "success":+ # We can validate all other integrations with the same domain and provider+ all_integrations_for_domain = model.Integration.objects.filter(+ team_id=self.integration.team_id,+ kind="email",+ config__domain=domain,+ config__provider=provider,+ )+ for integration in all_integrations_for_domain:+ integration.config["verified"] = True+ integration.save()++ reload_integrations_on_workers(+ self.integration.team_id, [integration.id for integration in all_integrations_for_domain]+ )++ return verification_result+++@receiver(models.signals.post_delete, sender=model.Integration)+def cleanup_ses_identity_on_integration_delete(sender: Any, instance: model.Integration, **kwargs: Any) -> None:+ # A post_delete signal (rather than viewset perform_destroy) so SES identities are+ # also cleaned up when integrations die via cascade, e.g. project or org deletion.+ # Leaving the identity behind permanently blocks the domain for every other+ # organization via the foreign-tenant guard in SESProvider.create_email_domain.+ if instance.kind != "email" or instance.config.get("provider") != "ses":+ return+ domain = instance.config.get("domain")+ if not domain:+ return++ from posthog.tasks.integrations import (+ delete_ses_identity_if_unused, # noqa: PLC0415 - breaks circular import with the tasks module+ )++ transaction.on_commit(lambda: delete_ses_identity_if_unused.delay(domain))diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.pynew file mode 100644index 000000000000..204603ce779b--- /dev/null+++ b/posthog/models/integration/github.py@@ -0,0 +1,935 @@+"""GitHub App integration: installation access, repository content and PR operations."""++import re+import time+import base64+from collections.abc import Mapping+from dataclasses import dataclass, field+from datetime import datetime+from typing import Any++from django.conf import settings++import requests+import structlog++from posthog.egress.github.transport import github_request+from posthog.egress.limiter.policies import Priority+from posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError+from posthog.models.user import User+from posthog.plugins.plugin_server_api import reload_integrations_on_workers+from posthog.sync import database_sync_to_async++from . import common, model, refresh_tracking++logger = structlog.get_logger(__name__)+++# `owner/repo`, single slash, no traversal. Used to keep repo/ref/sha values out of GitHub API URL+# paths where a crafted value (e.g. `../../other-repo/contents/x?ref=y`) could redirect the+# authenticated request to a different endpoint.+_GITHUB_REPO_PATH_RE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$")++_GITHUB_REF_RE = re.compile(r"^[A-Za-z0-9._\-/]+$")++_GITHUB_COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,40}$")++# Upper bound on the diff text we return, to keep a pathological diff (generated/vendored+# files) from bloating the JSON response and worker memory. ~1 MB of text.+_MAX_DIFF_CHARS = 1_000_000+++def _is_safe_github_repo_path(repo_path: str) -> bool:+ return ".." not in repo_path and bool(_GITHUB_REPO_PATH_RE.fullmatch(repo_path))+++def _is_safe_github_ref(ref: str) -> bool:+ """A git ref safe to interpolate into a GitHub API URL path (no traversal / URL-control chars)."""+ return (+ bool(ref)+ and ".." not in ref+ and not ref.startswith("/")+ and not ref.endswith("/")+ and bool(_GITHUB_REF_RE.fullmatch(ref))+ )+++def _is_safe_github_sha(sha: str) -> bool:+ return bool(_GITHUB_COMMIT_SHA_RE.fullmatch(sha))+++# Default branches change rarely; a multi-hour TTL is plenty to avoid hitting+# GitHub on every paginated branch request while keeping the window in which a+# renamed default branch stays stale tolerably short.+GITHUB_DEFAULT_BRANCH_CACHE_TTL_SECONDS = 60 * 60 * 6++GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS = 30+++@dataclass(frozen=True)+class GitHubUserAuthorization:+ """Outcome of a successful GitHub App user authorization code exchange."""++ gh_id: int+ gh_login: str+ access_token: str = field(repr=False)+ refresh_token: str | None = field(repr=False)+ access_token_expires_in: int | None+ refresh_token_expires_in: int | None+++@dataclass(frozen=True)+class GitHubInstallationAccess:+ """Installation-level access token response for a GitHub App installation."""++ installation_id: str+ installation_info: dict[str, Any]+ access_token: str = field(repr=False)+ token_expires_at: str # ISO datetime returned by GitHub, e.g. "2024-01-01T14:00:00Z"+ repository_selection: str+++class GitHubInstallationAccessFetchError(Exception):+ def __init__(self, code: str) -> None:+ self.code = code+ super().__init__(code)+++def invalidate_github_repository_caches_for_installation(installation_id: str | int) -> None:+ """Affects both team Integration and personal UserIntegration rows."""+ from posthog.models.user_integration import UserIntegration++ installation_id_str = str(installation_id)+ model.Integration.objects.filter(kind="github", integration_id=installation_id_str).update(+ repository_cache_updated_at=None+ )+ UserIntegration.objects.filter(+ kind=UserIntegration.IntegrationKind.GITHUB,+ integration_id=installation_id_str,+ ).update(repository_cache_updated_at=None)+++def github_account_type(owner_type: str | None) -> str | None:+ """Normalize GitHub's account ``type`` ("Organization" / "User") to org vs personal."""+ if owner_type == "Organization":+ return "organization"+ if owner_type == "User":+ return "personal"+ return None+++class GitHubIntegration(GitHubIntegrationBase):+ integration: model.Integration++ @classmethod+ def fetch_installation_access(cls, installation_id: str) -> GitHubInstallationAccess:+ try:+ installation_info = cls.client_request(f"installations/{installation_id}").json()+ access_token_response = cls.client_request(+ f"installations/{installation_id}/access_tokens", method="POST"+ ).json()+ except Exception as exc:+ raise GitHubInstallationAccessFetchError("installation_fetch_failed") from exc++ installation_access_token = access_token_response.get("token")+ token_expires_at = access_token_response.get("expires_at")+ if not installation_access_token or not token_expires_at:+ raise GitHubInstallationAccessFetchError("installation_token_failed")++ return GitHubInstallationAccess(+ installation_id=installation_id,+ installation_info=installation_info,+ access_token=installation_access_token,+ token_expires_at=token_expires_at,+ repository_selection=access_token_response.get("repository_selection", "selected"),+ )++ @classmethod+ def integration_from_installation_id(+ cls, installation_id: str, team_id: int, created_by: User | None = None+ ) -> model.Integration:+ installation_access = cls.fetch_installation_access(installation_id)+ now = int(time.time())+ expires_in = int(datetime.fromisoformat(installation_access.token_expires_at).timestamp() - now)++ config = {+ "installation_id": installation_id,+ "expires_in": expires_in,+ "refreshed_at": now,+ "repository_selection": installation_access.repository_selection,+ "account": {+ "type": common.dot_get(installation_access.installation_info, "account.type", None),+ "name": common.dot_get(installation_access.installation_info, "account.login", installation_id),+ },+ }+ # See GitHubIntegrationBase.refresh_access_token for why permissions are persisted.+ permissions = installation_access.installation_info.get("permissions")+ if isinstance(permissions, dict):+ config["permissions"] = permissions++ sensitive_config = {"access_token": installation_access.access_token}++ integration, created = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind="github",+ integration_id=installation_id,+ defaults={+ "config": config,+ "sensitive_config": sensitive_config,+ "created_by": created_by,+ },+ )++ if integration.errors:+ integration.errors = ""+ integration.save()++ # Every other kind reports this from IntegrationSerializer.create(). GitHub also gets created+ # through its App installation callback and through agentic provisioning, which never reach+ # that serializer, so this is the one place every GitHub connect passes through.+ # IntegrationSerializer.create() skips github for the same reason: its own github branch ends+ # up here, and reporting in both would count one connection twice.+ if created and created_by is not None:+ from posthog.event_usage import ( # noqa: PLC0415 — posthog.event_usage imports posthog.models+ report_user_action,+ )++ owner_type = common.dot_get(installation_access.installation_info, "account.type", None)+ try:+ report_user_action(+ created_by,+ "integration created",+ {+ "integration_kind": "github",+ "is_overwrite": False,+ "repo_owner_type": owner_type,+ "account_type": github_account_type(owner_type),+ },+ team=integration.team,+ )+ except Exception:+ # The integration row is already committed. Raising here would report a connection+ # that actually succeeded as a failure.+ logger.exception("github_integration: failed to report integration created")++ invalidate_github_repository_caches_for_installation(installation_id)++ return integration++ @classmethod+ def github_login_from_code(cls, code: str) -> str | None:+ result = cls.github_user_from_code(code)+ return result.gh_login if result else None++ @classmethod+ def github_user_from_code(cls, code: str, *, redirect_uri: str | None = None) -> "GitHubUserAuthorization | None":+ """Exchange an OAuth code from the GitHub App user authorization flow.++ Pass ``redirect_uri`` when the user was sent to ``/login/oauth/authorize`` with+ the same redirect URI (required by GitHub for the token exchange in that flow).++ Returns a :class:`GitHubUserAuthorization` with the user's id/login plus the+ user-to-server access/refresh tokens and their expirations, or ``None`` if+ the exchange fails or the response lacks an id/login.+ """+ client_id = settings.GITHUB_APP_CLIENT_ID+ client_secret = settings.GITHUB_APP_CLIENT_SECRET+ if not client_id or not client_secret:+ logger.warning("GitHubIntegration: GITHUB_APP_CLIENT_ID/SECRET not configured, cannot exchange code")+ return None++ token_body: dict[str, str] = {+ "client_id": client_id,+ "client_secret": client_secret,+ "code": code,+ }+ if redirect_uri is not None:+ token_body["redirect_uri"] = redirect_uri++ token_response = requests.post(+ "https://github.com/login/oauth/access_token",+ json=token_body,+ headers={"Accept": "application/json"},+ timeout=10,+ )+ token_data = token_response.json()+ access_token = token_data.get("access_token")+ if not access_token:+ logger.warning(+ "GitHubIntegration: code exchange returned no access_token",+ status_code=token_response.status_code,+ error=token_data.get("error"),+ error_description=token_data.get("error_description"),+ error_uri=token_data.get("error_uri"),+ )+ return None++ # Identity-blind: a fresh user OAuth token with no installation budget behind it.+ user_response = github_request(+ "GET",+ "https://api.github.com/user",+ source="integration",+ headers={"Authorization": f"Bearer {access_token}"},+ timeout=10,+ )+ if user_response.status_code != 200:+ logger.warning("GitHubIntegration: /user request failed", status_code=user_response.status_code)+ return None++ payload = user_response.json()+ gh_id = payload.get("id")+ gh_login = payload.get("login")+ if gh_id is None or not gh_login:+ return None+ access_expires_in = token_data.get("expires_in")+ refresh_expires_in = token_data.get("refresh_token_expires_in")+ return GitHubUserAuthorization(+ gh_id=int(gh_id),+ gh_login=str(gh_login),+ access_token=str(access_token),+ refresh_token=token_data.get("refresh_token") or None,+ access_token_expires_in=int(access_expires_in) if access_expires_in is not None else None,+ refresh_token_expires_in=int(refresh_expires_in) if refresh_expires_in is not None else None,+ )++ @classmethod+ def first_for_team_repository(+ cls,+ team_id: int,+ repository: str,+ *,+ source: str | None = None,+ priority: Priority | None = None,+ ) -> "GitHubIntegration | None":+ """First GitHub integration for the team whose installation can access ``repository`` (``owner/name``).++ ``repository`` reaches us from team-writable content (e.g. artefact payloads), and the access+ check below interpolates it into an authenticated ``GET /repos/{repository}``. Reject anything+ that isn't a plain ``owner/repo`` first, so a crafted value (``owner/repo/contents/x?ref=y``)+ can't steer that authenticated request to a different GitHub endpoint as a probe.+ """+ if not _is_safe_github_repo_path(repository):+ return None+ for integration in model.Integration.objects.filter(team_id=team_id, kind="github").order_by("id"):+ github = cls(integration, source=source, priority=priority)+ if github.installation_can_access_repository(repository):+ return github+ return None++ def __init__(+ self, integration: model.Integration, *, source: str | None = None, priority: Priority | None = None+ ) -> None:+ if integration.kind != "github":+ raise Exception("GitHubIntegration init called with Integration with wrong 'kind'")+ self.integration = integration+ if source is not None:+ self.source = source+ if priority is not None:+ self.priority = priority++ def _on_token_refresh_failed(self, response: requests.Response) -> None:+ logger.warning(f"Failed to refresh token for {self}", response=response.text)+ self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILED+ # A permanently-gone installation (uninstalled/suspended) drops expires_in/refreshed_at so the+ # every-minute beat loop stops re-minting it; the errors + config change persist in one save.+ self._disarm_proactive_refresh_if_installation_gone(response)+ reason = (+ refresh_tracking.REFRESH_FAILURE_REASON_HTTP_5XX+ if response.status_code >= 500+ else refresh_tracking.REFRESH_FAILURE_REASON_OTHER+ )+ attempt = refresh_tracking.record_refresh_failure(self.integration, reason=reason)+ refresh_tracking.oauth_refresh_counter.labels(+ kind=self.integration.kind, result="failed", reason=reason, attempt=attempt+ ).inc()+ self.integration.save()++ def _on_token_refreshed(self) -> None:+ logger.info(f"Refreshed access token for {self}")+ self.integration.errors = ""+ refresh_tracking.record_refresh_success(self.integration)+ reload_integrations_on_workers(self.integration.team_id, [self.integration.id])+ refresh_tracking.oauth_refresh_counter.labels(+ kind=self.integration.kind, result="success", reason="", attempt=""+ ).inc()++ @database_sync_to_async+ def list_cached_repositories_async(+ self, *, search: str = "", limit: int = 100, offset: int = 0+ ) -> tuple[list[dict], bool]:+ return self.list_cached_repositories(search=search, limit=limit, offset=offset)++ def create_issue(self, config: dict[str, Any]):+ title: str = config.pop("title")+ body: str = config.pop("body")+ repository: str = config.pop("repository")+ labels = config.pop("labels", None)++ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"+ json_body: dict[str, Any] = {"title": title, "body": body}+ if labels:+ json_body["labels"] = labels++ response = self.api_request(+ "POST",+ f"/repos/{repo_path}/issues",+ endpoint="/repos/{owner}/{repo}/issues",+ json_body=json_body,+ )+ if response.status_code != 201:+ raise GitHubIntegrationError(+ f"GitHubIntegration: failed to create issue in {repo_path}: {response.text[:300]}",+ status_code=response.status_code,+ )+ issue = response.json()++ return {"number": issue["number"], "repository": repository}++ def search_issues(self, repository: str, query: str, *, limit: int = 25) -> list[dict[str, Any]]:+ """Search existing GitHub issues in a repository for the link-existing flow."""+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"+ if not _is_safe_github_repo_path(repo_path):+ raise GitHubIntegrationError(f"GitHubIntegration: invalid repository path {repo_path!r}")++ # `repository` is stored bare in external_context so build_external_issue_url can re-prefix+ # the org, matching what create_issue persists.+ repository_name = repo_path.split("/", 1)[1]++ # Quote the user's text so search syntax in it (qualifiers like repo:, operators like OR)+ # is matched literally instead of rewriting the query, which would fill the result page+ # with foreign matches and hide valid ones.+ search_term = query.replace("\\", " ").replace('"', " ").strip()+ q = f'repo:{repo_path} "{search_term}" in:title type:issue' if search_term else f"repo:{repo_path} type:issue"++ response = self.api_request(+ "GET",+ "/search/issues",+ endpoint="/search/issues",+ params={"q": q, "per_page": limit},+ )+ if response.status_code != 200:+ raise GitHubIntegrationError(+ f"GitHubIntegration: failed to search issues in {repo_path}: {response.text[:300]}",+ status_code=response.status_code,+ )++ results: list[dict[str, Any]] = []+ for issue in response.json().get("items", []) or []:+ number = issue.get("number")+ if number is None:+ continue+ # The issues search API returns pull requests too; those aren't linkable issues.+ if issue.get("pull_request"):+ continue+ # Search-syntax operators in the user's query (e.g. "foo OR bar") can escape the+ # repo: qualifier, so drop anything that isn't actually from the chosen repository.+ repository_url = issue.get("repository_url") or ""+ if not repository_url.lower().endswith(f"/repos/{repo_path.lower()}"):+ continue+ results.append(+ {+ "id": str(number),+ "title": issue.get("title") or f"#{number}",+ "url": issue.get("html_url") or "",+ # Matches the shape GitHubIntegration.create_issue stores.+ "external_context": {"repository": repository_name, "number": number},+ }+ )+ return results++ def create_branch(self, repository: str, branch_name: str, base_branch: str | None = None) -> dict[str, Any]:+ """Create a new branch from a base branch."""+ org = self.organization()++ # Get the SHA of the base branch (default to repository's default branch)+ if not base_branch:+ base_branch = self.get_default_branch(repository)++ # Get the SHA of the base branch+ ref_response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/git/ref/heads/{base_branch}",+ endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",+ )++ if ref_response.status_code != 200:+ return {+ "success": False,+ "error": f"Failed to get base branch {base_branch}: {ref_response.text}",+ }++ base_sha = ref_response.json()["object"]["sha"]++ # Create the new branch+ response = self.api_request(+ "POST",+ f"/repos/{org}/{repository}/git/refs",+ endpoint="/repos/{owner}/{repo}/git/refs",+ json_body={+ "ref": f"refs/heads/{branch_name}",+ "sha": base_sha,+ },+ )++ if response.status_code == 201:+ branch_data = response.json()+ return {+ "success": True,+ "branch_name": branch_name,+ "sha": branch_data["object"]["sha"],+ "ref": branch_data["ref"],+ }+ else:+ return {+ "success": False,+ "error": f"Failed to create branch: {response.text}",+ "status_code": response.status_code,+ }++ def commit_files_to_branch(+ self,+ repository: str,+ branch_name: str,+ base_branch: str,+ files: Mapping[str, str],+ commit_message: str,+ replace_directory: str | None = None,+ ) -> dict[str, Any]:+ """Point ``branch_name`` at a single commit on top of ``base_branch`` writing every file in+ ``files`` (repo-relative path → text content).++ Prefer this over ``create_branch`` plus one ``update_file`` per file when the files only make+ sense together: the commit object is built before the branch reference exists, so a failure+ part way through leaves nothing in the repository, and reviewers get one commit rather than+ one per file. An existing branch is force-updated to the new commit, discarding whatever was+ on it — callers republishing generated content want exactly that, callers collaborating on a+ branch do not.++ ``replace_directory`` makes the commit *replace* that directory with exactly the files given+ under it, instead of merging them into whatever ``base_branch`` already holds there. Without+ it a path that existed on the base and is absent from ``files`` survives, because the tree is+ built on the base tree: a caller republishing a generated directory would keep shipping files+ it has since deleted or renamed. Files outside the directory are still merged as usual.+ """+ if not files:+ return {"success": False, "error": "No files to commit"}++ org = self.organization()++ base_ref_response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/git/ref/heads/{base_branch}",+ endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",+ )+ if base_ref_response.status_code != 200:+ return {+ "success": False,+ "error": f"Failed to get base branch {base_branch}: {base_ref_response.text}",+ "status_code": base_ref_response.status_code,+ }+ base_sha = base_ref_response.json()["object"]["sha"]++ base_commit_response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/git/commits/{base_sha}",+ endpoint="/repos/{owner}/{repo}/git/commits/{commit_sha}",+ )+ if base_commit_response.status_code != 200:+ return {+ "success": False,+ "error": f"Failed to read base commit {base_sha}: {base_commit_response.text}",+ "status_code": base_commit_response.status_code,+ }+ base_tree_sha = base_commit_response.json()["tree"]["sha"]++ # Inline `content` lets GitHub create the blobs as part of the tree, so no separate blob+ # round trip per file. 100644 is a non-executable file.+ def blob_entries(paths: Mapping[str, str]) -> list[dict[str, str]]:+ return [+ {"path": path, "mode": "100644", "type": "blob", "content": content} for path, content in paths.items()+ ]++ entries: list[dict[str, str]] = []+ if replace_directory:+ prefix = replace_directory.rstrip("/") + "/"+ inside = {path[len(prefix) :]: content for path, content in files.items() if path.startswith(prefix)}+ # Built with no base_tree, so this tree holds the given files and nothing else. Pointing+ # the directory entry at it swaps the whole subtree in one step, which is what makes a+ # path the caller dropped disappear rather than survive from the base tree.+ subtree_response = self.api_request(+ "POST",+ f"/repos/{org}/{repository}/git/trees",+ endpoint="/repos/{owner}/{repo}/git/trees",+ json_body={"tree": blob_entries(inside)},+ )+ if subtree_response.status_code != 201:+ return {+ "success": False,+ "error": f"Failed to create tree for {replace_directory}: {subtree_response.text}",+ "status_code": subtree_response.status_code,+ }+ entries.append(+ {+ "path": replace_directory.rstrip("/"),+ "mode": "040000",+ "type": "tree",+ "sha": subtree_response.json()["sha"],+ }+ )+ entries.extend(blob_entries({p: c for p, c in files.items() if not p.startswith(prefix)}))+ else:+ entries = blob_entries(files)++ tree_response = self.api_request(+ "POST",+ f"/repos/{org}/{repository}/git/trees",+ endpoint="/repos/{owner}/{repo}/git/trees",+ json_body={"base_tree": base_tree_sha, "tree": entries},+ )+ if tree_response.status_code != 201:+ return {+ "success": False,+ "error": f"Failed to create tree: {tree_response.text}",+ "status_code": tree_response.status_code,+ }++ commit_response = self.api_request(+ "POST",+ f"/repos/{org}/{repository}/git/commits",+ endpoint="/repos/{owner}/{repo}/git/commits",+ json_body={+ "message": commit_message,+ "tree": tree_response.json()["sha"],+ "parents": [base_sha],+ },+ )+ if commit_response.status_code != 201:+ return {+ "success": False,+ "error": f"Failed to create commit: {commit_response.text}",+ "status_code": commit_response.status_code,+ }+ commit_sha = commit_response.json()["sha"]++ create_ref_response = self.api_request(+ "POST",+ f"/repos/{org}/{repository}/git/refs",+ endpoint="/repos/{owner}/{repo}/git/refs",+ json_body={"ref": f"refs/heads/{branch_name}", "sha": commit_sha},+ )+ if create_ref_response.status_code == 201:+ return {"success": True, "branch_name": branch_name, "commit_sha": commit_sha, "created_branch": True}++ # 422 is what GitHub returns for a reference that already exists; move it instead.+ if create_ref_response.status_code != 422:+ return {+ "success": False,+ "error": f"Failed to create branch {branch_name}: {create_ref_response.text}",+ "status_code": create_ref_response.status_code,+ }++ update_ref_response = self.api_request(+ "PATCH",+ f"/repos/{org}/{repository}/git/refs/heads/{branch_name}",+ endpoint="/repos/{owner}/{repo}/git/refs/heads/{branch}",+ json_body={"sha": commit_sha, "force": True},+ )+ if update_ref_response.status_code != 200:+ return {+ "success": False,+ "error": f"Failed to update branch {branch_name}: {update_ref_response.text}",+ "status_code": update_ref_response.status_code,+ }+ return {"success": True, "branch_name": branch_name, "commit_sha": commit_sha, "created_branch": False}++ def delete_branch(self, repository: str, branch_name: str, expected_sha: str | None = None) -> dict[str, Any]:+ """Delete a branch reference. A branch that is already gone counts as success.++ ``expected_sha`` makes the delete conditional: the ref is read first and left alone when it+ has moved on, which is what a caller cleaning up its own failed write wants on a branch name+ that is shared by construction. GitHub has no conditional delete, so this narrows the race+ rather than closing it.+ """+ org = self.organization()++ if expected_sha is not None:+ head_response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/git/ref/heads/{branch_name}",+ endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",+ )+ if head_response.status_code == 404:+ return {"success": True, "branch_name": branch_name}+ if head_response.status_code != 200:+ return {+ "success": False,+ "error": f"Failed to read branch {branch_name}: {head_response.text}",+ "status_code": head_response.status_code,+ }+ if head_response.json()["object"]["sha"] != expected_sha:+ return {"success": True, "branch_name": branch_name, "skipped": True}++ response = self.api_request(+ "DELETE",+ f"/repos/{org}/{repository}/git/refs/heads/{branch_name}",+ endpoint="/repos/{owner}/{repo}/git/refs/heads/{branch}",+ )+ if response.status_code in (204, 404):+ return {"success": True, "branch_name": branch_name}+ # GitHub answers a delete with 422 both for a reference that is already gone and for one it+ # refused to remove, so the status alone can't tell "done" from "still there". Read the ref+ # back: absent is the success the caller wanted, present is a branch it has to hear about.+ if response.status_code == 422:+ recheck_response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/git/ref/heads/{branch_name}",+ endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",+ )+ if recheck_response.status_code == 404:+ return {"success": True, "branch_name": branch_name}+ return {+ "success": False,+ "error": f"Failed to delete branch {branch_name}: {response.text}",+ "status_code": response.status_code,+ }++ def get_diff(+ self,+ repository: str,+ target_branch: str,+ base_branch: str,+ target_sha: str | None = None,+ base_sha: str | None = None,+ ) -> dict[str, Any]:+ """Return the unified diff of one branch/commit against another for ``repository``.++ ``repository`` may be ``owner/name`` or a bare name (resolved against the installation's+ org). The diff is ``base...target``: ``target_branch`` compared against ``base_branch``.+ A SHA, when supplied, pins that side to an exact commit; otherwise the side tracks the+ branch tip (``None`` means "use latest"). The branch is what's used when no SHA pins the+ point — diffing branch tips keeps the result useful as a branch keeps moving (e.g. after PR+ babysitting or customer tweaks), which a single pinned commit would not.++ Uses the GitHub compare API with the ``diff`` media type, so the response body is raw+ unified-diff text. Repository / ref / SHA values come from team-writable artefact content,+ so they're validated before interpolation — a crafted value could otherwise redirect the+ authenticated request to a different GitHub endpoint.+ """+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"++ if not _is_safe_github_repo_path(repo_path):+ return {"success": False, "error": f"Invalid repository '{repository}'.", "status_code": 400}+ for ref in (target_branch, base_branch):+ if not _is_safe_github_ref(ref):+ return {"success": False, "error": f"Invalid branch '{ref}'.", "status_code": 400}+ for sha in (target_sha, base_sha):+ if sha is not None and not _is_safe_github_sha(sha):+ return {"success": False, "error": f"Invalid commit SHA '{sha}'.", "status_code": 400}++ # Pin to the SHA when we have one, else compare branch tips. Both sides are now built from+ # validated values, so the compare path can't be steered off-endpoint.+ base_ref = base_sha or base_branch+ target_ref = target_sha or target_branch++ try:+ response = self.api_request(+ "GET",+ f"/repos/{repo_path}/compare/{base_ref}...{target_ref}",+ endpoint="/repos/{owner}/{repo}/compare/{basehead}",+ headers={"Accept": "application/vnd.github.diff"},+ )+ except GitHubIntegrationError:+ # Don't let a slow/unreachable GitHub hang a worker or 500 the caller.+ return {"success": False, "error": "Could not reach GitHub.", "status_code": 502}+ if response.status_code != 200:+ return {"success": False, "error": response.text, "status_code": response.status_code}+ # Cap the diff we return: a branch touching generated/vendored files can produce a diff of+ # many MB, which would bloat the JSON response and worker memory. Truncate with a marker so+ # the consumer can tell the diff was cut rather than silently showing a partial diff.+ diff_text = response.text+ truncated = len(diff_text) > _MAX_DIFF_CHARS+ if truncated:+ diff_text = diff_text[:_MAX_DIFF_CHARS] + "\n\n… diff truncated (too large to display in full) …\n"+ return {"success": True, "diff": diff_text, "truncated": truncated}++ def update_file(+ self, repository: str, file_path: str, content: str, commit_message: str, branch: str, sha: str | None = None+ ) -> dict[str, Any]:+ """Create or update a file in the repository."""+ org = self.organization()++ # If no SHA provided, try to get existing file's SHA+ if not sha:+ get_response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/contents/{file_path}",+ endpoint="/repos/{owner}/{repo}/contents/{path}",+ params={"ref": branch},+ )+ if get_response.status_code == 200:+ sha = get_response.json()["sha"]++ encoded_content = base64.b64encode(content.encode("utf-8")).decode("utf-8")++ data = {+ "message": commit_message,+ "content": encoded_content,+ "branch": branch,+ }++ if sha:+ data["sha"] = sha++ response = self.api_request(+ "PUT",+ f"/repos/{org}/{repository}/contents/{file_path}",+ endpoint="/repos/{owner}/{repo}/contents/{path}",+ json_body=data,+ )++ if response.status_code in [200, 201]:+ commit_data = response.json()+ return {+ "success": True,+ "commit_sha": commit_data["commit"]["sha"],+ "file_sha": commit_data["content"]["sha"],+ "html_url": commit_data["commit"]["html_url"],+ }+ else:+ return {+ "success": False,+ "error": f"Failed to update file: {response.text}",+ "status_code": response.status_code,+ }++ def get_file_contents(self, repository: str, file_path: str, ref: str | None = None) -> dict[str, Any] | None:+ """Read a file's decoded text and blob SHA at ``ref`` (default branch when omitted).++ Returns ``{"content": str, "sha": str}``, or ``None`` when the file does not+ exist — a missing file is a normal state, not an error. The SHA lets a caller+ pass it straight to ``update_file`` for a conflict-safe write. Counterpart to+ ``update_file``, kept here so URL and token handling stay inside the client.+ """+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"++ response = self.api_request(+ "GET",+ f"/repos/{repo_path}/contents/{file_path}",+ endpoint="/repos/{owner}/{repo}/contents/{path}",+ params={"ref": ref} if ref else None,+ )+ if response.status_code == 404:+ return None+ if response.status_code != 200:+ raise GitHubIntegrationError(+ f"Failed to read {file_path} from {repository}: {response.text}",+ status_code=response.status_code,+ )+ payload = response.json()+ return {"content": base64.b64decode(payload["content"]).decode("utf-8"), "sha": payload["sha"]}++ def create_pull_request(+ self, repository: str, title: str, body: str, head_branch: str, base_branch: str | None = None+ ) -> dict[str, Any]:+ """Create a pull request."""+ org = self.organization()++ if not base_branch:+ base_branch = self.get_default_branch(repository)++ response = self.api_request(+ "POST",+ f"/repos/{org}/{repository}/pulls",+ endpoint="/repos/{owner}/{repo}/pulls",+ json_body={+ "title": title,+ "body": body,+ "head": head_branch,+ "base": base_branch,+ },+ )++ if response.status_code == 201:+ pr_data = response.json()+ return {+ "success": True,+ "pr_number": pr_data["number"],+ "pr_url": pr_data["html_url"],+ "pr_id": pr_data["id"],+ "state": pr_data["state"],+ }+ else:+ return {+ "success": False,+ "error": f"Failed to create pull request: {response.text}",+ "status_code": response.status_code,+ }++ def get_branch_info(self, repository: str, branch_name: str) -> dict[str, Any]:+ """Get information about a specific branch."""+ org = self.organization()++ response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/branches/{branch_name}",+ endpoint="/repos/{owner}/{repo}/branches/{branch}",+ )++ if response.status_code == 200:+ branch_data = response.json()+ return {+ "success": True,+ "exists": True,+ "branch_name": branch_data["name"],+ "commit_sha": branch_data["commit"]["sha"],+ "protected": branch_data.get("protected", False),+ }+ elif response.status_code == 404:+ return {+ "success": True,+ "exists": False,+ "branch_name": branch_name,+ }+ else:+ return {+ "success": False,+ "error": f"Failed to get branch info: {response.text}",+ "status_code": response.status_code,+ }++ def list_pull_requests(self, repository: str, state: str = "open") -> dict[str, Any]:+ """List pull requests for a repository."""+ org = self.organization()++ params: dict[str, str | int] = {"state": state, "per_page": 100}+ response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/pulls",+ endpoint="/repos/{owner}/{repo}/pulls",+ params=params,+ )++ if response.status_code == 200:+ prs = response.json()+ return {+ "success": True,+ "pull_requests": [+ {+ "number": pr["number"],+ "title": pr["title"],+ "url": pr["html_url"],+ "state": pr["state"],+ "head_branch": pr["head"]["ref"],+ "base_branch": pr["base"]["ref"],+ "created_at": pr["created_at"],+ "updated_at": pr["updated_at"],+ }+ for pr in prs+ ],+ }+ else:+ return {+ "success": False,+ "error": f"Failed to list pull requests: {response.text}",+ "status_code": response.status_code,+ }diff --git a/posthog/models/integration/gitlab.py b/posthog/models/integration/gitlab.pynew file mode 100644index 000000000000..5dc0f8cb3fc8--- /dev/null+++ b/posthog/models/integration/gitlab.py@@ -0,0 +1,148 @@+"""GitLab integration."""++from typing import Any++import requests++from posthog.security.url_validation import is_url_allowed++from . import common, model+++class GitLabIntegrationError(Exception):+ pass+++class GitLabIntegration:+ integration: model.Integration++ @staticmethod+ def get(hostname: str, endpoint: str, project_access_token: str) -> dict:+ url = f"{hostname}/api/v4/{endpoint}"+ allowed, error = is_url_allowed(url)+ if not allowed:+ raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")++ response = requests.get(+ url,+ headers={"PRIVATE-TOKEN": project_access_token},+ # disallow redirects to prevent SSRF on redirected host+ allow_redirects=False,+ timeout=10,+ )++ return response.json()++ @staticmethod+ def post(hostname: str, endpoint: str, project_access_token: str, json: dict) -> dict:+ url = f"{hostname}/api/v4/{endpoint}"+ allowed, error = is_url_allowed(url)+ if not allowed:+ raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")++ response = requests.post(+ url,+ json=json,+ headers={"PRIVATE-TOKEN": project_access_token},+ # disallow redirects to prevent SSRF on redirected host+ allow_redirects=False,+ timeout=10,+ )++ return response.json()++ @classmethod+ def create_integration(cls, hostname, project_id, project_access_token, team_id, user) -> model.Integration:+ project = cls.get(hostname, f"projects/{project_id}", project_access_token)++ integration = model.Integration.objects.create(+ team_id=team_id,+ kind=model.Integration.IntegrationKind.GITLAB,+ integration_id=project.get("name_with_namespace"),+ config={+ "hostname": hostname,+ "path_with_namespace": project.get("path_with_namespace"),+ "project_id": project.get("id"),+ },+ sensitive_config={"access_token": project_access_token},+ created_by=user,+ )++ return integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "gitlab":+ raise Exception("GitLabIntegration init called with Integration with wrong 'kind'")+ self.integration = integration++ @property+ def project_path(self) -> str:+ return common.dot_get(self.integration.config, "path_with_namespace")++ @property+ def hostname(self) -> str:+ return common.dot_get(self.integration.config, "hostname")++ def create_issue(self, config: dict[str, str]):+ title: str = config.pop("title")+ description: str = config.pop("body")++ hostname = self.integration.config.get("hostname")+ project_id = self.integration.config.get("project_id")+ access_token = self.integration.sensitive_config.get("access_token")++ issue = GitLabIntegration.post(+ hostname,+ f"projects/{project_id}/issues",+ access_token,+ {+ "title": title,+ "description": description,+ "labels": "posthog",+ },+ )++ return {"issue_id": issue["iid"]}++ def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:+ """Search existing GitLab issues in the connected project for the link-existing flow."""+ hostname = self.integration.config.get("hostname")+ project_id = self.integration.config.get("project_id")+ access_token = self.integration.sensitive_config.get("access_token")++ url = f"{hostname}/api/v4/projects/{project_id}/issues"+ allowed, error = is_url_allowed(url)+ if not allowed:+ raise GitLabIntegrationError(f"Invalid GitLab hostname: {error}")++ params: dict[str, str | int] = {"search": query, "per_page": limit, "in": "title"}+ response = requests.get(+ url,+ headers={"PRIVATE-TOKEN": access_token},+ params=params,+ allow_redirects=False,+ timeout=10,+ )+ if response.status_code != 200:+ raise GitLabIntegrationError(+ f"GitLabIntegration: failed to search issues: {response.text[:300]}",+ )+ issues = response.json()+ if not isinstance(issues, list):+ return []++ results: list[dict[str, Any]] = []+ for issue in issues:+ iid = issue.get("iid")+ if iid is None:+ continue+ results.append(+ {+ "id": str(iid),+ "title": issue.get("title") or f"#{iid}",+ "url": issue.get("web_url") or "",+ # Matches the shape GitLabIntegration.create_issue stores.+ "external_context": {"issue_id": iid},+ }+ )+ return resultsdiff --git a/posthog/models/integration/google_ads.py b/posthog/models/integration/google_ads.pynew file mode 100644index 000000000000..449867e29b34--- /dev/null+++ b/posthog/models/integration/google_ads.py@@ -0,0 +1,202 @@+"""Google Ads integration."""++from typing import Any++from django.conf import settings++import requests+import structlog+from rest_framework.exceptions import ValidationError+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed++from posthog.egress.slack.client import SlackWebClient as WebClient+from posthog.exceptions_capture import capture_exception++from . import common, model++logger = structlog.get_logger(__name__)+++def google_ads_hierarchy_level(account: dict) -> int:+ """Depth of an account below the manager the walk started from. Google's REST responses omit proto3+ defaults, so a level-0 account carries no `level` key at all, and deeper ones arrive as strings."""+ return int(account.get("level") or 0)+++@retry(+ stop=stop_after_attempt(3),+ wait=wait_fixed(2),+ retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError)),+ reraise=True,+)+def _google_ads_request(method: str, url: str, **kwargs) -> requests.Response:+ """`requests.request` with retries for a transient timeout/connection blip.++ `list_google_ads_accessible_accounts` walks the account hierarchy with a chain of sequential+ requests, so a single transient blip on any one of them would otherwise fail the whole walk.+ """+ return requests.request(method, url, **kwargs)+++class GoogleAdsIntegration:+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "google-ads":+ raise Exception("GoogleAdsIntegration init called with Integration with wrong 'kind'")++ self.integration = integration++ @property+ def client(self) -> WebClient:+ return WebClient(self.integration.sensitive_config["access_token"])++ def list_google_ads_conversion_actions(self, customer_id, parent_id=None) -> list[dict]:+ response = requests.request(+ "POST",+ f"https://googleads.googleapis.com/v24/customers/{customer_id}/googleAds:searchStream",+ json={+ "query": "SELECT conversion_action.id, conversion_action.name FROM conversion_action WHERE conversion_action.status != 'REMOVED'"+ },+ headers={+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "developer-token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,+ **({"login-customer-id": parent_id} if parent_id else {}),+ },+ timeout=10,+ )++ if response.status_code == 401:+ logger.warning(+ "GoogleAdsIntegration: Auth error listing conversion actions",+ status_code=response.status_code,+ integration_id=self.integration.id,+ )+ self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILED+ self.integration.save(update_fields=["errors"])+ raise ValidationError(+ "This integration's authentication is no longer valid. "+ "Please reconnect or disconnect this integration and connect a different account."+ )++ if response.status_code == 403:+ raise ValidationError(+ "This integration does not have permission to access this resource. "+ "Please check the account permissions on the provider side."+ )++ if response.status_code != 200:+ capture_exception(+ Exception(f"GoogleAdsIntegration: Failed to list ads conversion actions: {response.text}")+ )+ raise Exception("There was an internal error")++ return response.json()++ # Google Ads manager accounts can have access to other accounts (including other manager accounts).+ # Filter out duplicates where a user has direct access and access through a manager account, while prioritizing direct access.+ def list_google_ads_accessible_accounts(self) -> list[dict[str, Any]]:+ response = _google_ads_request(+ "GET",+ "https://googleads.googleapis.com/v24/customers:listAccessibleCustomers",+ headers={+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "developer-token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,+ },+ timeout=10,+ )++ if response.status_code == 401:+ logger.warning(+ "GoogleAdsIntegration: Auth error listing accessible accounts",+ status_code=response.status_code,+ integration_id=self.integration.id,+ )+ self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILED+ self.integration.save(update_fields=["errors"])+ raise ValidationError(+ "This integration's authentication is no longer valid. "+ "Please reconnect or disconnect this integration and connect a different account."+ )++ if response.status_code == 403:+ raise ValidationError(+ "This integration does not have permission to access this resource. "+ "Please check the account permissions on the provider side."+ )++ if response.status_code != 200:+ capture_exception(Exception(f"GoogleAdsIntegration: Failed to list accessible accounts: {response.text}"))+ raise Exception("There was an internal error")++ accessible_accounts = response.json()+ all_accounts: list[dict[str, Any]] = []++ def dfs(account_id, accounts=None, parent_id=None) -> list[dict]:+ if accounts is None:+ accounts = []+ response = _google_ads_request(+ "POST",+ f"https://googleads.googleapis.com/v24/customers/{account_id}/googleAds:searchStream",+ json={+ "query": "SELECT customer_client.descriptive_name, customer_client.client_customer, customer_client.level, customer_client.manager, customer_client.status FROM customer_client WHERE customer_client.level <= 5"+ },+ headers={+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "developer-token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,+ **({"login-customer-id": parent_id} if parent_id else {}),+ },+ timeout=10,+ )++ if response.status_code != 200:+ return accounts++ # searchStream's REST body is an array of response objects, one per streamed batch.+ data = response.json()+ results = [row for chunk in data for row in chunk.get("results", [])]++ for nested_account in results:+ client = nested_account["customerClient"]+ client_id = client["clientCustomer"].split("/")[1]+ # `level` is compared numerically: it is absent on the level-0 row and a string ("1", "2")+ # below it, so the raw values are not mutually comparable.+ client_level = google_ads_hierarchy_level(client)++ # Reject non-enabled accounts before deduping. Otherwise a disabled, shallower sighting+ # of an account we already kept as enabled would evict the enabled entry here and then be+ # skipped by the status check below, dropping the account from the picker entirely.+ if client.get("status") != "ENABLED":+ continue++ # One account can be reached from several accessible roots — e.g. a user with access to+ # both a manager and one of its clients walks that client twice, once as a root (level 0)+ # and once beneath the manager (level 1). Keep the shallowest sighting, whose `parent_id`+ # is the account we can authenticate the sync as.+ already_seen = [account for account in accounts if account["id"] == client_id]+ if already_seen:+ if all(google_ads_hierarchy_level(account) <= client_level for account in already_seen):+ continue+ accounts = [account for account in accounts if account["id"] != client_id]++ accounts.append(+ {+ "parent_id": parent_id,+ "id": client_id,+ "level": client.get("level"),+ "name": client.get("descriptiveName", "Google Ads account"),+ "manager": client.get("manager", False),+ }+ )++ return accounts++ # A Google login with no accessible Ads accounts gets a 200 with an empty body, so+ # `resourceNames` is absent (proto3 omits empty repeated fields) rather than an empty list.+ for account in accessible_accounts.get("resourceNames", []):+ all_accounts = dfs(account.split("/")[1], all_accounts, account.split("/")[1])++ return all_accountsdiff --git a/posthog/models/integration/google_cloud.py b/posthog/models/integration/google_cloud.pynew file mode 100644index 000000000000..25678f46cbe1--- /dev/null+++ b/posthog/models/integration/google_cloud.py@@ -0,0 +1,230 @@+"""Google Cloud service-account and Pub/Sub / Cloud Storage integrations."""++import time+from datetime import timedelta++import structlog+from google.auth.transport.requests import Request as GoogleRequest+from google.oauth2 import service_account+from rest_framework.exceptions import ValidationError++from posthog.models.user import User+from posthog.plugins.plugin_server_api import reload_integrations_on_workers++from . import model, refresh_tracking++logger = structlog.get_logger(__name__)+++def is_unique_service_account_by_organization_id(service_account_email: str, organization_id: str) -> bool:+ """Check if the service account is only in one organization.++ This is used as a security measure to block multiple organizations from+ impersonating the same service account.++ In the future we may lift this restriction, but initially we want to make sure about+ service account ownership with this check. This complements other runtime checks in+ batch exports; see `verify_impersonated_service_account_ownership` in+ `bigquery_batch_export.py`.+ """+ same_service_account_integrations = (+ model.Integration.objects.select_related("team__organization")+ .filter(kind="google-cloud-service-account", config__service_account_email=service_account_email)+ # If private key is present, then we are not impersonating+ .exclude(sensitive_config__has_key="private_key")+ )+ for integration in same_service_account_integrations:+ if str(integration.team.organization.id) != organization_id:+ return False++ return True+++class GoogleCloudServiceAccountIntegration:+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ self.integration = integration++ @classmethod+ def integration_from_service_account(+ cls,+ team_id: int,+ organization_id: str,+ service_account_email: str,+ project_id: str,+ private_key: str | None = None,+ private_key_id: str | None = None,+ token_uri: str | None = None,+ created_by: User | None = None,+ ) -> model.Integration:+ if private_key is None:+ if not is_unique_service_account_by_organization_id(service_account_email, organization_id):+ raise ValidationError("Cannot create Google Cloud service account integration: Invalid service account")++ sensitive_config = {}+ is_impersonated = True+ if isinstance(private_key, str) and isinstance(private_key_id, str) and isinstance(token_uri, str):+ sensitive_config["private_key"] = private_key+ sensitive_config["private_key_id"] = private_key_id+ sensitive_config["token_uri"] = token_uri++ is_impersonated = False++ variant = "impersonated" if is_impersonated else "key-file"++ integration, _ = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind=model.Integration.IntegrationKind.GOOGLE_CLOUD_SERVICE_ACCOUNT.value,+ # Including team_id to allow teams from the same organization to use the+ # same service account. Otherwise different teams would overwrite each other.+ integration_id=f"{service_account_email}-{team_id}-{variant}",+ defaults={+ "config": {+ "project_id": project_id,+ "service_account_email": service_account_email,+ },+ "sensitive_config": sensitive_config,+ "created_by": created_by,+ },+ )++ if integration.errors:+ integration.errors = ""+ integration.save()++ return integration++ def has_key(self) -> bool:+ """Return if this integration has a key associated with a service account.++ If not, then it is a service account we are meant to impersonate.+ """+ keys = ("private_key", "private_key_id")+ return all(key in self.integration.sensitive_config for key in keys) and all(+ self.integration.sensitive_config[key] for key in keys+ )++ @property+ def project_id(self) -> str:+ return self.integration.config["project_id"]++ @property+ def service_account_email(self) -> str:+ return self.integration.config["service_account_email"]++ @property+ def service_account_info(self) -> dict[str, str]:+ return {+ "private_key": self.integration.sensitive_config["private_key"],+ "private_key_id": self.integration.sensitive_config["private_key_id"],+ "token_uri": self.integration.sensitive_config["token_uri"],+ "client_email": self.service_account_email,+ "project_id": self.project_id,+ }+++class GoogleCloudIntegration:+ supported_kinds = ["google-pubsub", "google-cloud-storage"]+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ self.integration = integration++ @classmethod+ def integration_from_key(+ cls, kind: str, key_info: dict, team_id: int, created_by: User | None = None+ ) -> model.Integration:+ if kind == "google-pubsub":+ scope = "https://www.googleapis.com/auth/pubsub"+ elif kind == "google-cloud-storage":+ scope = "https://www.googleapis.com/auth/devstorage.read_write"+ else:+ raise NotImplementedError(f"Google Cloud integration kind {kind} not implemented")++ try:+ credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])+ credentials.refresh(GoogleRequest())+ except Exception:+ raise ValidationError(f"Failed to authenticate with provided service account key")++ integration, created = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind=kind,+ integration_id=credentials.service_account_email,+ defaults={+ "config": {+ "expires_in": credentials.expiry.timestamp() - int(time.time()),+ "refreshed_at": int(time.time()),+ },+ "sensitive_config": {+ "key_info": key_info,+ "access_token": credentials.token,+ },+ "created_by": created_by,+ },+ )++ if integration.errors:+ integration.errors = ""+ integration.save()++ return integration++ def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:+ expires_in = self.integration.config.get("expires_in")+ refreshed_at = self.integration.config.get("refreshed_at")+ if not expires_in or not refreshed_at:+ return False++ # To be really safe we refresh if its half way through the expiry+ time_threshold = time_threshold or timedelta(seconds=expires_in / 2)++ return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()++ def refresh_access_token(self):+ """+ Refresh the access token for the integration if necessary+ """+ if self.integration.kind == "google-pubsub":+ scope = "https://www.googleapis.com/auth/pubsub"+ elif self.integration.kind == "google-cloud-storage":+ scope = "https://www.googleapis.com/auth/devstorage.read_write"+ else:+ raise NotImplementedError(f"Google Cloud integration kind {self.integration.kind} not implemented")++ key_info = self.integration.sensitive_config.get("key_info", self.integration.sensitive_config)+ credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])++ try:+ credentials.refresh(GoogleRequest())+ except Exception:+ refresh_tracking.record_refresh_failure(self.integration)+ self.integration.save(update_fields=["config"])+ raise ValidationError(f"Failed to authenticate with provided service account key")++ # Wholesale replacement also clears any refresh backoff state+ self.integration.config = {+ "expires_in": credentials.expiry.timestamp() - int(time.time()),+ "refreshed_at": int(time.time()),+ }+ # Migrate pre-migration integrations where sensitive_config contains the+ # keyfile directly (not nested under "key_info"). Without this, setting+ # access_token pollutes the keyfile dict and breaks subsequent refreshes.+ if "key_info" not in self.integration.sensitive_config:+ self.integration.sensitive_config = {+ "key_info": self.integration.sensitive_config,+ "access_token": credentials.token,+ }+ else:+ self.integration.sensitive_config["access_token"] = credentials.token+ self.integration.save()+ reload_integrations_on_workers(self.integration.team_id, [self.integration.id])++ logger.info(f"Refreshed access token for {self}")++ def get_access_token(self) -> str:+ if self.access_token_expired():+ self.refresh_access_token()+ # Fall back to config for pre-migration integrations+ return self.integration.sensitive_config.get("access_token") or self.integration.config.get("access_token", "")diff --git a/posthog/models/integration/jira.py b/posthog/models/integration/jira.pynew file mode 100644index 000000000000..dee89e3671d3--- /dev/null+++ b/posthog/models/integration/jira.py@@ -0,0 +1,210 @@+"""Jira integration."""++import time+from datetime import timedelta+from typing import Any, NoReturn++import requests+import structlog+from rest_framework.exceptions import ValidationError++from posthog.exceptions_capture import capture_exception++from . import common, model, oauth++logger = structlog.get_logger(__name__)+++class JiraIntegration:+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "jira":+ raise Exception("JiraIntegration init called with Integration with wrong 'kind'")++ self.integration = integration++ def cloud_id(self) -> str | None:+ """Get the Atlassian cloud ID from the integration config"""+ return common.dot_get(self.integration.config, "cloud_id")++ def site_name(self) -> str | None:+ """Get the Jira site name from the integration config"""+ return common.dot_get(self.integration.config, "site_name")++ def site_url(self) -> str:+ """Get the Jira site URL from the integration config"""+ return common.dot_get(self.integration.config, "site_url", "")++ def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:+ """Check if the Atlassian access token has expired or is close to expiring"""+ refresh_token = self.integration.sensitive_config.get("refresh_token")+ expires_in = self.integration.config.get("expires_in")+ refreshed_at = self.integration.config.get("refreshed_at")++ if not refresh_token:+ return False++ if not expires_in or not refreshed_at:+ return False++ # To be safe we refresh if it's halfway through the expiry+ time_threshold = time_threshold or timedelta(seconds=expires_in / 2)++ return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()++ def refresh_access_token(self) -> None:+ """Refresh the Atlassian access token using the refresh token"""+ oauth_integration = oauth.OauthIntegration(self.integration)+ oauth_integration.refresh_access_token()++ def _ensure_token_valid(self) -> None:+ """Proactively refresh token if it's close to expiring to avoid intermittent 401s"""+ try:+ if self.access_token_expired():+ self.refresh_access_token()+ except Exception:+ logger.warning("JiraIntegration: token refresh pre-check failed", exc_info=True)++ def _raise_create_issue_error(self, response: requests.Response, response_body: Any) -> NoReturn:+ properties: dict[str, Any] = {+ "jira_status_code": response.status_code,+ "jira_response_content_type": response.headers.get("Content-Type"),+ "integration_id": self.integration.id,+ "team_id": self.integration.team_id,+ }+ if isinstance(response_body, dict):+ properties.update(+ {+ "jira_error_messages": response_body.get("errorMessages"),+ "jira_field_errors": response_body.get("errors"),+ "jira_response_keys": list(response_body.keys()),+ }+ )++ capture_exception(Exception("Jira issue creation failed"), additional_properties=properties)+ raise ValidationError("Could not create the Jira issue. Check the project's issue settings and try again.")++ def list_projects(self) -> list[dict]:+ """List all Jira projects accessible to the user"""+ cloud_id = self.cloud_id()+ if not cloud_id:+ raise ValidationError("Jira integration missing cloud_id - the integration may not be properly configured")++ self._ensure_token_valid()++ response = requests.get(+ f"https://api.atlassian.com/ex/jira/{cloud_id}/rest/api/3/project/search",+ headers={+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "Accept": "application/json",+ },+ timeout=10,+ )+ body = response.json()+ projects = body.get("values", [])+ return [{"id": p["id"], "key": p["key"], "name": p["name"]} for p in projects]++ def create_issue(self, config: dict[str, str]) -> dict[str, str]:+ """Create a Jira issue and return the issue key"""+ cloud_id = self.cloud_id()+ if not cloud_id:+ raise ValidationError("Jira integration missing cloud_id - the integration may not be properly configured")++ self._ensure_token_valid()++ title = config.get("title")+ description = config.get("description")+ project_key = config.get("project_key")++ # Jira uses Atlassian Document Format (ADF) for description+ payload = {+ "fields": {+ "project": {"key": project_key},+ "summary": title,+ "description": {+ "type": "doc",+ "version": 1,+ "content": [+ {+ "type": "paragraph",+ "content": [{"type": "text", "text": description}],+ }+ ],+ },+ "issuetype": {"name": "Task"},+ }+ }++ response = requests.post(+ f"https://api.atlassian.com/ex/jira/{cloud_id}/rest/api/3/issue",+ headers={+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "Accept": "application/json",+ "Content-Type": "application/json",+ },+ json=payload,+ timeout=10,+ )++ try:+ issue = response.json()+ except ValueError:+ issue = None++ if response.status_code != 201:+ self._raise_create_issue_error(response, issue)++ if not isinstance(issue, dict) or not issue.get("key"):+ self._raise_create_issue_error(response, issue)++ return {"key": issue["key"], "id": issue.get("id", "")}++ def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:+ """Search existing Jira issues for the link-existing flow.++ Uses Jira's purpose-built issue picker endpoint, which matches on summary and+ issue key without us having to build (and escape) a JQL string from user input.+ """+ cloud_id = self.cloud_id()+ if not cloud_id:+ raise ValidationError("Jira integration missing cloud_id - the integration may not be properly configured")++ self._ensure_token_valid()++ response = requests.get(+ f"https://api.atlassian.com/ex/jira/{cloud_id}/rest/api/3/issue/picker",+ headers={+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "Accept": "application/json",+ },+ # Without currentJQL the picker only returns history suggestions (issues the+ # user recently viewed); this constant JQL makes it search all accessible issues.+ params={"query": query, "currentJQL": "order by created DESC", "showSubTasks": "true"},+ timeout=10,+ )+ if response.status_code != 200:+ raise ValidationError(f"Failed to search Jira issues (status {response.status_code})")+ body = response.json()++ site_url = self.site_url()+ results: list[dict[str, Any]] = []+ seen_keys: set[str] = set()+ for section in body.get("sections", []) or []:+ for issue in section.get("issues", []) or []:+ key = issue.get("key")+ if not key or key in seen_keys:+ continue+ seen_keys.add(key)+ results.append(+ {+ "id": str(issue.get("id", "")),+ "title": issue.get("summaryText") or issue.get("summary") or key,+ "url": f"{site_url}/browse/{key}" if site_url else "",+ # Matches the shape JiraIntegration.create_issue stores.+ "external_context": {"key": key, "id": str(issue.get("id", ""))},+ }+ )+ if len(results) >= limit:+ return results+ return resultsdiff --git a/posthog/models/integration/linear.py b/posthog/models/integration/linear.pynew file mode 100644index 000000000000..bcd45e0174dc--- /dev/null+++ b/posthog/models/integration/linear.py@@ -0,0 +1,119 @@+"""Linear integration."""++from typing import Any++import requests+import structlog+from rest_framework.exceptions import ValidationError++from . import common, model++logger = structlog.get_logger(__name__)+++class LinearIntegration:+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "linear":+ raise Exception("LinearIntegration init called with Integration with wrong 'kind'")++ self.integration = integration++ def url_key(self) -> str:+ return common.dot_get(self.integration.config, "data.viewer.organization.urlKey")++ def list_teams(self) -> list[dict]:+ body = self.query(f"{{ teams {{ nodes {{ id name }} }} }}")+ teams = common.dot_get(body, "data.teams.nodes")+ return teams++ def create_issue(self, attachment_url: str, config: dict[str, str]) -> dict[str, str]:+ title: str = config.pop("title")+ description: str = config.pop("description")+ linear_team_id = config.pop("team_id")++ issue_create_query = """+ mutation IssueCreate($title: String!, $description: String!, $teamId: String!) {+ issueCreate(input: { title: $title, description: $description, teamId: $teamId }) {+ success+ issue { identifier }+ }+ }+ """+ body = self.query(+ issue_create_query,+ variables={"title": title, "description": description, "teamId": linear_team_id},+ )+ linear_issue_id = common.dot_get(body, "data.issueCreate.issue.identifier")+ # Linear reports failures in a 200 body; without this check a failed create would+ # persist a reference with id None. Nothing was created, so raising is safe.+ if body.get("errors") or not linear_issue_id:+ raise ValidationError("Failed to create the Linear issue")++ # Best-effort: the Linear issue already exists at this point, so failing the whole+ # create over a missing back-link would produce duplicate issues on retry.+ try:+ self.create_attachment(linear_issue_id, attachment_url)+ except ValidationError:+ logger.warning("linear_issue_attachment_failed", issue_id=linear_issue_id)++ return {"id": linear_issue_id}++ def create_attachment(self, issue_id: str, url: str) -> None:+ """Attach a PostHog issue link to a Linear issue (shows as a back-link in Linear).++ Raises on failure: Linear reports errors in the GraphQL body with HTTP 200,+ and the mutation itself can report success=false.+ """+ link_attachment_query = """+ mutation AttachmentCreate($issueId: String!, $title: String!, $url: String!) {+ attachmentCreate(input: { issueId: $issueId, title: $title, url: $url }) {+ success+ }+ }+ """+ body = self.query(+ link_attachment_query,+ variables={"issueId": issue_id, "title": "PostHog issue", "url": url},+ )+ if body.get("errors") or not common.dot_get(body, "data.attachmentCreate.success"):+ raise ValidationError("Failed to attach the PostHog link to the Linear issue")++ def search_issues(self, query: str, *, limit: int = 25) -> list[dict[str, Any]]:+ """Search existing Linear issues by title / identifier for the link-existing flow."""+ search_query = """+ query SearchIssues($term: String!, $first: Int!) {+ searchIssues(term: $term, first: $first) {+ nodes { identifier title url }+ }+ }+ """+ body = self.query(search_query, variables={"term": query, "first": limit})+ if body.get("errors") or common.dot_get(body, "data.searchIssues") is None:+ raise ValidationError("Failed to search Linear issues")+ nodes = common.dot_get(body, "data.searchIssues.nodes") or []+ results: list[dict[str, Any]] = []+ for node in nodes:+ identifier = node.get("identifier")+ if not identifier:+ continue+ results.append(+ {+ "id": identifier,+ "title": node.get("title") or identifier,+ "url": node.get("url") or "",+ # Matches the shape LinearIntegration.create_issue stores.+ "external_context": {"id": identifier},+ }+ )+ return results++ def query(self, query: str, variables: dict[str, Any] | None = None) -> dict[str, Any]:+ response = requests.post(+ "https://api.linear.app/graphql",+ headers={"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}"},+ json={"query": query, "variables": variables or {}},+ timeout=10,+ )+ return response.json()diff --git a/posthog/models/integration/linkedin_ads.py b/posthog/models/integration/linkedin_ads.pynew file mode 100644index 000000000000..3615cb6490dc--- /dev/null+++ b/posthog/models/integration/linkedin_ads.py@@ -0,0 +1,74 @@+"""LinkedIn Ads integration."""++import requests+import structlog+from rest_framework.exceptions import ValidationError++from posthog.egress.slack.client import SlackWebClient as WebClient++from . import common, model++logger = structlog.get_logger(__name__)+++class LinkedInAdsIntegration:+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "linkedin-ads":+ raise Exception("LinkedInAdsIntegration init called with Integration with wrong 'kind'")++ self.integration = integration++ @property+ def client(self) -> WebClient:+ return WebClient(self.integration.sensitive_config["access_token"])++ def _check_auth_error(self, response: requests.Response, context: str) -> None:+ if response.status_code == 401:+ logger.warning(+ f"LinkedInAdsIntegration: Auth error {context}",+ status_code=response.status_code,+ integration_id=self.integration.id,+ )+ self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILED+ self.integration.save(update_fields=["errors"])+ raise ValidationError(+ "This integration's authentication is no longer valid. "+ "Please reconnect or disconnect this integration and connect a different account."+ )+ if response.status_code == 403:+ raise ValidationError(+ "This integration does not have permission to access this resource. "+ "Please check the account permissions on the provider side."+ )++ def list_linkedin_ads_conversion_rules(self, account_id):+ response = requests.request(+ "GET",+ f"https://api.linkedin.com/rest/conversions?q=account&account=urn%3Ali%3AsponsoredAccount%3A{account_id}&fields=conversionMethod%2Cenabled%2Ctype%2Cname%2Cid%2Ccampaigns%2CattributionType",+ headers={+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "LinkedIn-Version": "202607",+ },+ timeout=10,+ )++ self._check_auth_error(response, "listing conversion rules")+ return response.json()++ def list_linkedin_ads_accounts(self) -> dict:+ response = requests.request(+ "GET",+ "https://api.linkedin.com/rest/adAccounts?q=search",+ headers={+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",+ "LinkedIn-Version": "202607",+ },+ timeout=10,+ )++ self._check_auth_error(response, "listing ad accounts")+ return response.json()diff --git a/posthog/models/integration/meta.py b/posthog/models/integration/meta.pynew file mode 100644index 000000000000..2bcf2da0342a--- /dev/null+++ b/posthog/models/integration/meta.py@@ -0,0 +1,86 @@+"""Meta Graph API integrations (Meta Ads, Instagram) and their shared token refresh."""++import time++import requests+import structlog++from . import common, model, oauth, refresh_tracking++logger = structlog.get_logger(__name__)+++class MetaGraphIntegration:+ """Token handling shared by the Meta Graph OAuth kinds (Meta Ads, Instagram).++ Meta issues no refresh token: a long-lived user access token is swapped for a fresh one+ through the `fb_exchange_token` grant, which is why these kinds sit outside the generic+ `OauthIntegration` refresh sweep and refresh on use instead.+ """++ integration: model.Integration+ kind: str = ""+ api_version: str = common.META_GRAPH_API_VERSION++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != self.kind:+ raise Exception(f"{type(self).__name__} init called with Integration with wrong 'kind'")+ self.integration = integration++ def refresh_access_token(self):+ oauth_config = oauth.OauthIntegration.oauth_config_for_kind(self.integration.kind)++ # skip refresh if more than 7 days until expiry+ if self.integration.config.get("expires_in") and self.integration.config.get("refreshed_at"):+ if (+ time.time()+ < self.integration.config.get("refreshed_at") + self.integration.config.get("expires_in") - 604800+ ):+ return++ res = requests.post(+ oauth_config.token_url,+ data={+ "client_id": oauth_config.client_id,+ "client_secret": oauth_config.client_secret,+ "fb_exchange_token": self.integration.sensitive_config["access_token"],+ "grant_type": "fb_exchange_token",+ "set_token_expires_in_60_days": True,+ },+ timeout=10,+ )++ try:+ config: dict = res.json()+ except ValueError:+ config = {}++ if res.status_code != 200 or not config.get("access_token"):+ logger.warning(f"Failed to refresh token for {self}", response=res.text)+ self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILED+ reason = refresh_tracking.oauth_refresh_failure_reason(res.status_code, config, kind=self.integration.kind)+ attempt = refresh_tracking.record_refresh_failure(self.integration, reason=reason)+ refresh_tracking.oauth_refresh_counter.labels(+ kind=self.integration.kind, result="failed", reason=reason, attempt=attempt+ ).inc()+ else:+ logger.info(f"Refreshed access token for {self}")+ refresh_tracking.record_refresh_success(self.integration)+ self.integration.sensitive_config["access_token"] = config["access_token"]+ self.integration.errors = ""+ self.integration.config["expires_in"] = config.get("expires_in")+ self.integration.config["refreshed_at"] = int(time.time())+ # not used in CDP yet+ # reload_integrations_on_workers(self.integration.team_id, [self.integration.id])+ refresh_tracking.oauth_refresh_counter.labels(+ kind=self.integration.kind, result="success", reason="", attempt=""+ ).inc()+ self.integration.save()+++class MetaAdsIntegration(MetaGraphIntegration):+ kind = "meta-ads"+++class InstagramIntegration(MetaGraphIntegration):+ kind = "instagram"diff --git a/posthog/models/integration/model.py b/posthog/models/integration/model.pynew file mode 100644index 000000000000..978ed550893d--- /dev/null+++ b/posthog/models/integration/model.py@@ -0,0 +1,296 @@+"""The Integration Django model, its manager, and generic secret-decryption helpers."""++from typing import Any, Self, cast++from django.db import models+from django.db.models import Q++import structlog+from prometheus_client import Counter++from posthog.helpers.encrypted_fields import FERNET_TOKEN_PREFIX, EncryptedJSONField+from posthog.models.user import User+from posthog.rbac.decorators import field_access_control+from posthog.sync import database_sync_to_async++from . import common++logger = structlog.get_logger(__name__)+++class UndecryptedIntegrationSecretError(ValueError):+ """Raised when a value read off `Integration.sensitive_config` still looks like Fernet+ ciphertext instead of the decrypted secret, and no configured key can open it.++ `sensitive_config` sets `ignore_decrypt_errors=True` so integrations written before+ encryption existed keep loading, but that same leniency means a value that fails to+ decrypt under every configured key (a lost key, a corrupted row) comes back as raw+ ciphertext rather than raising. Left unchecked, that ciphertext gets sent to the+ third-party API as if it were the real credential, which rejects it as invalid, hiding+ the actual cause behind what looks like a bad customer-supplied key.++ The message is user-facing: it lands on the failed data warehouse job as `latest_error`.+ """++ def __init__(self) -> None:+ super().__init__(+ "We couldn't read the saved credentials for this connection. Reconnect the account to start syncing again."+ )+++# Reading a still-encrypted secret means the row is either recoverably over-encrypted or+# permanently unreadable. Both are invisible from the sync failure alone, so count them by kind:+# a rising `unreadable` rate means live customer credentials are being lost.+integration_secret_decrypt_counter = Counter(+ "integration_sensitive_config_decrypt_recovery",+ "Reads of an Integration secret that came back still encrypted, by recovery outcome",+ labelnames=["kind", "result"],+)+++def _decrypted_sensitive_value(integration: "Integration", field_name: str) -> str | None:+ """Read a secret off `sensitive_config`, peeling any extra encryption layers it picked up.++ A read-then-save of a row whose secret failed to decrypt writes that ciphertext back+ encrypted again, so the stored value ends up double-encrypted. One decrypt (the field's+ own) then leaves ciphertext behind. Peel the rest here: the underlying secret is intact+ and the connection keeps working.+ """+ value = integration.sensitive_config.get(field_name)+ if not isinstance(value, str) or not value.startswith(FERNET_TOKEN_PREFIX):+ return value++ # django-stubs can't see through `field_access_control`, so it doesn't know this field name.+ field = cast(EncryptedJSONField, integration._meta.get_field("sensitive_config")) # type: ignore[misc]+ recovered = field.decrypt_all_layers(value)++ if recovered is None:+ integration_secret_decrypt_counter.labels(kind=integration.kind, result="unreadable").inc()+ logger.error(+ "integration_sensitive_config_unreadable",+ integration_id=integration.pk,+ team_id=integration.team_id,+ kind=integration.kind,+ field=field_name,+ )+ raise UndecryptedIntegrationSecretError()++ integration_secret_decrypt_counter.labels(kind=integration.kind, result="recovered").inc()+ logger.warning(+ "integration_sensitive_config_over_encrypted",+ integration_id=integration.pk,+ team_id=integration.team_id,+ kind=integration.kind,+ field=field_name,+ )+ return recovered+++class IntegrationQuerySet(models.QuerySet["Integration"]):+ def for_github_installation_id(self, installation_id: str | int) -> Self:+ return self.filter(+ Q(config__installation_id=str(installation_id)) | Q(config__installation_id=int(installation_id))+ )+++class IntegrationManager(models.Manager["Integration"]):+ _queryset_class = IntegrationQuerySet++ def get_queryset(self) -> IntegrationQuerySet:+ return IntegrationQuerySet(self.model, using=self._db)++ def filter(self, *args: Any, **kwargs: Any) -> IntegrationQuerySet:+ return self.get_queryset().filter(*args, **kwargs)++ def first_github_for_team_installation(self, team_id: int, installation_id: str) -> "Integration | None":+ return (+ self.filter(team_id=team_id, kind=Integration.IntegrationKind.GITHUB)+ .for_github_installation_id(installation_id)+ .first()+ )++ def first_github_for_user_installation(self, user: User, installation_id: str) -> "Integration | None":+ user_team_ids = user.teams.values_list("id", flat=True)+ return (+ self.filter(team_id__in=user_team_ids, kind=Integration.IntegrationKind.GITHUB)+ .for_github_installation_id(installation_id)+ .first()+ )+++class Integration(models.Model):+ class IntegrationKind(models.TextChoices):+ ANTHROPIC = "anthropic"+ APPLE_PUSH = "apns"+ AWS_REDSHIFT = "aws-redshift"+ AWS_S3 = "aws-s3"+ AZURE_BLOB = "azure-blob"+ BING_ADS = "bing-ads"+ CLICKUP = "clickup"+ CUSTOMERIO_APP = "customerio-app"+ CUSTOMERIO_TRACK = "customerio-track"+ CUSTOMERIO_WEBHOOK = "customerio-webhook"+ DATABRICKS = "databricks"+ EMAIL = "email"+ FIREBASE = "firebase"+ GITHUB = "github"+ GITLAB = "gitlab"+ GOOGLE_ADS = "google-ads"+ GOOGLE_ANALYTICS = "google-analytics"+ GOOGLE_CALENDAR = "google-calendar"+ GOOGLE_CLOUD_SERVICE_ACCOUNT = "google-cloud-service-account"+ GOOGLE_CLOUD_STORAGE = "google-cloud-storage"+ GOOGLE_PUBSUB = "google-pubsub"+ GOOGLE_SEARCH_CONSOLE = "google-search-console"+ GOOGLE_SHEETS = "google-sheets"+ HUBSPOT = "hubspot"+ INSTAGRAM = "instagram"+ INTERCOM = "intercom"+ JIRA = "jira"+ LINEAR = "linear"+ LINKEDIN_ADS = "linkedin-ads"+ META_ADS = "meta-ads"+ PARDOT = "pardot"+ PINTEREST_ADS = "pinterest-ads"+ POSTGRESQL = "postgresql"+ POSTHOG = "posthog"+ REDDIT_ADS = "reddit-ads"+ RESEND = "resend"+ S3_COMPATIBLE = "s3-compatible"+ SALESFORCE = "salesforce"+ SLACK = "slack"+ # Deprecated — kept in choices to avoid a no-op migration. The runtime no longer creates+ # or reads this kind; see `products/slack_app/backend/api.py` for the live integration.+ SLACK_POSTHOG_CODE = "slack-posthog-code"+ SNAPCHAT = "snapchat"+ SNOWFLAKE = "snowflake"+ STRIPE = "stripe"+ TIKTOK_ADS = "tiktok-ads"+ TWILIO = "twilio"+ VERCEL = "vercel"+ YOUTUBE_ANALYTICS = "youtube-analytics"++ team = models.ForeignKey("Team", on_delete=models.CASCADE)++ # The integration type identifier+ kind = field_access_control(models.CharField(max_length=32, choices=IntegrationKind), "project", "admin")+ # The ID of the integration in the external system+ integration_id = field_access_control(models.TextField(null=True, blank=True), "project", "admin")+ # Any config that COULD be passed to the frontend+ config = field_access_control(models.JSONField(default=dict), "project", "admin")+ sensitive_config = field_access_control(+ EncryptedJSONField(+ default=dict,+ ignore_decrypt_errors=True, # allows us to load previously unencrypted data+ ),+ "project",+ "admin",+ )+ repository_cache = models.JSONField(default=list, blank=True)+ repository_cache_updated_at = models.DateTimeField(null=True, blank=True)++ errors = models.TextField()++ # Meta+ created_at = models.DateTimeField(auto_now_add=True, blank=True)+ created_by = models.ForeignKey("User", on_delete=models.SET_NULL, null=True, blank=True)++ objects: IntegrationManager = IntegrationManager()++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["team", "kind", "integration_id"], name="posthog_integration_kind_id_unique"+ )+ ]+ indexes = [models.Index(fields=["kind", "integration_id"], name="posthog_integration_kind_ext")]++ @property+ def display_name(self) -> str:+ if self.kind == "pinterest-ads":+ # Pinterest's OAuth username is an opaque hash, so prefer the business name when there is one.+ return self.config.get("business_name") or self.config.get("username") or self.integration_id+ if self.kind == "tiktok-ads":+ # The OAuth id is a list of advertiser ids, so prefer whoever authorized the connection.+ return self.config.get("user_email") or self.config.get("user_display_name") or self.integration_id+ # Deferred: every provider module imports `model` for the `Integration` type, so a+ # module-level import here would cycle back through them.+ from . import google_cloud, oauth # noqa: PLC0415 — breaks a circular import++ if self.kind in oauth.OauthIntegration.supported_kinds:+ region = self.config.get("region") if self.kind == "posthog" else None+ oauth_config = oauth.OauthIntegration.oauth_config_for_kind(self.kind, region)+ return common.dot_get(self.config, oauth_config.name_path, self.integration_id)+ if self.kind in google_cloud.GoogleCloudIntegration.supported_kinds:+ return self.integration_id or "unknown ID"+ if self.kind == "github":+ return common.dot_get(self.config, "account.name", self.integration_id)+ if self.kind == "databricks":+ return self.integration_id or "unknown ID"+ if self.kind == Integration.IntegrationKind.AWS_S3:+ name = self.integration_id or "unknown ID"++ account_id = self.config.get("aws_account_id")+ role = self.config.get("aws_role_arn")++ if role:+ detail = f"AWS role '{role}'"+ elif account_id:+ detail = f"AWS account {account_id}"+ else:+ detail = "access key"++ return f"{name} ({detail})"+ if self.kind == Integration.IntegrationKind.AWS_REDSHIFT:+ name = self.integration_id or "unknown ID"++ account_id = self.config.get("aws_account_id")+ role = self.config.get("aws_role_arn")+ host = self.config.get("host")+ user = self.config.get("user")++ if role:+ detail = f"AWS role '{role}'"+ elif account_id:+ detail = f"AWS account {account_id}"+ elif user and host:+ detail = f"{user}@{host}"+ else:+ detail = "access key"++ return f"{name} ({detail})"+ if self.kind == Integration.IntegrationKind.S3_COMPATIBLE:+ name = self.integration_id or "unknown ID"+ endpoint_url = self.config.get("endpoint_url")+ detail = f"access key, {endpoint_url}" if endpoint_url else "access key"+ return f"{name} ({detail})"+ if self.kind == Integration.IntegrationKind.SNOWFLAKE:+ name = self.integration_id or "unknown ID"+ auth_type = self.config.get("authentication_type", "password")+ account = self.config.get("account")+ return f"{name} (account: {account}, {auth_type} auth)"+ if self.kind == "gitlab":+ return self.integration_id or "unknown ID"+ if self.kind == "email":+ return self.config.get("email", self.integration_id)+ if self.kind == "apns":+ return self.config.get("bundle_id", self.integration_id)++ return f"ID: {self.integration_id}"++ @property+ def access_token(self) -> str | None:+ return _decrypted_sensitive_value(self, "access_token")++ @property+ def refresh_token(self) -> str | None:+ return _decrypted_sensitive_value(self, "refresh_token")+++def defer_repository_cache_fields(queryset: models.QuerySet[Integration]) -> models.QuerySet[Integration]:+ return queryset.defer("repository_cache", "repository_cache_updated_at")+++@database_sync_to_async+def aget_integration_by_id(integration_id: str, team_id: int) -> Integration | None:+ return Integration.objects.get(id=integration_id, team_id=team_id)diff --git a/posthog/models/integration/oauth.py b/posthog/models/integration/oauth.pynew file mode 100644index 000000000000..e626fae3d56e--- /dev/null+++ b/posthog/models/integration/oauth.py@@ -0,0 +1,1519 @@+"""Generic OAuth connect/refresh dispatcher shared by every generic-OAuth integration kind."""++import json+import time+import base64+import hashlib+import secrets+from dataclasses import field, replace+from datetime import timedelta+from typing import NoReturn+from urllib.parse import parse_qs, urlencode, urlparse++from django.conf import settings+from django.core.cache import cache++import requests+import structlog+from requests.auth import HTTPBasicAuth+from rest_framework.exceptions import ValidationError++from posthog.cache_utils import cache_for+from posthog.dataclasses import frozen+from posthog.egress.slack.observability import record_slack_api_response+from posthog.models.instance_setting import get_instance_settings+from posthog.models.user import User+from posthog.plugins.plugin_server_api import reload_integrations_on_workers+from posthog.schema_enums import SlackIntegrationScope+from posthog.scopes import get_oauth_scopes_supported++from . import common, model, refresh_tracking++logger = structlog.get_logger(__name__)+++def _extract_oauth_error_message(res: requests.Response) -> str | None:+ """Pull a human-readable error from a failed OAuth token-exchange response.++ Most providers (Stripe, Google, etc.) return JSON of the shape+ `{"error": "...", "error_description": "..."}`. Fall back to the raw body+ (truncated) when the JSON has none of those fields, or when the body isn't+ JSON at all — better to dump a snippet than to swallow the cause silently+ and let the caller render a status-code-only message.+ """+ try:+ body = res.json()+ except Exception:+ text = (res.text or "").strip()+ return text[:300] if text else None++ if isinstance(body, dict):+ description = body.get("error_description") or body.get("message")+ code = body.get("error")+ if description and code:+ return f"{code}: {description}"+ if description:+ return str(description)+ if code:+ return str(code)++ # Unknown shape — surface a serialized snippet so the customer at least sees what came back.+ try:+ snippet = json.dumps(body)+ except (TypeError, ValueError):+ snippet = (res.text or "").strip()+ return snippet[:300] if snippet else None+++def _raise_oauth_validation_error(kind: str, res: requests.Response) -> NoReturn:+ """Raise a ValidationError describing a failed OAuth token exchange.++ DRF turns ValidationError into a 400 with a populated `detail`, so the frontend toast renders+ a useful message instead of the generic "Something went wrong" fallback that follows from a+ bare Exception (which surfaces as a 500 with no detail).+ """+ provider_error = _extract_oauth_error_message(res)+ if provider_error:+ raise ValidationError(f"{kind} OAuth failed: {provider_error}")+ raise ValidationError(f"{kind} OAuth failed (status {res.status_code}). Please try again.")+++# Instagram API with Facebook Login: the professional account is reached through the Facebook Page+# it is linked to, so the grant needs the page permissions as well as the Instagram ones. Meta+# replaced the legacy `instagram_*` permission names with `instagram_business_*`; the old names are+# rejected at the OAuth dialog ("This app needs at least one supported permission").+# https://developers.facebook.com/docs/instagram-platform/instagram-api-with-facebook-login+INSTAGRAM_OAUTH_SCOPE = (+ "instagram_business_basic instagram_business_manage_insights instagram_business_manage_comments"+ " pages_show_list pages_read_engagement"+)+++@frozen+class OauthConfig:+ authorize_url: str+ token_url: str+ client_id: str+ client_secret: str = field(repr=False)+ scope: str+ id_path: str+ name_path: str+ token_info_url: str | None = None+ token_info_graphql_query: str | None = None+ token_info_config_fields: list[str] | None = None+ additional_authorize_params: dict[str, str] | None = None+ client_id_fallback: str | None = None+ client_secret_fallback: str | None = field(default=None, repr=False)+ # When true, the authorize/token-exchange flow uses PKCE (RFC 7636, S256)+ pkce: bool = False+ # When set, disconnecting the integration also revokes the grant at the provider+ token_revoke_url: str | None = None+++# Slack accepts comma-separated scopes on the OAuth authorize URL. The canonical list is the+# StrEnum declared in posthog/schema.py (generated from the SlackIntegrationScope enum in+# frontend/src/types.ts via `hogli build:schema`), so widening it on either side stays in sync.+#+# Every scope here is approved for the public Cloud app, so the same list is requested on every+# instance. Staging a scope Slack hasn't approved needs a DEV/local-only branch again — see the+# note by SlackIntegrationScope in frontend/src/types.ts.+POSTHOG_SLACK_SCOPE = ",".join(scope.value for scope in SlackIntegrationScope)+++def _salesforce_instance_host(instance_url: str | None) -> str | None:+ # Every Salesforce-issued instance_url host ends in .salesforce.com: login/test, the+ # pod hosts (na1.salesforce.com, ...), and My Domain variants like+ # acme.my.salesforce.com and acme--sandbox.sandbox.my.salesforce.com. Validating at+ # the point of use means a stray write to integration.config can't cause the shared+ # SALESFORCE_CONSUMER_SECRET to be POSTed to an attacker origin during a refresh,+ # even if a future endpoint or admin tool exposes config as writable. Returns+ # "https://<host>" for a legitimate value, None otherwise (caller falls back to the+ # hardcoded prod URL).+ if not instance_url:+ return None+ try:+ parsed = urlparse(instance_url)+ # port/hostname/username/password are lazily parsed from netloc on access, and+ # port in particular raises ValueError on a non-numeric or out-of-range value+ # (e.g. https://host:abc/). Keep every derived-property read inside the try so a+ # poisoned instance_url can never crash the refresh sweep.+ if parsed.scheme != "https" or parsed.port is not None or parsed.username or parsed.password:+ return None+ host = (parsed.hostname or "").lower()+ except ValueError:+ return None+ if not host.endswith(".salesforce.com"):+ return None+ return f"https://{host}"+++# Kinds authorized against Salesforce's OAuth server, so they share its quirks: the token+# response often omits expires_in, and refresh/revoke must go to the org's own instance host+# rather than the hardcoded login host (sandbox orgs reject the prod endpoints).+SALESFORCE_OAUTH_KINDS = ("salesforce", "pardot")++# PostHog connect. Unlike every other OAuth kind — which points at a fixed third-party provider —+# the `posthog` kind points at *another PostHog project*, in a region chosen by the user at connect+# time. That region may differ from the connecting project's or be the same one (same-region is just+# region == your own). So its authorize/token/userinfo URLs and client credentials are resolved per+# target region rather than baked into a static config. The connecting side is the OAuth client; the+# target region is the authorization server (its /oauth/authorize, /oauth/token, /oauth/userinfo,+# /oauth/revoke already exist). `openid`+`email` are always requested on top of the user-selected+# scopes so /oauth/userinfo can identify the connected account (`sub`/`email`).+POSTHOG_CONNECT_KIND = "posthog"++# `DEV` points at a local/self-hosted cell (`POSTHOG_CONNECT_BASE_URL_DEV` defaults to+# http://localhost:8000) and the token exchange is a server-side POST, so a production instance must+# never treat `DEV` as a real, connectable region — otherwise an org member could point the backend+# at a URL of their choosing. Gate it behind an explicit dev/test context rather than relying on the+# client id/secret env vars being unset.+_POSTHOG_CONNECT_ALLOW_DEV = bool(settings.DEBUG or settings.TEST or settings.E2E_TESTING)++POSTHOG_CONNECT_ALLOWED_REGIONS = ("US", "EU", *(("DEV",) if _POSTHOG_CONNECT_ALLOW_DEV else ()))++POSTHOG_CONNECT_DEFAULT_SCOPES = ("task:read", "task:write")++POSTHOG_CONNECT_IDENTITY_SCOPES = ("openid", "email")++# A connection can proxy any request the granted scopes allow, so the user may pick from the full set+# of user-grantable OAuth scopes (the same set the consent screen advertises — excludes internal,+# hidden, and privileged scopes). The real bound is enforced twice more downstream: the target cell's+# OAuthApplication.allowed_scopes at consent time, and the target's per-request scope checks. Identity+# scopes are auto-added and not part of this set.+POSTHOG_CONNECT_GRANTABLE_SCOPES = frozenset(get_oauth_scopes_supported())+++# nosemgrep: tuple-return-prefer-dataclass -- private helper, both call sites a few lines below in this file+def _posthog_connect_target(region: str | None) -> tuple[str, str, str]:+ """Resolve (base_url, client_id, client_secret) for a remote target cell.++ Raises NotImplementedError for an unknown or unconfigured region so the connect/refresh+ paths fail closed (surfaced to the user as a reconnect error) rather than silently hitting+ the wrong cell.+ """+ normalized = (region or "").upper()+ if normalized == "DEV" and not _POSTHOG_CONNECT_ALLOW_DEV:+ # Defense in depth: even if a `DEV` region row somehow reaches here in production, refuse to+ # resolve it so the backend never POSTs a token exchange to the dev base URL.+ raise NotImplementedError("PostHog connect DEV region is only available in dev/test")+ targets = {+ "US": (+ settings.POSTHOG_CONNECT_BASE_URL_US,+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_US,+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_US,+ ),+ "EU": (+ settings.POSTHOG_CONNECT_BASE_URL_EU,+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU,+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU,+ ),+ "DEV": (+ settings.POSTHOG_CONNECT_BASE_URL_DEV,+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_DEV,+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_DEV,+ ),+ }+ if normalized not in targets:+ raise NotImplementedError(f"PostHog connect OAuth not supported for region {region!r}")+ base_url, client_id, client_secret = targets[normalized]+ if not base_url or not client_id or not client_secret:+ raise NotImplementedError(f"PostHog connect app not configured for region {normalized}")+ return base_url.rstrip("/"), client_id, client_secret+++def posthog_connect_base_url(region: str | None) -> str:+ """Public base URL of a remote target cell (e.g. https://eu.posthog.com), for callers that+ need to reach its API with a `posthog` integration token. Raises for unknown/unconfigured regions."""+ base_url, _, _ = _posthog_connect_target(region)+ return base_url+++class OauthIntegration:+ supported_kinds = [+ "slack",+ "posthog",+ "salesforce",+ "hubspot",+ "google-ads",+ "google-analytics",+ "google-calendar",+ "google-search-console",+ "google-sheets",+ "snapchat",+ "linkedin-ads",+ "reddit-ads",+ "tiktok-ads",+ "bing-ads",+ "meta-ads",+ "instagram",+ "intercom",+ "linear",+ "clickup",+ "jira",+ "pardot",+ "pinterest-ads",+ "stripe",+ "resend",+ "youtube-analytics",+ ]+ integration: model.Integration++ def __str__(self) -> str:+ return f"OauthIntegration(integration={self.integration.id}, kind={self.integration.kind}, team={self.integration.team_id})"++ def __init__(self, integration: model.Integration) -> None:+ self.integration = integration++ @classmethod+ @cache_for(timedelta(minutes=5))+ def oauth_config_for_kind(cls, kind: str, region: str | None = None) -> OauthConfig:+ # `region` only applies to the `posthog` remote kind, whose endpoints depend on the+ # target cell. cache_for keys on all args, so each (kind, region) pair caches separately;+ # every other kind is called without region and keeps its single cached entry.+ config = cls._build_oauth_config(kind, region)+ fallback = settings.OAUTH_CLIENT_FALLBACKS.get(kind)+ if fallback and fallback.get("client_secret"):+ config = replace(+ config,+ client_secret_fallback=fallback["client_secret"],+ client_id_fallback=fallback.get("client_id") or config.client_id,+ )+ return config++ @classmethod+ def _build_oauth_config(cls, kind: str, region: str | None = None) -> OauthConfig:+ if kind == "posthog":+ base_url, client_id, client_secret = _posthog_connect_target(region)+ return OauthConfig(+ authorize_url=f"{base_url}/oauth/authorize",+ token_url=f"{base_url}/oauth/token",+ token_info_url=f"{base_url}/oauth/userinfo",+ token_info_config_fields=["sub", "email"],+ token_revoke_url=f"{base_url}/oauth/revoke",+ client_id=client_id,+ client_secret=client_secret,+ # Default only; authorize_url overrides with the user-selected scopes (plus the+ # identity scopes). Token exchange/refresh don't send scope, so this is unused there.+ scope=" ".join([*POSTHOG_CONNECT_DEFAULT_SCOPES, *POSTHOG_CONNECT_IDENTITY_SCOPES]),+ id_path="sub",+ name_path="email",+ pkce=True,+ )+ if kind == "slack":+ from_settings = get_instance_settings(+ [+ "SLACK_APP_CLIENT_ID",+ "SLACK_APP_CLIENT_SECRET",+ "SLACK_APP_SIGNING_SECRET",+ ]+ )++ if not from_settings["SLACK_APP_CLIENT_ID"] or not from_settings["SLACK_APP_CLIENT_SECRET"]:+ raise NotImplementedError("Slack app not configured")++ return OauthConfig(+ authorize_url="https://slack.com/oauth/v2/authorize",+ token_url="https://slack.com/api/oauth.v2.access",+ client_id=from_settings["SLACK_APP_CLIENT_ID"],+ client_secret=from_settings["SLACK_APP_CLIENT_SECRET"],+ scope=POSTHOG_SLACK_SCOPE,+ id_path="team.id",+ name_path="team.name",+ )+ elif kind == "salesforce":+ if not settings.SALESFORCE_CONSUMER_KEY or not settings.SALESFORCE_CONSUMER_SECRET:+ raise NotImplementedError("Salesforce app not configured")++ return OauthConfig(+ authorize_url="https://login.salesforce.com/services/oauth2/authorize",+ token_url="https://login.salesforce.com/services/oauth2/token",+ token_revoke_url="https://login.salesforce.com/services/oauth2/revoke",+ client_id=settings.SALESFORCE_CONSUMER_KEY,+ client_secret=settings.SALESFORCE_CONSUMER_SECRET,+ scope="full refresh_token",+ id_path="instance_url",+ name_path="instance_url",+ pkce=True,+ )+ elif kind == "salesforce-sandbox":+ if not settings.SALESFORCE_CONSUMER_KEY or not settings.SALESFORCE_CONSUMER_SECRET:+ raise NotImplementedError("Salesforce app not configured")++ return OauthConfig(+ authorize_url="https://test.salesforce.com/services/oauth2/authorize",+ token_url="https://test.salesforce.com/services/oauth2/token",+ token_revoke_url="https://test.salesforce.com/services/oauth2/revoke",+ client_id=settings.SALESFORCE_CONSUMER_KEY,+ client_secret=settings.SALESFORCE_CONSUMER_SECRET,+ scope="full refresh_token",+ id_path="instance_url",+ name_path="instance_url",+ pkce=True,+ )+ elif kind == "pardot":+ if not settings.SALESFORCE_CONSUMER_KEY or not settings.SALESFORCE_CONSUMER_SECRET:+ raise NotImplementedError("Salesforce app not configured")++ # Account Engagement (formerly Pardot) authorizes against Salesforce, so this reuses the+ # Salesforce connected app rather than registering a second one. It needs its own kind+ # because `pardot_api` is not covered by the `full` scope the `salesforce` kind requests:+ # a Salesforce integration authorized for the CRM cannot call the Account Engagement API,+ # and a token scoped for Account Engagement should not appear in the CRM picker.+ return OauthConfig(+ authorize_url="https://login.salesforce.com/services/oauth2/authorize",+ token_url="https://login.salesforce.com/services/oauth2/token",+ token_revoke_url="https://login.salesforce.com/services/oauth2/revoke",+ client_id=settings.SALESFORCE_CONSUMER_KEY,+ client_secret=settings.SALESFORCE_CONSUMER_SECRET,+ scope="pardot_api refresh_token",+ id_path="instance_url",+ name_path="instance_url",+ pkce=True,+ )+ elif kind == "hubspot":+ if not settings.HUBSPOT_APP_CLIENT_ID or not settings.HUBSPOT_APP_CLIENT_SECRET:+ raise NotImplementedError("Hubspot app not configured")++ return OauthConfig(+ authorize_url="https://app.hubspot.com/oauth/authorize",+ token_url="https://api.hubapi.com/oauth/v1/token",+ token_info_url="https://api.hubapi.com/oauth/v1/access-tokens/:access_token",+ token_info_config_fields=["hub_id", "hub_domain", "user", "user_id", "scopes"],+ client_id=settings.HUBSPOT_APP_CLIENT_ID,+ client_secret=settings.HUBSPOT_APP_CLIENT_SECRET,+ scope="tickets crm.objects.contacts.write sales-email-read crm.objects.companies.read crm.objects.deals.read crm.objects.contacts.read crm.objects.quotes.read crm.objects.companies.write",+ additional_authorize_params={+ # NOTE: these scopes are only available on certain hubspot plans and as such are optional.+ # crm.objects.leads.read is Sales Hub Pro+/Enterprise only — requesting it as a+ # mandatory scope would fail the whole authorization for portals that lack it.+ # The owners/commerce/product scopes are the same story: the data warehouse+ # source offers those tables, but the objects only exist on portals with the+ # matching hub, so they stay optional and their tables start deselected.+ "optional_scope": (+ "analytics.behavioral_events.send behavioral_events.event_definitions.read_write "+ "crm.objects.leads.read crm.objects.owners.read crm.objects.line_items.read "+ "crm.objects.products.read crm.objects.invoices.read crm.objects.orders.read "+ "crm.objects.subscriptions.read crm.objects.commercepayments.read"+ )+ },+ id_path="hub_id",+ name_path="hub_domain",+ )+ elif kind == "google-ads":+ if not settings.GOOGLE_ADS_APP_CLIENT_ID or not settings.GOOGLE_ADS_APP_CLIENT_SECRET:+ raise NotImplementedError("Google Ads app not configured")++ return OauthConfig(+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",+ # forces the consent screen, otherwise we won't receive a refresh token+ additional_authorize_params={"access_type": "offline", "prompt": "consent"},+ token_info_url="https://openidconnect.googleapis.com/v1/userinfo",+ token_info_config_fields=["sub", "email"],+ token_url="https://oauth2.googleapis.com/token",+ client_id=settings.GOOGLE_ADS_APP_CLIENT_ID,+ client_secret=settings.GOOGLE_ADS_APP_CLIENT_SECRET,+ scope="https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/userinfo.email",+ id_path="sub",+ name_path="email",+ )+ elif kind == "google-analytics":+ if not settings.GOOGLE_ANALYTICS_APP_CLIENT_ID or not settings.GOOGLE_ANALYTICS_APP_CLIENT_SECRET:+ raise NotImplementedError("Google Analytics app not configured")++ return OauthConfig(+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",+ # forces the consent screen, otherwise we won't receive a refresh token+ additional_authorize_params={"access_type": "offline", "prompt": "consent"},+ token_info_url="https://openidconnect.googleapis.com/v1/userinfo",+ token_info_config_fields=["sub", "email"],+ token_url="https://oauth2.googleapis.com/token",+ client_id=settings.GOOGLE_ANALYTICS_APP_CLIENT_ID,+ client_secret=settings.GOOGLE_ANALYTICS_APP_CLIENT_SECRET,+ scope="https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/userinfo.email",+ id_path="sub",+ name_path="email",+ )+ elif kind == "google-calendar":+ if not settings.GOOGLE_CALENDAR_APP_CLIENT_ID or not settings.GOOGLE_CALENDAR_APP_CLIENT_SECRET:+ raise NotImplementedError("Google Calendar app not configured")++ return OauthConfig(+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",+ # forces the consent screen, otherwise we won't receive a refresh token+ additional_authorize_params={"access_type": "offline", "prompt": "consent"},+ token_info_url="https://openidconnect.googleapis.com/v1/userinfo",+ token_info_config_fields=["sub", "email"],+ token_url="https://oauth2.googleapis.com/token",+ client_id=settings.GOOGLE_CALENDAR_APP_CLIENT_ID,+ client_secret=settings.GOOGLE_CALENDAR_APP_CLIENT_SECRET,+ scope="https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/userinfo.email",+ id_path="sub",+ name_path="email",+ )+ elif kind == "google-search-console":+ if not settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID or not settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET:+ raise NotImplementedError("Google Search Console app not configured")++ return OauthConfig(+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",+ additional_authorize_params={"access_type": "offline", "prompt": "consent"},+ token_info_url="https://openidconnect.googleapis.com/v1/userinfo",+ token_info_config_fields=["sub", "email"],+ token_url="https://oauth2.googleapis.com/token",+ client_id=settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID,+ client_secret=settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET,+ scope="https://www.googleapis.com/auth/webmasters.readonly https://www.googleapis.com/auth/userinfo.email",+ id_path="sub",+ name_path="email",+ )+ elif kind == "google-sheets":+ if not settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY or not settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET:+ raise NotImplementedError("Google Sheets app not configured")++ return OauthConfig(+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",+ # forces the consent screen, otherwise we won't receive a refresh token+ additional_authorize_params={"access_type": "offline", "prompt": "consent"},+ token_info_url="https://openidconnect.googleapis.com/v1/userinfo",+ token_info_config_fields=["sub", "email"],+ token_url="https://oauth2.googleapis.com/token",+ client_id=settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY,+ client_secret=settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET,+ scope="https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/userinfo.email",+ id_path="sub",+ name_path="email",+ )+ elif kind == "youtube-analytics":+ if not settings.YOUTUBE_ANALYTICS_APP_CLIENT_ID or not settings.YOUTUBE_ANALYTICS_APP_CLIENT_SECRET:+ raise NotImplementedError("YouTube Analytics app not configured")++ return OauthConfig(+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",+ # forces the consent screen, otherwise we won't receive a refresh token+ additional_authorize_params={"access_type": "offline", "prompt": "consent"},+ token_info_url="https://openidconnect.googleapis.com/v1/userinfo",+ token_info_config_fields=["sub", "email"],+ token_url="https://oauth2.googleapis.com/token",+ client_id=settings.YOUTUBE_ANALYTICS_APP_CLIENT_ID,+ client_secret=settings.YOUTUBE_ANALYTICS_APP_CLIENT_SECRET,+ # `yt-analytics.readonly` reads the reports; `youtube.readonly` lists the account's+ # channels so the user picks one instead of hunting for its ID. Channel reports carry+ # no revenue metrics, so `yt-analytics-monetary.readonly` is deliberately not asked for.+ scope=(+ "https://www.googleapis.com/auth/yt-analytics.readonly "+ "https://www.googleapis.com/auth/youtube.readonly "+ "https://www.googleapis.com/auth/userinfo.email"+ ),+ id_path="sub",+ name_path="email",+ )+ elif kind == "snapchat":+ if not settings.SNAPCHAT_APP_CLIENT_ID or not settings.SNAPCHAT_APP_CLIENT_SECRET:+ raise NotImplementedError("Snapchat app not configured")++ return OauthConfig(+ authorize_url="https://accounts.snapchat.com/accounts/oauth2/auth",+ token_url="https://accounts.snapchat.com/accounts/oauth2/token",+ token_info_url="https://adsapi.snapchat.com/v1/me",+ token_info_config_fields=["me.id", "me.email"],+ client_id=settings.SNAPCHAT_APP_CLIENT_ID,+ client_secret=settings.SNAPCHAT_APP_CLIENT_SECRET,+ scope="snapchat-offline-conversions-api snapchat-marketing-api",+ id_path="me.id",+ name_path="me.email",+ )+ elif kind == "linkedin-ads":+ if not settings.LINKEDIN_APP_CLIENT_ID or not settings.LINKEDIN_APP_CLIENT_SECRET:+ raise NotImplementedError("LinkedIn Ads app not configured")++ # Note: We extract user info from id_token JWT instead of calling token_info_url+ # because LinkedIn's /v2/userinfo endpoint has intermittent issues returning+ # REVOKED_ACCESS_TOKEN errors for valid tokens. See JWT extraction below.+ return OauthConfig(+ authorize_url="https://www.linkedin.com/oauth/v2/authorization",+ token_url="https://www.linkedin.com/oauth/v2/accessToken",+ client_id=settings.LINKEDIN_APP_CLIENT_ID,+ client_secret=settings.LINKEDIN_APP_CLIENT_SECRET,+ scope="r_ads rw_conversions r_ads_reporting openid profile email",+ id_path="sub",+ name_path="email",+ )+ elif kind == "bing-ads":+ if not settings.BING_ADS_CLIENT_ID or not settings.BING_ADS_CLIENT_SECRET:+ raise NotImplementedError("Bing Ads app not configured")++ return OauthConfig(+ authorize_url="https://login.microsoftonline.com/common/oauth2/v2.0/authorize",+ token_url="https://login.microsoftonline.com/common/oauth2/v2.0/token",+ client_id=settings.BING_ADS_CLIENT_ID,+ client_secret=settings.BING_ADS_CLIENT_SECRET,+ scope="https://ads.microsoft.com/msads.manage offline_access openid profile",+ id_path="id",+ name_path="userPrincipalName",+ )+ elif kind == "intercom":+ if not settings.INTERCOM_APP_CLIENT_ID or not settings.INTERCOM_APP_CLIENT_SECRET:+ raise NotImplementedError("Intercom app not configured")++ return OauthConfig(+ authorize_url="https://app.intercom.com/oauth",+ token_url="https://api.intercom.io/auth/eagle/token",+ token_info_url="https://api.intercom.io/me",+ token_info_config_fields=["id", "email", "app.region"],+ client_id=settings.INTERCOM_APP_CLIENT_ID,+ client_secret=settings.INTERCOM_APP_CLIENT_SECRET,+ scope="",+ id_path="id",+ name_path="email",+ )+ elif kind == "linear":+ if not settings.LINEAR_APP_CLIENT_ID or not settings.LINEAR_APP_CLIENT_SECRET:+ raise NotImplementedError("Linear app not configured")++ return OauthConfig(+ authorize_url="https://linear.app/oauth/authorize",+ additional_authorize_params={"actor": "application"},+ token_url="https://api.linear.app/oauth/token",+ token_info_url="https://api.linear.app/graphql",+ token_info_graphql_query="{ viewer { organization { id name urlKey } } }",+ token_info_config_fields=[+ "data.viewer.organization.id",+ "data.viewer.organization.name",+ "data.viewer.organization.urlKey",+ ],+ client_id=settings.LINEAR_APP_CLIENT_ID,+ client_secret=settings.LINEAR_APP_CLIENT_SECRET,+ scope="read issues:create",+ id_path="data.viewer.organization.id",+ name_path="data.viewer.organization.name",+ )+ elif kind == "meta-ads":+ if not settings.META_ADS_APP_CLIENT_ID or not settings.META_ADS_APP_CLIENT_SECRET:+ raise NotImplementedError("Meta Ads app not configured")++ return OauthConfig(+ authorize_url=f"https://www.facebook.com/{common.META_GRAPH_API_VERSION}/dialog/oauth",+ token_url=f"https://graph.facebook.com/{common.META_GRAPH_API_VERSION}/oauth/access_token",+ token_info_url=f"https://graph.facebook.com/{common.META_GRAPH_API_VERSION}/me",+ token_info_config_fields=["id", "name", "email"],+ client_id=settings.META_ADS_APP_CLIENT_ID,+ client_secret=settings.META_ADS_APP_CLIENT_SECRET,+ scope="ads_read",+ id_path="id",+ name_path="name",+ )+ elif kind == "instagram":+ if not settings.INSTAGRAM_APP_CLIENT_ID or not settings.INSTAGRAM_APP_CLIENT_SECRET:+ raise NotImplementedError("Instagram app not configured")++ # Same Facebook Login endpoints as Meta Ads, and the credentials may even be the same+ # Meta app, but the two grants request different scopes so they stay separate kinds.+ # The token response carries no account identifier, so id/name come from `/me`.+ return OauthConfig(+ authorize_url=f"https://www.facebook.com/{common.META_GRAPH_API_VERSION}/dialog/oauth",+ token_url=f"https://graph.facebook.com/{common.META_GRAPH_API_VERSION}/oauth/access_token",+ token_info_url=f"https://graph.facebook.com/{common.META_GRAPH_API_VERSION}/me",+ token_info_config_fields=["id", "name"],+ client_id=settings.INSTAGRAM_APP_CLIENT_ID,+ client_secret=settings.INSTAGRAM_APP_CLIENT_SECRET,+ scope=INSTAGRAM_OAUTH_SCOPE,+ id_path="id",+ name_path="name",+ )+ elif kind == "reddit-ads":+ if not settings.REDDIT_ADS_CLIENT_ID or not settings.REDDIT_ADS_CLIENT_SECRET:+ raise NotImplementedError("Reddit Ads app not configured")++ return OauthConfig(+ authorize_url="https://www.reddit.com/api/v1/authorize",+ token_url="https://www.reddit.com/api/v1/access_token",+ client_id=settings.REDDIT_ADS_CLIENT_ID,+ client_secret=settings.REDDIT_ADS_CLIENT_SECRET,+ scope="read adsread adsconversions history adsedit",+ id_path="reddit_user_id", # We'll extract this from JWT+ # ads-api /me returns the human-readable username under the granted ads scopes+ # (oauth.reddit.com/api/v1/me would need the extra `identity` scope), wrapped in a+ # `data` object. Falls back to the JWT user id when absent.+ token_info_url="https://ads-api.reddit.com/api/v3/me",+ token_info_config_fields=["data.reddit_username"],+ name_path="data.reddit_username",+ additional_authorize_params={"duration": "permanent"},+ )+ elif kind == "tiktok-ads":+ if not settings.TIKTOK_ADS_CLIENT_ID or not settings.TIKTOK_ADS_CLIENT_SECRET:+ raise NotImplementedError("TikTok Ads app not configured")++ return OauthConfig(+ authorize_url="https://business-api.tiktok.com/portal/auth",+ token_url="https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/",+ client_id=settings.TIKTOK_ADS_CLIENT_ID,+ client_secret=settings.TIKTOK_ADS_CLIENT_SECRET,+ scope="",+ id_path="data.advertiser_ids",+ name_path="data.advertiser_ids",+ )+ elif kind == "clickup":+ if not settings.CLICKUP_APP_CLIENT_ID or not settings.CLICKUP_APP_CLIENT_SECRET:+ raise NotImplementedError("ClickUp app not configured")++ return OauthConfig(+ authorize_url="https://app.clickup.com/api",+ token_url="https://api.clickup.com/api/v2/oauth/token",+ token_info_url="https://api.clickup.com/api/v2/user",+ token_info_config_fields=["user.id", "user.email"],+ client_id=settings.CLICKUP_APP_CLIENT_ID,+ client_secret=settings.CLICKUP_APP_CLIENT_SECRET,+ scope="",+ id_path="user.id",+ name_path="user.email",+ )+ elif kind == "jira":+ if not settings.ATLASSIAN_APP_CLIENT_ID or not settings.ATLASSIAN_APP_CLIENT_SECRET:+ raise NotImplementedError("Atlassian/Jira app not configured")++ return OauthConfig(+ authorize_url="https://auth.atlassian.com/authorize",+ additional_authorize_params={"audience": "api.atlassian.com", "prompt": "consent"},+ token_url="https://auth.atlassian.com/oauth/token",+ token_info_url="https://api.atlassian.com/oauth/token/accessible-resources",+ token_info_config_fields=[], # Handled specially in integration_from_oauth_response+ client_id=settings.ATLASSIAN_APP_CLIENT_ID,+ client_secret=settings.ATLASSIAN_APP_CLIENT_SECRET,+ scope="read:jira-work write:jira-work offline_access",+ id_path="cloud_id",+ name_path="site_name",+ )+ elif kind == "pinterest-ads":+ if not settings.PINTEREST_ADS_CLIENT_ID or not settings.PINTEREST_ADS_CLIENT_SECRET:+ raise NotImplementedError("Pinterest Ads app not configured")++ return OauthConfig(+ authorize_url="https://www.pinterest.com/oauth/",+ token_url="https://api.pinterest.com/v5/oauth/token",+ token_info_url="https://api.pinterest.com/v5/user_account",+ token_info_config_fields=["id", "username", "business_name"],+ client_id=settings.PINTEREST_ADS_CLIENT_ID,+ client_secret=settings.PINTEREST_ADS_CLIENT_SECRET,+ scope="ads:read user_accounts:read",+ id_path="id",+ name_path="username",+ )+ elif kind == "stripe":+ if not settings.STRIPE_APP_CLIENT_ID or not settings.STRIPE_APP_SECRET_KEY:+ raise NotImplementedError("Stripe app not configured")++ client_id = settings.STRIPE_APP_CLIENT_ID+ client_secret = settings.STRIPE_APP_SECRET_KEY++ authorize_url = (+ settings.STRIPE_APP_OVERRIDE_AUTHORIZE_URL or "https://marketplace.stripe.com/oauth/v2/authorize"+ )+ return OauthConfig(+ authorize_url=authorize_url,+ token_url="https://api.stripe.com/v1/oauth/token",+ client_id=client_id,+ client_secret=client_secret,+ scope="",+ id_path="stripe_user_id",+ name_path="account_name",+ )+ elif kind == "resend":+ if not settings.RESEND_APP_CLIENT_ID or not settings.RESEND_APP_CLIENT_SECRET:+ raise NotImplementedError("Resend app not configured")++ # Resend implements OAuth 2.1: PKCE is required, and access tokens are short-lived+ # (~15m) JWTs while refresh tokens rotate on every use. We register as a confidential+ # client (token_endpoint_auth_method=client_secret_post), so the standard client_secret+ # token-exchange/refresh path applies on top of PKCE. `full_access` is the scope needed+ # to read the warehouse resources (emails/audiences/contacts/domains/broadcasts).+ # The token response carries no account identifier, so id/name are derived from the+ # access-token JWT below (see the resend branch in integration_from_oauth_response).+ return OauthConfig(+ authorize_url="https://resend.com/oauth/authorize",+ token_url="https://api.resend.com/oauth/token",+ token_revoke_url="https://api.resend.com/oauth/revoke",+ client_id=settings.RESEND_APP_CLIENT_ID,+ client_secret=settings.RESEND_APP_CLIENT_SECRET,+ scope="full_access",+ pkce=True,+ id_path="resend_account_id",+ name_path="resend_account_name",+ )++ raise NotImplementedError(f"Oauth config for kind {kind} not implemented")++ @classmethod+ def redirect_uri(cls, kind: str) -> str:+ # The redirect uri is fixed but should always be https and include the "next" parameter for the frontend to redirect+ if settings.DEBUG and settings.NGROK_URL:+ return f"{settings.NGROK_URL}/integrations/{kind}/callback"+ return f"{settings.SITE_URL.replace('http://', 'https://')}/integrations/{kind}/callback"++ @classmethod+ def authorize_url(+ cls,+ kind: str,+ token: str,+ next: str = "",+ *,+ region: str | None = None,+ scopes: list[str] | None = None,+ team_id: int | None = None,+ ) -> str:+ oauth_config = cls.oauth_config_for_kind(kind, region)++ # Carry the initiating team through the OAuth round-trip. The fixed callback URL is not+ # project-scoped, so without this the SPA re-resolves to the user's default team on+ # reload and the integration lands on the wrong project.+ state_payload: dict[str, str] = {"next": next, "token": token}+ if team_id is not None:+ state_payload["team_id"] = str(team_id)++ scope = oauth_config.scope+ if kind == "posthog":+ # The target cell is the authorization server, so the callback (which runs on the+ # connecting cell) needs to know which region to exchange the code against — carry it+ # in state. Always append the identity scopes so /oauth/userinfo can name the account.+ state_payload["region"] = (region or "").upper()+ requested = list(scopes) if scopes else list(POSTHOG_CONNECT_DEFAULT_SCOPES)+ scope = " ".join(dict.fromkeys([*requested, *POSTHOG_CONNECT_IDENTITY_SCOPES]))++ if kind == "tiktok-ads":+ # TikTok uses different parameter names+ query_params = {+ "app_id": oauth_config.client_id,+ "redirect_uri": cls.redirect_uri(kind),+ "state": urlencode(state_payload),+ }+ else:+ query_params = {+ "client_id": oauth_config.client_id,+ "scope": scope,+ "redirect_uri": cls.redirect_uri(kind),+ "response_type": "code",+ "state": urlencode(state_payload),+ **(oauth_config.additional_authorize_params or {}),+ }++ if oauth_config.pkce:+ # The verifier is cached against the state token so the token exchange —+ # a separate request via the frontend callback — can retrieve it.+ code_verifier = secrets.token_urlsafe(64)+ code_challenge = (+ base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).rstrip(b"=").decode()+ )+ query_params["code_challenge"] = code_challenge+ query_params["code_challenge_method"] = "S256"+ cache.set(f"oauth_pkce_verifier/{token}", code_verifier, timeout=60 * 5)++ return f"{oauth_config.authorize_url}?{urlencode(query_params)}"++ @classmethod+ def integration_from_oauth_response(+ cls, kind: str, team_id: int, created_by: User, params: dict[str, str]+ ) -> model.Integration:+ region: str | None = None+ if kind == "posthog":+ # The target region was stashed in state at authorize time; the token exchange must hit+ # that same cell. Missing/invalid region fails closed via _posthog_connect_target.+ region = (parse_qs(params.get("state", "")).get("region", [""])[0] or "").upper()++ oauth_config = cls.oauth_config_for_kind(kind, region)++ code_verifier: str | None = None+ if oauth_config.pkce:+ state_token = parse_qs(params.get("state", "")).get("token", [""])[0]+ if state_token:+ verifier_cache_key = f"oauth_pkce_verifier/{state_token}"+ code_verifier = cache.get(verifier_cache_key)+ cache.delete(verifier_cache_key) # single-use, per RFC 7636+ # Missing verifier still exchanges without PKCE (Salesforce accepts that until it+ # requires PKCE). Log it so the gap is visible before we enforce PKCE provider-side.+ if not code_verifier:+ logger.warning("oauth_pkce_verifier_missing", kind=kind, has_state_token=bool(state_token))+ # posthog is a first-party flow we control both ends of — a missing verifier is never+ # a legacy-provider compat case here, so fail closed rather than exchanging without PKCE.+ if kind == "posthog":+ raise ValidationError("Remote authorization failed: missing PKCE verifier. Please retry.")++ # Reddit uses HTTP Basic Auth https://github.com/reddit-archive/reddit/wiki/OAuth2 and requires a User-Agent header+ if kind == "reddit-ads":+ res = requests.post(+ oauth_config.token_url,+ auth=HTTPBasicAuth(oauth_config.client_id, oauth_config.client_secret),+ data={+ "code": params["code"],+ "redirect_uri": OauthIntegration.redirect_uri(kind),+ "grant_type": "authorization_code",+ },+ headers={"User-Agent": "PostHog/1.0 by PostHogTeam"},+ timeout=10,+ )+ # Pinterest uses HTTP Basic Auth for token exchange (base64-encoded client_id:client_secret)+ elif kind == "pinterest-ads":+ res = requests.post(+ oauth_config.token_url,+ auth=HTTPBasicAuth(oauth_config.client_id, oauth_config.client_secret),+ data={+ "code": params["code"],+ "redirect_uri": OauthIntegration.redirect_uri(kind),+ "grant_type": "authorization_code",+ },+ timeout=10,+ )+ elif kind == "tiktok-ads":+ # TikTok Ads uses JSON request body instead of form data and maps 'code' to 'auth_code'+ res = requests.post(+ oauth_config.token_url,+ json={+ "app_id": oauth_config.client_id,+ "secret": oauth_config.client_secret,+ "auth_code": params["code"],+ },+ headers={"Content-Type": "application/json"},+ timeout=10,+ )+ elif kind == "stripe":+ # Stripe Apps OAuth authenticates with the developer secret key as HTTP Basic+ # username and does not accept client_id/redirect_uri in the token-exchange body.+ # Connect OAuth (client_id+client_secret in body) is a different system.+ res = requests.post(+ oauth_config.token_url,+ auth=HTTPBasicAuth(oauth_config.client_secret, ""),+ data={+ "code": params["code"],+ "grant_type": "authorization_code",+ },+ timeout=10,+ )+ else:+ redirect_uri = OauthIntegration.redirect_uri(kind)+ res = requests.post(+ oauth_config.token_url,+ data={+ "client_id": oauth_config.client_id,+ "client_secret": oauth_config.client_secret,+ "code": params["code"],+ "redirect_uri": redirect_uri,+ "grant_type": "authorization_code",+ **({"code_verifier": code_verifier} if code_verifier else {}),+ },+ timeout=10,+ # allow_redirects=False so a misconfigured/compromised token endpoint can't 30x us+ # into resending client_secret + authorization code to another origin.+ allow_redirects=False,+ )++ if kind == "slack":+ record_slack_api_response(+ res,+ source="oauth",+ workspace_id=None,+ app_id="posthog",+ method="POST",+ endpoint="oauth.v2.access",+ )++ try:+ config: dict = res.json()+ except ValueError:+ # Non-JSON body (e.g. an HTML 502 from a proxy). Keep going so the status-code+ # branch below can surface a structured ValidationError to the frontend.+ config = {}++ access_token = None+ if kind == "tiktok-ads":+ # TikTok has a different response format - access_token is nested under 'data'+ access_token = config.get("data", {}).get("access_token")+ else:+ access_token = config.get("access_token")++ if res.status_code != 200 or not access_token:+ # Hack to try getting sandbox auth token instead of their salesforce production account+ if kind == "salesforce":+ oauth_config = cls.oauth_config_for_kind("salesforce-sandbox")+ res = requests.post(+ oauth_config.token_url,+ data={+ "client_id": oauth_config.client_id,+ "client_secret": oauth_config.client_secret,+ "code": params["code"],+ "redirect_uri": OauthIntegration.redirect_uri(kind),+ "grant_type": "authorization_code",+ **({"code_verifier": code_verifier} if code_verifier else {}),+ },+ timeout=10,+ )++ try:+ config = res.json()+ except ValueError:+ config = {}++ if res.status_code != 200 or not config.get("access_token"):+ logger.error(f"Oauth error for {kind}", response=res.text)+ _raise_oauth_validation_error(kind, res)+ else:+ # Include request context so on-call can compare what we sent against what+ # the merchant authorized with in Stripe. Code prefix only, full grant is+ # short-lived but still a credential during its TTL. Never log client_secret.+ logger.error(+ f"Oauth error for {kind}",+ response=res.text,+ status_code=res.status_code,+ client_id=oauth_config.client_id,+ redirect_uri=OauthIntegration.redirect_uri(kind),+ code_prefix=str(params.get("code", ""))[:12],+ )+ # Surface the provider's error to the frontend toast — without this, DRF turns+ # the bare Exception into a generic 500 and the user sees "Something went wrong"+ # with no actionable detail. ValidationError → 400 with `detail` set.+ _raise_oauth_validation_error(kind, res)++ if oauth_config.token_info_url:+ # If token info url is given we call it and check the integration id from there+ if oauth_config.token_info_graphql_query:+ token_info_res = requests.post(+ oauth_config.token_info_url,+ headers={"Authorization": f"Bearer {config['access_token']}"},+ json={"query": oauth_config.token_info_graphql_query},+ timeout=10,+ # This call carries the access token; don't let a misconfigured/compromised+ # provider 30x us into resending it to another origin (matches the exchange/refresh/revoke calls).+ allow_redirects=False,+ )+ else:+ token_info_res = requests.get(+ oauth_config.token_info_url.replace(":access_token", config["access_token"]),+ headers={"Authorization": f"Bearer {config['access_token']}"},+ timeout=10,+ allow_redirects=False,+ )++ if token_info_res.status_code == 200:+ data = token_info_res.json()++ # Jira returns an array of accessible resources, extract the first one+ if kind == "jira" and isinstance(data, list):+ if len(data) > 0:+ site = data[0]+ config["cloud_id"] = site.get("id")+ config["site_name"] = site.get("name")+ config["site_url"] = site.get("url")+ else:+ logger.error(+ "Jira OAuth returned empty accessible resources array - user may not have access to any Jira sites",+ kind=kind,+ )+ raise ValidationError(+ "No accessible Jira sites found. Please ensure your Atlassian account has access to at least one Jira site."+ )+ elif oauth_config.token_info_config_fields:+ for field in oauth_config.token_info_config_fields:+ config[field] = common.dot_get(data, field)+ else:+ logger.error(+ f"OAuth token_info request failed for {kind}",+ token_info_url=oauth_config.token_info_url,+ status_code=token_info_res.status_code,+ response=token_info_res.text[:500],+ )++ integration_id = common.dot_get(config, oauth_config.id_path)++ # Bing Ads id_token is a JWT, extract user ID from it+ if kind == "bing-ads" and not integration_id:+ try:+ id_token = config.get("id_token")+ if id_token:+ jwt_data = common._decode_jwt_payload(id_token)+ if jwt_data:+ bing_user_id = jwt_data.get("oid")+ bing_username = jwt_data.get("preferred_username")+ if bing_user_id:+ config["id"] = bing_user_id+ config["userPrincipalName"] = bing_username+ integration_id = bing_user_id+ else:+ logger.error("Bing Ads OAuth response missing id_token", config_keys=list(config.keys()))+ except Exception:+ logger.exception("Failed to decode Bing Ads JWT")++ # Reddit access token is a JWT, extract user ID from it+ if kind == "reddit-ads" and not integration_id:+ try:+ access_token = config.get("access_token")+ if access_token:+ jwt_data = common._decode_jwt_payload(access_token)+ if jwt_data:+ # Extract user ID from JWT (lid = login ID)+ reddit_user_id = jwt_data.get("lid", jwt_data.get("aid"))+ if reddit_user_id:+ config["reddit_user_id"] = reddit_user_id+ integration_id = reddit_user_id+ except Exception as e:+ logger.exception("Failed to decode Reddit JWT", error=str(e))++ # Resend's token response carries no account identifier, but the access token is a JWT.+ # Derive the integration id/name from its claims (`sub` is the account subject; email/name+ # are used for a human-readable label when present). Assumes the standard `sub` claim — if+ # Resend uses a different claim, the missing-id guard below raises and the user sees a clear+ # reconnect error rather than a silently mislabeled integration.+ if kind == "resend" and not integration_id:+ try:+ access_token = config.get("access_token")+ if access_token:+ jwt_data = common._decode_jwt_payload(access_token)+ if jwt_data:+ resend_account_id = jwt_data.get("sub")+ if resend_account_id:+ config["resend_account_id"] = resend_account_id+ config["resend_account_name"] = (+ jwt_data.get("email") or jwt_data.get("name") or f"Resend account {resend_account_id}"+ )+ integration_id = resend_account_id+ else:+ logger.error("Resend OAuth response missing access_token", config_keys=list(config.keys()))+ except Exception:+ logger.exception("Failed to decode Resend JWT")++ # LinkedIn id_token is a JWT, extract user ID and email from it+ # This avoids calling /v2/userinfo which has intermittent REVOKED_ACCESS_TOKEN errors+ if kind == "linkedin-ads" and not integration_id:+ try:+ id_token = config.get("id_token")+ if id_token:+ jwt_data = common._decode_jwt_payload(id_token)+ if jwt_data:+ linkedin_user_id = jwt_data.get("sub")+ linkedin_email = jwt_data.get("email")+ if linkedin_user_id:+ config["sub"] = linkedin_user_id+ config["email"] = linkedin_email+ integration_id = linkedin_user_id+ else:+ logger.error("LinkedIn Ads OAuth response missing id_token", config_keys=list(config.keys()))+ except Exception:+ logger.exception("Failed to decode LinkedIn JWT")++ # Stripe OAuth returns stripe_user_id but no account name — fetch it from the Accounts API+ if kind == "stripe" and integration_id:+ try:+ from stripe import StripeClient # noqa: PLC0415++ stripe_client = StripeClient(oauth_config.client_secret)+ account = stripe_client.accounts.retrieve(str(integration_id))+ business_profile = getattr(account, "business_profile", None)+ business_name = getattr(business_profile, "name", None) if business_profile else None+ company = getattr(account, "company", None)+ company_name = getattr(company, "name", None) if company else None+ account_name = business_name or company_name or getattr(account, "email", None) or str(integration_id)+ config["account_name"] = f"{account_name} ({integration_id})"+ except Exception:+ logger.exception("Failed to fetch Stripe account name")+ config["account_name"] = str(integration_id)++ # Persist the target region and namespace the dedup key by it, so the same PostHog account+ # connected in two different cells yields two distinct integrations instead of colliding on+ # `sub`. `region` also drives config/refresh/revoke lookups for the lifetime of the row.+ if kind == "posthog" and integration_id:+ config["region"] = region+ integration_id = f"{region}:{integration_id}"+ # Persist the resource scopes the target actually granted (obj:action only, dropping the+ # openid/email identity scopes). The connection proxy uses this to require a caller's own+ # token to cover these scopes before it will wield the connection's grant.+ config["granted_scopes"] = sorted({s for s in (config.get("scope") or "").split() if ":" in s})++ # TikTok can complete OAuth without the user granting any advertiser account, leaving+ # `advertiser_ids` empty. Surface an actionable reconnect message rather than the generic+ # "failed to extract integration ID" 500 the guard below would otherwise raise.+ if kind == "tiktok-ads" and isinstance(integration_id, list) and len(integration_id) == 0:+ raise ValidationError(+ "No TikTok ad accounts were authorized. In TikTok, grant access to at least one "+ "advertiser account, then reconnect."+ )++ if isinstance(integration_id, int):+ integration_id = str(integration_id)+ elif isinstance(integration_id, list) and len(integration_id) > 0:+ integration_id = ",".join(str(item) for item in integration_id)++ if not isinstance(integration_id, str):+ raise Exception(f"Oauth error: failed to extract integration ID for {kind}")++ # Handle TikTok's nested response format+ if kind == "tiktok-ads":+ data = config.pop("data", {})+ # Move other data fields to main config for TikTok+ config.update(data)+ # Best-effort: fetch who authorized this, so it isn't listed as a row of advertiser ids.+ try:+ user_res = requests.get(+ "https://business-api.tiktok.com/open_api/v1.3/user/info/",+ headers={"Access-Token": config["access_token"]},+ timeout=10,+ )+ # TikTok answers 200 even when the call failed; the body `code` (0 = OK) is the outcome.+ body = user_res.json()+ if body.get("code") == 0:+ user = body.get("data") or {}+ if user.get("email"):+ config["user_email"] = user["email"]+ if user.get("display_name"):+ config["user_display_name"] = user["display_name"]+ except Exception:+ logger.warning("Failed to fetch TikTok user info for display name")++ sensitive_config: dict = {+ "access_token": config.pop("access_token"),+ # NOTE: We don't actually use the refresh and id tokens (typically they aren't even provided for this sort of service auth)+ # but we ensure they are popped and stored in sensitive config to avoid accidental exposure+ "refresh_token": config.pop("refresh_token", None),+ "id_token": config.pop("id_token", None),+ }++ # Handle case where Salesforce doesn't provide expires_in in initial response+ if not config.get("expires_in") and kind in SALESFORCE_OAUTH_KINDS:+ # Default to 1 hour for Salesforce if not provided (conservative)+ config["expires_in"] = 3600++ # Stripe Apps OAuth tokens don't include expires_in in the response+ if not config.get("expires_in") and kind == "stripe":+ config["expires_in"] = 3600++ config["refreshed_at"] = int(time.time())++ integration, created = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind=kind,+ integration_id=integration_id,+ defaults={+ "config": config,+ "sensitive_config": sensitive_config,+ "created_by": created_by,+ },+ )++ if integration.errors:+ integration.errors = ""+ integration.save()++ if kind == "slack":+ # The cached auth verdict in slack_app is per-integration. A+ # reconnect mints a new bot token, so any stale ``ok=false`` row+ # from the previous token would silently demote this install for+ # the remaining cache TTL. Inline-imported to keep the slack_app+ # module off the core django.setup() path; wrapped so a broken+ # slack_app build can't take down OAuth completion for every+ # integration kind.+ try:+ from products.slack_app.backend.facade.api import ( # noqa: PLC0415+ invalidate_slack_integration_auth_state,+ )++ invalidate_slack_integration_auth_state(integration.id)+ except Exception:+ logger.warning(+ "slack_app_auth_state_invalidation_on_oauth_failed",+ integration_id=integration.id,+ exc_info=True,+ )++ return integration++ def revoke_token(self) -> None:+ """Revoke the OAuth grant at the provider, for kinds with a revoke endpoint.++ Revoking the refresh token also invalidates its access tokens (per RFC 7009 and+ Salesforce's revoke semantics), so the provider no longer considers PostHog authorized+ after a disconnect. Callers treat this as best-effort — the local deletion proceeds+ regardless.+ """+ region = self.integration.config.get("region") if self.integration.kind == "posthog" else None+ oauth_config = self.oauth_config_for_kind(self.integration.kind, region)+ if not oauth_config.token_revoke_url:+ return++ # Prefer the refresh token: revoking it invalidates the whole grant (and its access+ # tokens), so an attacker holding it can't keep minting access tokens after disconnect.+ refresh_token = self.integration.sensitive_config.get("refresh_token")+ token = refresh_token or self.integration.sensitive_config.get("access_token")+ if not token:+ return++ revoke_url = oauth_config.token_revoke_url+ # Salesforce sandbox integrations are stored under the production kind (the sandbox is+ # only a token-exchange fallback), so the static prod revoke URL would miss them. Revoke+ # at the validated instance host so a stray write to config can't redirect the token to+ # an attacker origin.+ if self.integration.kind in SALESFORCE_OAUTH_KINDS:+ allowed_host = _salesforce_instance_host(self.integration.config.get("instance_url"))+ if allowed_host:+ revoke_url = f"{allowed_host}/services/oauth2/revoke"++ data = {"token": token}+ if self.integration.kind == "resend":+ # Resend registers PostHog as a confidential client (token_endpoint_auth_method=+ # client_secret_post) and requires client authentication on revocation. Without it+ # the endpoint rejects the request and the grant survives the disconnect. The hint+ # tells the provider which token type it received (RFC 7009).+ data["client_id"] = oauth_config.client_id+ data["client_secret"] = oauth_config.client_secret+ data["token_type_hint"] = "refresh_token" if refresh_token else "access_token"++ # allow_redirects=False so a misconfigured/compromised provider can't 30x us into+ # resending the token to another host. raise_for_status surfaces a provider rejection+ # to the caller's capture_exception instead of it passing silently as a revoke.+ response = requests.post(+ revoke_url,+ data=data,+ timeout=10,+ allow_redirects=False,+ )+ response.raise_for_status()++ def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:+ # Not all integrations have refresh tokens or expiries, so we just return False if we can't check++ refresh_token = self.integration.sensitive_config.get("refresh_token")+ expires_in = self.integration.config.get("expires_in")+ refreshed_at = self.integration.config.get("refreshed_at")++ if not refresh_token:+ return False++ if not expires_in and self.integration.kind in SALESFORCE_OAUTH_KINDS:+ # Salesforce tokens typically last 2-4 hours, we'll assume 1 hour (3600 seconds) to be conservative+ expires_in = 3600++ if not expires_in and self.integration.kind == "stripe":+ expires_in = 3600++ if not expires_in or not refreshed_at:+ return False++ # To be really safe we refresh if its half way through the expiry+ time_threshold = time_threshold or timedelta(seconds=expires_in / 2)++ return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()++ def _post_token_refresh(self, oauth_config: OauthConfig, client_id: str, client_secret: str) -> requests.Response:+ # Via the property, so a token that picked up an extra encryption layer is peeled back to+ # the real one instead of being posted to the provider as ciphertext.+ refresh_token = self.integration.refresh_token+ if refresh_token is None:+ # A grant with no refresh token at all is a caller error, not a provider rejection -+ # keep failing loudly rather than posting `None` and reading the 400 back as one.+ raise KeyError("refresh_token")+ kind = self.integration.kind++ # Reddit uses HTTP Basic Auth for token refresh+ if kind == "reddit-ads":+ return requests.post(+ oauth_config.token_url,+ auth=HTTPBasicAuth(client_id, client_secret),+ data={"refresh_token": refresh_token, "grant_type": "refresh_token"},+ # If I use a standard User-Agent, it will throw a 429 too many requests error+ headers={"User-Agent": "PostHog/1.0 by PostHogTeam"},+ timeout=10,+ )+ # Pinterest uses HTTP Basic Auth for token refresh+ elif kind == "pinterest-ads":+ return requests.post(+ oauth_config.token_url,+ auth=HTTPBasicAuth(client_id, client_secret),+ data={"refresh_token": refresh_token, "grant_type": "refresh_token"},+ timeout=10,+ )+ elif kind == "tiktok-ads":+ # Refresh against the Business API app we authorized against, using its app_id/secret and+ # JSON body (mirroring the token exchange). The open.tiktokapis.com/v2 endpoint with+ # client_key belongs to Login Kit — a different TikTok app family whose credentials this+ # integration never holds.+ return requests.post(+ "https://business-api.tiktok.com/open_api/v1.3/oauth2/refresh_token/",+ json={+ "app_id": client_id,+ "secret": client_secret,+ "refresh_token": refresh_token,+ "grant_type": "refresh_token",+ },+ headers={"Content-Type": "application/json"},+ timeout=10,+ )+ elif kind == "bing-ads":+ # Microsoft Azure AD requires scope parameter on token refresh+ return requests.post(+ oauth_config.token_url,+ data={+ "client_id": client_id,+ "client_secret": client_secret,+ "refresh_token": refresh_token,+ "grant_type": "refresh_token",+ "scope": oauth_config.scope,+ },+ timeout=10,+ )+ elif kind == "stripe":+ # Stripe Apps OAuth: secret as HTTP Basic username, no client_id/client_secret in body.+ return requests.post(+ oauth_config.token_url,+ auth=HTTPBasicAuth(client_secret, ""),+ data={"refresh_token": refresh_token, "grant_type": "refresh_token"},+ timeout=10,+ )+ else:+ token_url = oauth_config.token_url+ # Salesforce sandbox integrations are stored under the production kind (the sandbox+ # is only a token-exchange fallback in the OAuth callback), so the static prod+ # token URL would refuse a sandbox-issued refresh_token. Refresh at the org's+ # own instance host instead. Validate the host before sending client_secret ++ # refresh_token so a stray write to config can't exfiltrate the fleet-wide+ # Salesforce app secret; fall back to the hardcoded prod URL on rejection.+ if kind in SALESFORCE_OAUTH_KINDS:+ allowed_host = _salesforce_instance_host(self.integration.config.get("instance_url"))+ if allowed_host:+ token_url = f"{allowed_host}/services/oauth2/token"++ return requests.post(+ token_url,+ data={+ "client_id": client_id,+ "client_secret": client_secret,+ "refresh_token": refresh_token,+ "grant_type": "refresh_token",+ },+ timeout=10,+ allow_redirects=False,+ )++ def _parse_token_refresh_response(self, res: requests.Response) -> dict:+ try:+ config = res.json()+ except ValueError:+ # e.g. an HTML error page from a proxy/5xx - still a failed refresh, not an exception+ return {}+ # TikTok Business API nests the refreshed tokens under `data`, same as the token exchange.+ # Lift them to the top level so the generic access_token/refresh_token/expires_in handling reads them.+ if self.integration.kind == "tiktok-ads" and isinstance(config.get("data"), dict):+ config = {**config, **config["data"]}+ return config++ def _record_terminal_unreadable_secret(self) -> None:+ logger.error(+ "integration_refresh_secret_unreadable",+ integration_id=self.integration.pk,+ team_id=self.integration.team_id,+ kind=self.integration.kind,+ )+ self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILED+ attempt = refresh_tracking.record_refresh_failure(+ self.integration, reason=refresh_tracking.REFRESH_FAILURE_REASON_UNREADABLE_SECRET+ )+ refresh_tracking.oauth_refresh_counter.labels(+ kind=self.integration.kind,+ result="failed",+ reason=refresh_tracking.REFRESH_FAILURE_REASON_UNREADABLE_SECRET,+ attempt=attempt,+ ).inc()+ # `sensitive_config` is deliberately excluded: saving it would re-encrypt the ciphertext+ # this integration already can't read, adding another layer to the stored value.+ self.integration.save(update_fields=["errors", "config"])++ def refresh_access_token(self):+ """+ Refresh the access token for the integration if necessary+ """+ region = self.integration.config.get("region") if self.integration.kind == "posthog" else None+ oauth_config = self.oauth_config_for_kind(self.integration.kind, region)++ # Clear out previous token refreshing errors, as they'll be re-set below if another error occurs+ self.integration.errors = ""++ res: requests.Response | None = None+ config: dict = {}+ used_fallback = False+ try:+ res = self._post_token_refresh(oauth_config, oauth_config.client_id, oauth_config.client_secret)+ config = self._parse_token_refresh_response(res)+ except model.UndecryptedIntegrationSecretError:+ # The stored refresh token can't be read, so there is nothing to refresh with and no+ # later attempt can change that. Go terminal immediately: the sweep stops retrying,+ # and the UI shows the reconnect prompt.+ self._record_terminal_unreadable_secret()+ return+ except requests.RequestException as e:+ # A network error (timeout, connection reset) is a failed refresh, not a crash. Without+ # this the Celery sweep task errors out before recording the failure, so the backoff and+ # the TOKEN_REFRESH_FAILED reconnect state are never persisted.+ logger.warning(f"Network error on primary credentials for {self}", error=str(e))++ # A rotated or migrated OAuth app leaves users with refresh tokens only the previous+ # credentials can refresh. Retry with the fallback pair — including when the primary hit a+ # network error — so they keep working until they reconnect.+ if (+ res is None or res.status_code != 200 or not config.get("access_token")+ ) and oauth_config.client_secret_fallback:+ try:+ res = self._post_token_refresh(+ oauth_config,+ oauth_config.client_id_fallback or oauth_config.client_id,+ oauth_config.client_secret_fallback,+ )+ config = self._parse_token_refresh_response(res)+ used_fallback = True+ except requests.RequestException as e:+ logger.warning(f"Network error on fallback credentials for {self}", error=str(e))+ res = None+ config = {}++ if res is None or res.status_code != 200 or not config.get("access_token"):+ logger.warning(+ f"Failed to refresh token for {self}", response=res.text if res is not None else "network error"+ )+ self.integration.errors = common.ERROR_TOKEN_REFRESH_FAILED+ reason = (+ refresh_tracking.oauth_refresh_failure_reason(res.status_code, config, kind=self.integration.kind)+ if res is not None+ else refresh_tracking.REFRESH_FAILURE_REASON_NETWORK+ )+ attempt = refresh_tracking.record_refresh_failure(self.integration, reason=reason)+ refresh_tracking.oauth_refresh_counter.labels(+ kind=self.integration.kind, result="failed", reason=reason, attempt=attempt+ ).inc()+ # A failed refresh leaves `sensitive_config` untouched, so writing it back only risks+ # harm: `ignore_decrypt_errors` hands back raw ciphertext for a secret that couldn't be+ # decrypted, and saving re-encrypts it, permanently adding a layer to the stored value.+ self.integration.save(update_fields=["errors", "config"])+ return+ else:+ logger.info(f"Refreshed access token for {self}")+ refresh_tracking.record_refresh_success(self.integration)+ refresh_tracking.record_oauth_client_used(self.integration, used_fallback=used_fallback)+ self.integration.sensitive_config["access_token"] = config["access_token"]++ # Some providers (e.g. Atlassian/Jira) rotate refresh tokens — each+ # refresh response includes a new refresh_token and the old one is+ # invalidated. Always store the latest one to avoid "invalid refresh+ # token" errors on subsequent refreshes.+ if config.get("refresh_token"):+ self.integration.sensitive_config["refresh_token"] = config["refresh_token"]++ # Handle case where Salesforce/Stripe doesn't provide expires_in in refresh response+ expires_in = config.get("expires_in")+ if not expires_in and self.integration.kind in SALESFORCE_OAUTH_KINDS:+ expires_in = 3600+ if not expires_in and self.integration.kind == "stripe":+ expires_in = 3600++ self.integration.config["expires_in"] = expires_in+ self.integration.config["refreshed_at"] = int(time.time())+ reload_integrations_on_workers(self.integration.team_id, [self.integration.id])+ refresh_tracking.oauth_refresh_counter.labels(+ kind=self.integration.kind,+ result="success_fallback" if used_fallback else "success",+ reason="",+ attempt="",+ ).inc()++ self.integration.save()diff --git a/posthog/models/integration/postgres.py b/posthog/models/integration/postgres.pynew file mode 100644index 000000000000..8ff5222decbd--- /dev/null+++ b/posthog/models/integration/postgres.py@@ -0,0 +1,172 @@+"""Direct-connection PostgreSQL-protocol integrations (Postgres, Redshift over Postgres wire)."""++from typing import ClassVar, Literal, NamedTuple++from posthog.models.user import User++from . import common, model+++class Credentials(NamedTuple):+ """PostgreSQL credentials."""++ user: str+ password: str+++class Authority(NamedTuple):+ """PostgreSQL authority parameters."""++ host: str+ port: int+++MISSING_CERT_PATH = "/tmp/posthog/batch-exports/MISSING.crt"+++class TLS(NamedTuple):+ """PostgreSQL TLS parameters.++ NOTE: If a root CA file exists in the default '~/.postgresql/root.crt' path libpq+ treats `sslmode='require'` as `sslmode='verify-ca'`.++ **This is not what we want**++ If a user has not provided a root certificate (by setting `ssl_root_cert` to the+ cert's contents) or asked to use the system store explicitly (by setting+ `ssl_root_cert='system'`, in version >=16), then whatever is present in the default+ path should not be used.++ This could be a problem if, for example, another application or library or+ dependency bundled in the same container ships with a default cert.++ For this reason we require `ssl_root_cert` to not be `None` (as that would translate+ to the default path), and it defaults to an application-scoped path under `/tmp/`.+ """++ ssl_mode: Literal["prefer", "require", "verify-ca", "verify-full"]+ ssl_root_cert: str | Literal["system"] = MISSING_CERT_PATH+++_PostgreSQLServerKindType = Literal[+ model.Integration.IntegrationKind.AWS_REDSHIFT, model.Integration.IntegrationKind.POSTGRESQL+]+++class PostgreSQLServerIntegration:+ """Base class for any integration targetting a PostgreSQL-server."""++ integration: model.Integration+ integration_kind: ClassVar[_PostgreSQLServerKindType]++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != self.integration_kind:+ raise common.IntegrationError(+ "Integration provided is not the expected PostgreSQL server integration "+ f"(got kind='{integration.kind}', expected kind='{self.integration_kind}')"+ )++ self.integration = integration++ @classmethod+ def integration_from_config(+ cls,+ team_id: int,+ created_by: User | None = None,+ **config,+ ) -> model.Integration:+ from products.batch_exports.backend.api.batch_export import resolve_and_validate_host++ host = common._return_non_empty_str_from_config(config, "host", friendly_name="Host", kind=cls.integration_kind)+ try:+ resolve_and_validate_host(host)+ except ValueError:+ raise common.IntegrationError(f"Provided host '{host}' is not valid")++ port = config.get("port", None)+ try:+ port = int(port) # type: ignore+ except (TypeError, ValueError):+ raise common.IntegrationError("Port must be an integer")++ if port > 65535 or port < 0:+ raise common.IntegrationError(f"A valid port is required for an {cls.integration_kind} integration")++ user = common._return_non_empty_str_from_config(+ config,+ "user",+ friendly_name="A username",+ kind=cls.integration_kind,+ )+ password = common._return_non_empty_str_from_config(+ config,+ "password",+ friendly_name="A password",+ kind=cls.integration_kind,+ )++ ssl_mode = config.get("ssl_mode", "require")+ if ssl_mode not in ("require", "verify-ca", "verify-full"):+ raise common.IntegrationError("SSL mode must be one of: require, verify-ca, verify-full")++ ssl_root_cert = config.get("ssl_root_cert", None)+ if ssl_mode in ("verify-ca", "verify-full"):+ if not ssl_root_cert:+ raise common.IntegrationError(+ "SSL root certificate must be provided when verifying server certificates"+ )+ if not isinstance(ssl_root_cert, str):+ raise common.IntegrationError("SSL root certificate must be a string")++ integration, _ = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind=cls.integration_kind,+ integration_id=f"{team_id}-{host}-{port}-{user}",+ defaults={+ "config": {+ "host": host,+ "port": port,+ "user": user,+ "ssl_mode": ssl_mode,+ "ssl_root_cert": ssl_root_cert,+ },+ "sensitive_config": {+ "password": password,+ },+ "created_by": created_by,+ },+ )++ if integration.errors:+ integration.errors = ""+ integration.save()++ return integration++ def authority(self) -> Authority:+ return Authority(self.integration.config["host"], self.integration.config["port"])++ def credentials(self) -> Credentials:+ return Credentials(self.integration.config["user"], self.integration.sensitive_config["password"])++ def tls(self) -> TLS:+ if (ssl_root_cert := self.integration.config.get("ssl_root_cert", None)) is not None:+ return TLS(+ ssl_mode=self.integration.config["ssl_mode"],+ ssl_root_cert=ssl_root_cert,+ )+ else:+ # Preserve the default ssl_root_cert if one was not provided+ return TLS(ssl_mode=self.integration.config["ssl_mode"])+++class PostgreSQLIntegration(PostgreSQLServerIntegration):+ integration_kind: ClassVar[Literal[model.Integration.IntegrationKind.POSTGRESQL]] = (+ model.Integration.IntegrationKind.POSTGRESQL+ )+++class RedshiftIntegration(PostgreSQLServerIntegration):+ integration_kind: ClassVar[Literal[model.Integration.IntegrationKind.AWS_REDSHIFT]] = (+ model.Integration.IntegrationKind.AWS_REDSHIFT+ )diff --git a/posthog/models/integration/push.py b/posthog/models/integration/push.pynew file mode 100644index 000000000000..9797da3638bb--- /dev/null+++ b/posthog/models/integration/push.py@@ -0,0 +1,305 @@+"""Push-notification provider credentials (APNS, Firebase) and device-identity verification config."""++import time+from datetime import timedelta++from django.db import connection, transaction++import structlog+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ec+from google.auth.transport.requests import Request as GoogleRequest+from google.oauth2 import service_account+from rest_framework.exceptions import ValidationError++from posthog.models.user import User+from posthog.plugins.plugin_server_api import reload_integrations_on_workers++from . import model, refresh_tracking++logger = structlog.get_logger(__name__)+++# `config` key holding the push device-registration identity verification policy, read by the+# push subscriptions endpoint. Owned by the customer, not by the provider credentials.+CONFIG_PUSH_IDENTITY_VERIFICATION = "push_identity_verification"++PUSH_IDENTITY_VERIFICATION_MODES = ("disabled", "optional", "required")++# `config` key holding the customer's EC (P-256) public key(s) used to verify ES256 identity tokens.+# Public halves only — the private key stays on the customer's backend. At most two, so a key can be+# rotated (register the new one, cut over, drop the old) without a gap, mirroring the secret's+# primary/backup pair.+CONFIG_PUSH_IDENTITY_PUBLIC_KEYS = "push_identity_public_keys"++MAX_PUSH_IDENTITY_PUBLIC_KEYS = 2+++def _validate_push_identity_public_keys(public_keys: list[str]) -> None:+ if not isinstance(public_keys, list) or not all(isinstance(key, str) for key in public_keys):+ raise ValidationError("push_identity_public_keys must be a list of PEM-encoded public key strings")+ if len(public_keys) > MAX_PUSH_IDENTITY_PUBLIC_KEYS:+ raise ValidationError(f"push_identity_public_keys accepts at most {MAX_PUSH_IDENTITY_PUBLIC_KEYS} keys")+ for key in public_keys:+ try:+ loaded = serialization.load_pem_public_key(key.encode())+ except Exception:+ raise ValidationError("Each push_identity_public_key must be a valid PEM-encoded public key")+ # ES256 is defined over P-256 specifically. Accepting another curve (P-384/P-521) would store a+ # key the verifier can't use — jwt.decode raises InvalidKeyError against it — so reject it here.+ if not isinstance(loaded, ec.EllipticCurvePublicKey) or not isinstance(loaded.curve, ec.SECP256R1):+ raise ValidationError("push_identity_public_keys must be P-256 (secp256r1) EC public keys for ES256")+++def preserved_push_config(+ team_id: int,+ kind: str,+ integration_id: str,+ push_identity_verification: str | None,+ push_identity_public_keys: list[str] | None = None,+) -> dict:+ """Config keys a push credential upsert must carry over rather than drop.++ Connecting a push integration is an upsert, and the provider helpers rebuild `config` from the+ credentials they were handed. Anything they don't know about would be lost, so rotating a Firebase+ key or APNs .p8 would silently reset an enabled identity verification policy (its mode and its+ registered public keys) back to nothing, reopening the device takeover it exists to prevent. Carry+ each existing value forward unless the caller explicitly sets a new one; pass an empty list to+ clear the public keys.+ """+ if push_identity_verification is not None and push_identity_verification not in PUSH_IDENTITY_VERIFICATION_MODES:+ raise ValidationError(+ f"push_identity_verification must be one of: {', '.join(PUSH_IDENTITY_VERIFICATION_MODES)}"+ )+ if push_identity_public_keys is not None:+ _validate_push_identity_public_keys(push_identity_public_keys)++ # Serialize concurrent setup of this one integration for the rest of the caller's transaction.+ # `select_for_update` alone only locks a row that already exists, so two first-time setups could+ # both read "no policy" and the later write would clobber a policy the earlier one had just set.+ # An advisory lock covers the not-yet-created case too, keyed on the integration's identity so it+ # only serializes writers racing for the same integration. Every writer takes it, including one+ # setting explicit values — otherwise it could slip its row in between a preserving writer's read+ # and write, and have its policy dropped.+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [team_id, f"{kind}:{integration_id}"])++ existing = (+ model.Integration.objects.select_for_update()+ .filter(team_id=team_id, kind=kind, integration_id=integration_id)+ .only("config")+ .first()+ )+ existing_config = (existing.config or {}) if existing else {}+ result: dict = {}++ if push_identity_verification is not None:+ result[CONFIG_PUSH_IDENTITY_VERIFICATION] = push_identity_verification+ else:+ # Drop a stored mode we don't recognize rather than carrying it forward. The push endpoint+ # already treats an unknown mode as disabled, so preserving it would keep dead data alive, and+ # raising here would leave a corrupted integration unable to rotate its credentials.+ existing_mode = existing_config.get(CONFIG_PUSH_IDENTITY_VERIFICATION)+ if existing_mode in PUSH_IDENTITY_VERIFICATION_MODES:+ result[CONFIG_PUSH_IDENTITY_VERIFICATION] = existing_mode++ if push_identity_public_keys is not None:+ # A non-empty list sets/replaces; an empty list clears (omit the key entirely).+ if push_identity_public_keys:+ result[CONFIG_PUSH_IDENTITY_PUBLIC_KEYS] = push_identity_public_keys+ else:+ existing_keys = existing_config.get(CONFIG_PUSH_IDENTITY_PUBLIC_KEYS)+ if isinstance(existing_keys, list) and existing_keys:+ result[CONFIG_PUSH_IDENTITY_PUBLIC_KEYS] = existing_keys++ return result+++class FirebaseIntegration:+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "firebase":+ raise Exception("FirebaseIntegration init called with Integration with wrong 'kind'")+ self.integration = integration++ @classmethod+ def integration_from_key(+ cls,+ key_info: dict,+ team_id: int,+ created_by: User | None = None,+ push_identity_verification: str | None = None,+ push_identity_public_keys: list[str] | None = None,+ ) -> "model.Integration":+ scope = "https://www.googleapis.com/auth/firebase.messaging"++ try:+ credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])+ credentials.refresh(GoogleRequest())+ except Exception:+ raise ValidationError("Failed to authenticate with provided Firebase service account key")++ project_id = key_info.get("project_id")+ if not project_id:+ raise ValidationError("Service account key must contain a project_id")++ # Atomic so `preserved_push_config`'s row lock is held through the upsert that follows it.+ with transaction.atomic():+ integration, created = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind="firebase",+ integration_id=project_id,+ defaults={+ "config": {+ **preserved_push_config(+ team_id, "firebase", project_id, push_identity_verification, push_identity_public_keys+ ),+ "project_id": project_id,+ "expires_in": credentials.expiry.timestamp() - int(time.time()),+ "refreshed_at": int(time.time()),+ },+ "sensitive_config": {+ "key_info": key_info,+ "access_token": credentials.token,+ },+ "created_by": created_by,+ },+ )++ if integration.errors:+ integration.errors = ""+ integration.save()++ return integration++ @property+ def project_id(self) -> str:+ return self.integration.config.get("project_id", "")++ def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:+ expires_in = self.integration.config.get("expires_in")+ refreshed_at = self.integration.config.get("refreshed_at")+ if not expires_in or not refreshed_at:+ return False++ # To be really safe we refresh if its half way through the expiry+ time_threshold = time_threshold or timedelta(seconds=expires_in / 2)+ return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()++ def refresh_access_token(self) -> None:+ scope = "https://www.googleapis.com/auth/firebase.messaging"+ key_info = self.integration.sensitive_config.get("key_info", {})++ credentials = service_account.Credentials.from_service_account_info(key_info, scopes=[scope])++ try:+ credentials.refresh(GoogleRequest())+ except Exception:+ refresh_tracking.record_refresh_failure(self.integration)+ self.integration.save(update_fields=["config"])+ raise ValidationError("Failed to authenticate with provided Firebase service account key")++ refresh_tracking.record_refresh_success(self.integration)+ self.integration.config["expires_in"] = credentials.expiry.timestamp() - int(time.time())+ self.integration.config["refreshed_at"] = int(time.time())+ self.integration.sensitive_config["access_token"] = credentials.token+ self.integration.save()+ reload_integrations_on_workers(self.integration.team_id, [self.integration.id])++ logger.info(f"Refreshed access token for FirebaseIntegration {self.integration.id}")++ def get_access_token(self) -> str:+ if self.access_token_expired():+ self.refresh_access_token()+ return self.integration.sensitive_config.get("access_token", "")+++class ApplePushIntegration:+ """+ Integration for Apple Push Notification Service (APNS).++ config stores:+ - team_id: Apple Developer Team ID+ - bundle_id: App bundle identifier (e.g. com.example.app)+ - key_id: The Key ID for the .p8 signing key+ - environment: "production" or "sandbox" (defaults to "production")++ sensitive_config stores:+ - signing_key: The .p8 signing key contents+ """++ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "apns":+ raise Exception("ApplePushIntegration init called with Integration with wrong 'kind'")+ self.integration = integration++ @classmethod+ def integration_from_key(+ cls,+ signing_key: str,+ key_id: str,+ team_id_apple: str,+ bundle_id: str,+ team_id: int,+ created_by: User | None = None,+ environment: str = "production",+ push_identity_verification: str | None = None,+ push_identity_public_keys: list[str] | None = None,+ ) -> "model.Integration":+ if not all([signing_key, key_id, team_id_apple, bundle_id]):+ raise ValidationError("All APNS fields are required: signing_key, key_id, team_id_apple, bundle_id")++ if environment not in ("production", "sandbox"):+ raise ValidationError("APNS environment must be 'production' or 'sandbox'")++ integration_id = f"{team_id_apple}.{bundle_id}"+ # Atomic so `preserved_push_config`'s row lock is held through the upsert that follows it.+ with transaction.atomic():+ integration, created = model.Integration.objects.update_or_create(+ team_id=team_id,+ kind="apns",+ integration_id=integration_id,+ defaults={+ "config": {+ **preserved_push_config(+ team_id, "apns", integration_id, push_identity_verification, push_identity_public_keys+ ),+ "team_id": team_id_apple,+ "bundle_id": bundle_id,+ "key_id": key_id,+ "environment": environment,+ },+ "sensitive_config": {+ "signing_key": signing_key,+ },+ },+ )++ if created and created_by is not None:+ integration.created_by = created_by+ integration.save(update_fields=["created_by"])++ if integration.errors:+ integration.errors = ""+ integration.save(update_fields=["errors"])++ return integration++ @property+ def team_id_apple(self) -> str:+ return self.integration.config.get("team_id", "")++ @property+ def bundle_id(self) -> str:+ return self.integration.config.get("bundle_id", "")++ @property+ def key_id(self) -> str:+ return self.integration.config.get("key_id", "")++ @property+ def signing_key(self) -> str:+ return self.integration.sensitive_config.get("signing_key", "")diff --git a/posthog/models/integration/refresh_tracking.py b/posthog/models/integration/refresh_tracking.pynew file mode 100644index 000000000000..c02065bfe7a1--- /dev/null+++ b/posthog/models/integration/refresh_tracking.py@@ -0,0 +1,190 @@+"""OAuth refresh bookkeeping shared across every OAuth-backed integration kind."""++import time+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from . import model+++import structlog+from prometheus_client import Counter++from . import common++logger = structlog.get_logger(__name__)+++oauth_refresh_counter = Counter(+ "integration_oauth_refresh",+ "Number of times an oauth refresh has been attempted",+ labelnames=["kind", "result", "reason", "attempt"],+)++# Terminal rows are skipped by the sweep and stop emitting failure metrics, so a gradual fleet+# die-off would otherwise be invisible. Incremented once per row at the transition; a rising+# rate means connections are permanently breaking (e.g. a provider mass-revoking grants).+oauth_refresh_terminal_counter = Counter(+ "integration_oauth_refresh_went_terminal",+ "OAuth integrations whose refresh went terminal (unbroken invalid_grant streak)",+ labelnames=["kind"],+)++# Consecutive-failure backoff for the every-minute refresh sweep (posthog/tasks/integrations.py).+# Without it, permanently dead integrations (revoked grants, deleted consumers) are retried every+# minute forever, hammering providers and drowning the failure metric in a noise floor that+# masks real fleet-wide breakage.+REFRESH_BACKOFF_BASE_SECONDS = 120++REFRESH_BACKOFF_MAX_SECONDS = 3600++REFRESH_TERMINAL_FAILURE_COUNT = 5++# `config` key flagging a grant that only the legacy fallback credentials can refresh.+CONFIG_LEGACY_OAUTH_CLIENT = "oauth_uses_legacy_client"++# Values for the counter's `reason` label, bucketed from the OAuth error response.+REFRESH_FAILURE_REASON_INVALID_GRANT = "invalid_grant"++REFRESH_FAILURE_REASON_INVALID_CLIENT = "invalid_client"++REFRESH_FAILURE_REASON_HTTP_5XX = "http_5xx"++REFRESH_FAILURE_REASON_NETWORK = "network"++REFRESH_FAILURE_REASON_RATE_LIMITED = "rate_limited"++REFRESH_FAILURE_REASON_OTHER = "other"++# Not a provider response: the stored refresh token itself can't be decrypted, so no request was+# made. Terminal on the first occurrence, since no later attempt can make the secret readable.+REFRESH_FAILURE_REASON_UNREADABLE_SECRET = "unreadable_secret"+++def oauth_refresh_failure_reason(status_code: int, body: dict, kind: str | None = None) -> str:+ error = body.get("error")+ if error == REFRESH_FAILURE_REASON_INVALID_GRANT:+ return REFRESH_FAILURE_REASON_INVALID_GRANT+ if error == REFRESH_FAILURE_REASON_INVALID_CLIENT:+ return REFRESH_FAILURE_REASON_INVALID_CLIENT+ # Reddit reports a dead grant as `{"message": "Bad Request", "error": 400}` with no OAuth+ # error code. Our refresh request shape is fixed and succeeds fleet-wide, so a 400 on this+ # endpoint means the grant, not the request - match that exact shape for reddit only.+ if kind == "reddit-ads" and status_code == 400 and error == 400:+ return REFRESH_FAILURE_REASON_INVALID_GRANT+ # HubSpot reports a grant whose portal (hub) was deleted or disconnected as+ # `{"status": "BAD_HUB", "error": "access_denied", ...}` - no `invalid_grant` code, so+ # without this mapping the row is retried forever instead of going terminal. Its+ # `BAD_REFRESH_TOKEN` responses do carry `"error": "invalid_grant"` and need no special case.+ if kind == "hubspot" and status_code < 500 and body.get("status") == "BAD_HUB":+ return REFRESH_FAILURE_REASON_INVALID_GRANT+ # Meta Graph nests its error as an object (`{"error": {"code": 190, ...}}`) and never+ # sends the `invalid_grant` string. Code 190 means the access token is dead (password+ # change, checkpoint, expiry, revocation). Without this mapping, a revoked Meta token+ # classifies as `other`. Meta rate limits use codes 4, 17, and 32, which do not match.+ if kind in ("meta-ads", "instagram") and status_code < 500 and isinstance(error, dict) and error.get("code") == 190:+ return REFRESH_FAILURE_REASON_INVALID_GRANT+ # Transient throttling, not a credential problem: the backoff cap synchronises failed+ # integrations into retry herds that can trip a provider's per-second limit and take+ # healthy refreshes in the same second down with them.+ if status_code == 429:+ return REFRESH_FAILURE_REASON_RATE_LIMITED+ if status_code >= 500:+ return REFRESH_FAILURE_REASON_HTTP_5XX+ return REFRESH_FAILURE_REASON_OTHER+++def record_refresh_failure(integration: "model.Integration", *, reason: str = REFRESH_FAILURE_REASON_OTHER) -> str:+ """Track a consecutive refresh failure on the integration's config; caller saves.++ Schedules the next attempt with capped exponential backoff. `invalid_grant` means the grant+ itself is dead and only a customer re-auth can fix it, so after an unbroken streak of them the+ integration goes terminal and the sweep stops retrying entirely. The streak is tracked+ separately from the total failure count and resets on any other reason, so one transient+ invalid_grant amid e.g. a 5xx outage can't brick the integration. `unreadable_secret` goes+ terminal on the first occurrence - we never even reached the provider, and retrying can't make+ an undecryptable token readable. Other reasons (invalid_client, 5xx, network, rate_limited)+ never go terminal - a platform-side credential fix must let the fleet self-recover.++ Returns "first"/"retry" for the metric's `attempt` label - a spike in first failures means+ connections are newly breaking, regardless of retry noise.+ """+ count = int(integration.config.get("refresh_failure_count") or 0)+ attempt = "first" if count == 0 else "retry"+ count += 1+ integration.config["refresh_failure_count"] = count+ integration.config["refresh_next_attempt_at"] = int(time.time()) + min(+ REFRESH_BACKOFF_BASE_SECONDS * 2 ** (count - 1), REFRESH_BACKOFF_MAX_SECONDS+ )+ if reason == REFRESH_FAILURE_REASON_UNREADABLE_SECRET:+ integration.config.pop("refresh_invalid_grant_count", None)+ if not integration.config.get("refresh_terminal"):+ integration.config["refresh_terminal"] = True+ oauth_refresh_terminal_counter.labels(kind=integration.kind).inc()+ elif reason == REFRESH_FAILURE_REASON_INVALID_GRANT:+ grant_streak = int(integration.config.get("refresh_invalid_grant_count") or 0) + 1+ integration.config["refresh_invalid_grant_count"] = grant_streak+ # Guarded so on-demand refreshes (which bypass the backoff) can't re-count a dead row+ if grant_streak >= REFRESH_TERMINAL_FAILURE_COUNT and not integration.config.get("refresh_terminal"):+ integration.config["refresh_terminal"] = True+ oauth_refresh_terminal_counter.labels(kind=integration.kind).inc()+ else:+ integration.config.pop("refresh_invalid_grant_count", None)+ return attempt+++def record_refresh_success(integration: "model.Integration") -> None:+ for key in ("refresh_failure_count", "refresh_invalid_grant_count", "refresh_next_attempt_at", "refresh_terminal"):+ integration.config.pop(key, None)+++def record_oauth_client_used(integration: "model.Integration", *, used_fallback: bool) -> None:+ """Track whether the grant still depends on the legacy (fallback) OAuth credentials.++ A refresh token minted by a since-migrated app can only be refreshed by that app's+ credentials, so a successful fallback refresh identifies exactly the connections that break+ when the legacy app is retired. The flag rides on `config`, which the API exposes, so the+ product can tell those teams to reconnect. Reconnecting mints a grant on the primary+ credentials and replaces `config` wholesale, which clears the flag.+ """+ if used_fallback:+ integration.config[CONFIG_LEGACY_OAUTH_CLIENT] = True+ else:+ integration.config.pop(CONFIG_LEGACY_OAUTH_CLIENT, None)+++def issuing_oauth_client_ids(integration: "model.Integration") -> list[str]:+ """The OAuth client ids the connection was established with. Empty when that can't be read.++ OIDC puts the client id in the id_token's `aud` claim, and we keep the id_token from the+ authorization exchange - refreshes only overwrite the access and refresh tokens. So this reads+ the app the customer actually connected through, which is knowable for connections that already+ exist, without waiting for a refresh to reveal it.++ `aud` is a string or a list of strings per RFC 7519, so both shapes are normalized here.+ Callers should test membership rather than assume a single value: treating a list-shaped+ audience as unreadable would silently drop those connections from the reconnect campaign.+ """+ id_token = integration.sensitive_config.get("id_token")+ if not id_token:+ return []+ try:+ claims = common._decode_jwt_payload(id_token) or {}+ except Exception:+ logger.warning("Failed to decode id_token", integration_id=integration.id, kind=integration.kind)+ return []+ audience = claims.get("aud")+ if isinstance(audience, str):+ return [audience]+ if isinstance(audience, list):+ return [entry for entry in audience if isinstance(entry, str)]+ return []+++def refresh_backoff_active(integration: "model.Integration") -> bool:+ """Whether the refresh sweep should skip this integration. Reconnecting resets the state+ (the OAuth callback replaces `config` wholesale), and on-demand API refreshes bypass this."""+ if integration.config.get("refresh_terminal"):+ return True+ next_attempt_at = integration.config.get("refresh_next_attempt_at")+ return bool(next_attempt_at) and time.time() < next_attempt_atdiff --git a/posthog/models/integration/slack.py b/posthog/models/integration/slack.pynew file mode 100644index 000000000000..6cd464fbbd21--- /dev/null+++ b/posthog/models/integration/slack.py@@ -0,0 +1,227 @@+"""Slack integration: connected-workspace API calls and request-signature verification."""++import hmac+import time+import hashlib+from collections.abc import Iterable+from datetime import timedelta+from typing import TYPE_CHECKING, Literal, Optional++from posthog.dataclasses import frozen++if TYPE_CHECKING:+ import aiohttp+ from slack_sdk.web.async_client import AsyncWebClient++from django.http import HttpRequest++from opentelemetry import trace+from rest_framework.request import Request+from slack_sdk.errors import SlackApiError++from posthog.cache_utils import cache_for+from posthog.egress.slack.client import SlackWebClient as WebClient+from posthog.models.instance_setting import get_instance_settings++from . import model++tracer = trace.get_tracer(__name__)+++PRIVATE_CHANNEL_WITHOUT_ACCESS = "PRIVATE_CHANNEL_WITHOUT_ACCESS"+++class SlackIntegrationError(Exception):+ pass+++SLACK_INTEGRATION_KINDS: tuple[str, ...] = ("slack",)++SLACK_CHANNELS_PAGE_SIZE = 1000++SLACK_CHANNELS_MAX_PAGES = 10+++class SlackIntegration:+ integration: model.Integration++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind not in SLACK_INTEGRATION_KINDS:+ raise Exception("SlackIntegration init called with Integration with wrong 'kind'")++ self.integration = integration++ @property+ def client(self) -> WebClient:+ return WebClient(+ self.integration.sensitive_config["access_token"],+ source="integration",+ workspace_id=self.integration.integration_id,+ app_id="posthog",+ )++ def async_client(self, session: Optional["aiohttp.ClientSession"] = None) -> "AsyncWebClient":+ # slack_sdk's async client imports aiohttp at module scope; this is a models module,+ # so a top-level import would put aiohttp on the django.setup() path+ from posthog.egress.slack.async_client import SlackAsyncWebClient # noqa: PLC0415++ return SlackAsyncWebClient(+ self.integration.sensitive_config["access_token"],+ source="integration",+ workspace_id=self.integration.integration_id,+ app_id="posthog",+ session=session,+ )++ def granted_scopes(self) -> frozenset[str]:+ """OAuth scopes Slack granted this install, stored on Integration.config["scope"]."""+ raw = self.integration.config.get("scope") or ""+ return frozenset(scope.strip() for scope in raw.split(",") if scope.strip())++ def missing_scopes(self, required: Iterable[str]) -> frozenset[str]:+ return frozenset(required) - self.granted_scopes()++ def list_channels(self, should_include_private_channels: bool, authed_user: str) -> list[dict]:+ # NOTE: Annoyingly the Slack API has no search so we have to load all channels...+ # We load public and private channels separately as when mixed, the Slack API pagination is buggy+ public_channels = self._list_channels_by_type("public_channel")+ private_channels = self._list_channels_by_type("private_channel", should_include_private_channels, authed_user)+ channels = public_channels + private_channels++ return sorted(channels, key=lambda x: x["name"])++ def get_channel_by_id(+ self, channel_id: str, should_include_private_channels: bool = False, authed_user: str | None = None+ ) -> dict | None:+ try:+ response = self.client.conversations_info(channel=channel_id, include_num_members=True)+ channel = response["channel"]+ members_response = self.client.conversations_members(channel=channel_id, limit=channel["num_members"] + 1)+ isMember = authed_user in members_response["members"]++ if not isMember:+ return None++ isPrivateWithoutAccess = channel["is_private"] and not should_include_private_channels++ return {+ "id": channel["id"],+ "name": PRIVATE_CHANNEL_WITHOUT_ACCESS if isPrivateWithoutAccess else channel["name"],+ "is_private": channel["is_private"],+ "is_member": channel.get("is_member", True),+ "is_ext_shared": channel["is_ext_shared"],+ "is_private_without_access": isPrivateWithoutAccess,+ }+ except SlackApiError as e:+ if e.response["error"] == "channel_not_found":+ return None+ raise++ def _list_channels_by_type(+ self,+ type: Literal["public_channel", "private_channel"],+ should_include_private_channels: bool = False,+ authed_user: str | None = None,+ ) -> list[dict]:+ max_page = SLACK_CHANNELS_MAX_PAGES+ channels = []+ cursor = None++ while max_page > 0:+ max_page -= 1+ if type == "public_channel":+ res = self.client.conversations_list(+ exclude_archived=True, types=type, limit=SLACK_CHANNELS_PAGE_SIZE, cursor=cursor+ )+ else:+ res = self.client.users_conversations(+ exclude_archived=True,+ types=type,+ limit=SLACK_CHANNELS_PAGE_SIZE,+ cursor=cursor,+ user=authed_user,+ )++ for channel in res["channels"]:+ if channel["is_private"] and not should_include_private_channels:+ channel["name"] = PRIVATE_CHANNEL_WITHOUT_ACCESS+ channel["is_private_without_access"] = True++ channels.extend(res["channels"])+ cursor = res["response_metadata"]["next_cursor"]+ if not cursor:+ break++ return channels++ @classmethod+ def validate_request(cls, request: HttpRequest | Request):+ slack_config = cls.slack_config()+ validate_slack_request(request, slack_config["SLACK_APP_SIGNING_SECRET"])++ @classmethod+ @cache_for(timedelta(minutes=5))+ def slack_config(cls):+ # Span only fires on cache miss (cache_for is process-local in-memory).+ # If preflight.slack_config_main is fast in production traces, this span+ # will be absent; if it appears, it tells us the DB hit was slow.+ with tracer.start_as_current_span("slack_integration.slack_config_db"):+ config = get_instance_settings(+ [+ "SLACK_APP_CLIENT_ID",+ "SLACK_APP_CLIENT_SECRET",+ "SLACK_APP_SIGNING_SECRET",+ ]+ )++ return config+++@frozen+class SlackRequestSignature:+ signature: str+ timestamp: str+++def sign_slack_request(body: bytes, signing_secret: str) -> SlackRequestSignature:+ """Sign a body with the Slack HMAC-SHA256 scheme.++ Used by both prod (PostHog→PostHog cross-region calls that reuse the Slack signing scheme)+ and tests. The matching verifier is `validate_slack_request` below.+ """+ ts = str(int(time.time()))+ sig_basestring = f"v0:{ts}:{body.decode('utf-8')}".encode()+ signature = "v0=" + hmac.new(signing_secret.encode("utf-8"), sig_basestring, digestmod=hashlib.sha256).hexdigest()+ return SlackRequestSignature(signature=signature, timestamp=ts)+++def validate_slack_request(request: HttpRequest | Request, signing_secret: str) -> None:+ """+ Validate a Slack request using HMAC-SHA256 signature verification.+ Based on https://api.slack.com/authentication/verifying-requests-from-slack+ """+ slack_signature = request.headers.get("X-SLACK-SIGNATURE")+ slack_time = request.headers.get("X-SLACK-REQUEST-TIMESTAMP")++ if not signing_secret or not slack_signature or not slack_time:+ raise SlackIntegrationError("Invalid")++ try:+ if time.time() - float(slack_time) > 300:+ raise SlackIntegrationError("Expired")+ except ValueError:+ raise SlackIntegrationError("Invalid")++ sig_basestring = f"v0:{slack_time}:{request.body.decode('utf-8')}"++ my_signature = (+ "v0="+ + hmac.new(+ signing_secret.encode("utf-8"),+ sig_basestring.encode("utf-8"),+ digestmod=hashlib.sha256,+ ).hexdigest()+ )++ if not hmac.compare_digest(my_signature, slack_signature):+ raise SlackIntegrationError("Invalid")diff --git a/posthog/models/integration/snowflake.py b/posthog/models/integration/snowflake.pynew file mode 100644index 000000000000..927f2b467ade--- /dev/null+++ b/posthog/models/integration/snowflake.py@@ -0,0 +1,148 @@+"""Snowflake integration."""++import re++from django.db import transaction++from posthog.models.user import User+from posthog.models.utils import IntegrityError++from . import model+++class SnowflakeIntegrationError(Exception):+ """Error raised when a Snowflake integration is not valid."""++ pass+++# A Snowflake account identifier: an alphanumeric first character followed by alphanumerics, dots,+# hyphens and underscores.+_SNOWFLAKE_ACCOUNT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")+++class SnowflakeIntegration:+ """A Snowflake integration storing reusable Snowflake credentials.++ Holds the account, user, and authentication material (a password, or a key-pair) needed to+ connect to Snowflake. Database, warehouse, schema, table name and role stay on the batch export+ destination config, so one credential can be reused across many exports.++ Supports both of Snowflake's authentication types:+ - "password": `password` in sensitive_config.+ - "keypair": `private_key` (PEM) plus optional `private_key_passphrase` in sensitive_config.++ Rather than using an auto-generated ID (e.g. '{account}-{user}-{auth_type}'), we use a+ user-provided name, similarly to how we do for S3 integrations. The benefits of this approach+ are:+ - a user can create multiple integrations for the same account, allowing for credential rotation+ - we don't overwrite an existing integration if creating an integration for the same account,+ so existing exports can continue to use the old credentials+ - a human-readable name in the UI+ """++ integration: model.Integration+ account: str+ user: str+ authentication_type: str++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != model.Integration.IntegrationKind.SNOWFLAKE:+ raise SnowflakeIntegrationError(+ f"Integration provided is not a Snowflake integration (got kind='{integration.kind}')"+ )+ self.integration = integration+ try:+ self.account = integration.config["account"]+ self.user = integration.config["user"]+ self.authentication_type = integration.config["authentication_type"]+ except KeyError as e:+ raise SnowflakeIntegrationError(f"Snowflake integration is not valid: {str(e)} missing")++ @property+ def password(self) -> str | None:+ return self.integration.sensitive_config.get("password")++ @property+ def private_key(self) -> str | None:+ return self.integration.sensitive_config.get("private_key")++ @property+ def private_key_passphrase(self) -> str | None:+ return self.integration.sensitive_config.get("private_key_passphrase")++ @staticmethod+ def validate_account(account: str) -> None:+ """Validate the Snowflake account identifier format.++ Snowflake has no user-supplied host: the connector derives the host from the account, always+ on a fixed Snowflake-owned domain suffix, so there is no SSRF surface as there is for+ Databricks or S3-compatible. We validate the identifier's shape to reject URLs and arbitrary+ hosts (for example, anything with a scheme, `/`, `@`, `:`, `#`, or whitespace).+ """+ if not _SNOWFLAKE_ACCOUNT_RE.fullmatch(account):+ raise SnowflakeIntegrationError(+ f"Snowflake integration is not valid: invalid account identifier '{account}'"+ )++ @classmethod+ def integration_from_config(+ cls,+ team_id: int,+ name: str,+ account: str,+ user: str,+ authentication_type: str,+ password: str | None = None,+ private_key: str | None = None,+ private_key_passphrase: str | None = None,+ created_by: User | None = None,+ ) -> model.Integration:+ if not (name and account and user):+ raise SnowflakeIntegrationError("Name, account, and user must be provided")+ if not all(isinstance(value, str) for value in (name, account, user, authentication_type)):+ raise SnowflakeIntegrationError("Name, account, user, and authentication type must be strings")+ if not all(+ value is None or isinstance(value, str) for value in (password, private_key, private_key_passphrase)+ ):+ raise SnowflakeIntegrationError("Password, private key, and private key passphrase must be strings")++ cls.validate_account(account)++ sensitive_config: dict[str, str] = {}+ if authentication_type == "password":+ if not password:+ raise SnowflakeIntegrationError("Password is required for password authentication")+ sensitive_config["password"] = password+ elif authentication_type == "keypair":+ if not private_key:+ raise SnowflakeIntegrationError("Private key is required for key-pair authentication")+ sensitive_config["private_key"] = private_key+ if private_key_passphrase:+ sensitive_config["private_key_passphrase"] = private_key_passphrase+ else:+ raise SnowflakeIntegrationError(f"Invalid authentication type: {authentication_type}")++ # `name` is the unencrypted, frontend-visible identifier — never a credential. Unlike most+ # integrations, it is a free-form user-supplied name rather than one derived from the+ # connection, so we create rather than upsert: re-using a name is a 400, not a silent+ # overwrite of an unrelated credential set.+ try:+ # Savepoint so the unique-constraint IntegrityError aborts only this INSERT, not the+ # surrounding transaction.+ with transaction.atomic():+ return model.Integration.objects.create(+ team_id=team_id,+ kind=model.Integration.IntegrationKind.SNOWFLAKE,+ integration_id=name,+ config={+ "name": name,+ "account": account,+ "user": user,+ "authentication_type": authentication_type,+ },+ sensitive_config=sensitive_config,+ created_by=created_by,+ )+ except IntegrityError:+ raise SnowflakeIntegrationError(f"An integration named '{name}' already exists")diff --git a/posthog/models/integration/stripe.py b/posthog/models/integration/stripe.pynew file mode 100644index 000000000000..de5de5195b1f--- /dev/null+++ b/posthog/models/integration/stripe.py@@ -0,0 +1,183 @@+"""Stripe App integration: writing PostHog OAuth secrets into Stripe's Secret Store."""++from datetime import timedelta+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from stripe import StripeClient++from django.conf import settings+from django.utils import timezone++import structlog++from posthog.exceptions_capture import capture_exception+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken+from posthog.models.user import User+from posthog.models.utils import generate_random_oauth_access_token, generate_random_oauth_refresh_token+from posthog.utils import get_instance_region++from . import model, oauth++logger = structlog.get_logger(__name__)+++class StripeIntegration:+ integration: model.Integration++ # Every endpoint services/stripe-app/src/posthog/client.ts calls, and nothing else.+ # This token is readable by every member of the customer's Stripe account, so anything+ # granted here is granted to all of them. Read-only by design; do not add a write scope.+ SCOPES: str = " ".join(+ [+ "customer_journey:read",+ "experiment:read",+ "feature_flag:read",+ "insight:read",+ "query:read",+ ]+ )++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "stripe":+ raise ValueError(f"Expected stripe integration, got {integration.kind}")+ self.integration = integration++ def _stripe_client(self) -> "StripeClient | None":+ # Returns None when the required env vars are missing so callers can skip Stripe+ # API calls without raising past their per-secret error handling.+ from stripe import StripeClient # noqa: PLC0415++ try:+ oauth_config = oauth.OauthIntegration.oauth_config_for_kind("stripe")+ except NotImplementedError as e:+ capture_exception(+ e,+ {+ "stripe_user_id": self.integration.integration_id,+ },+ )+ return None+ return StripeClient(oauth_config.client_secret)++ def write_posthog_secrets(self, team_id: int, created_by: "User") -> None:+ """Write PostHog OAuth tokens to Stripe's Secret Store so the Stripe App can call PostHog APIs."""++ oauth_app = self._get_posthog_oauth_app()+ if not oauth_app:+ logger.warning("PostHog OAuth app not found, cannot write secrets to Stripe")+ return++ access_token_value = generate_random_oauth_access_token(None)+ access_token = OAuthAccessToken.objects.create(+ application=oauth_app,+ token=access_token_value,+ user=created_by,+ expires=timezone.now() + timedelta(days=14),+ scope=self.SCOPES,+ scoped_teams=[team_id],+ )++ refresh_token_value = generate_random_oauth_refresh_token(None)+ OAuthRefreshToken.objects.create(+ application=oauth_app,+ token=refresh_token_value,+ user=created_by,+ access_token=access_token,+ scoped_teams=[team_id],+ )++ stripe_user_id = self.integration.integration_id+ if not stripe_user_id:+ raise ValueError("Missing stripe_user_id on integration")++ region = get_instance_region() or "us"++ secrets = {+ "posthog_region": region.lower(),+ "posthog_access_token": access_token_value,+ "posthog_refresh_token": refresh_token_value,+ "posthog_project_id": str(team_id),+ "posthog_oauth_client_id": oauth_app.client_id,+ }++ client = self._stripe_client()+ if client is None:+ return++ for name, payload in secrets.items():+ try:+ client.apps.secrets.create(+ params={+ "scope": {"type": "account"},+ "name": name,+ "payload": payload,+ },+ options={"stripe_account": stripe_user_id},+ )+ except Exception as e:+ capture_exception(+ e,+ {+ "secret_name": name,+ "stripe_user_id": stripe_user_id,+ },+ )++ def clear_posthog_secrets(self) -> None:+ """Best-effort clear of PostHog secrets from Stripe and revoke local OAuth tokens."""+ stripe_user_id = self.integration.integration_id+ if not stripe_user_id:+ raise ValueError("Missing stripe_user_id on integration")++ client = self._stripe_client()+ if client is None:+ self._destroy_posthog_oauth_tokens()+ return++ for name in (+ "posthog_region",+ "posthog_access_token",+ "posthog_refresh_token",+ "posthog_project_id",+ "posthog_oauth_client_id",+ ):+ try:+ client.apps.secrets.delete_where(+ params={+ "scope": {"type": "account"},+ "name": name,+ },+ options={"stripe_account": stripe_user_id},+ )+ except Exception as e:+ capture_exception(+ e,+ {+ "secret_name": name,+ "stripe_user_id": stripe_user_id,+ },+ )++ self._destroy_posthog_oauth_tokens()++ def _destroy_posthog_oauth_tokens(self) -> None:+ """Delete the local OAuth access and refresh tokens created for this Stripe integration."""+ oauth_app = self._get_posthog_oauth_app()+ if not oauth_app:+ return++ team_id = self.integration.team_id+ access_tokens = OAuthAccessToken.objects.filter(+ application=oauth_app,+ scoped_teams__contains=[team_id],+ )+ # Delete refresh tokens first since their FK to access_token is SET_NULL+ OAuthRefreshToken.objects.filter(access_token__in=access_tokens).delete()+ access_tokens.delete()++ def _get_posthog_oauth_app(self):+ if settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID:+ return OAuthApplication.objects.filter(client_id=settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID).first()++ return Nonediff --git a/posthog/models/integration/twilio.py b/posthog/models/integration/twilio.pynew file mode 100644index 000000000000..69387026df38--- /dev/null+++ b/posthog/models/integration/twilio.py@@ -0,0 +1,55 @@+"""Twilio integration."""++from rest_framework.exceptions import ValidationError++from products.workflows.backend.providers import TwilioProvider++from . import model+++class TwilioIntegration:+ integration: model.Integration+ twilio_provider: TwilioProvider++ def __init__(self, integration: model.Integration) -> None:+ if integration.kind != "twilio":+ raise Exception("TwilioIntegration init called with Integration with wrong 'kind'")+ self.integration = integration+ self.twilio_provider = TwilioProvider(+ account_sid=self.integration.config["account_sid"],+ auth_token=self.integration.sensitive_config["auth_token"],+ )++ def list_twilio_phone_numbers(self) -> list[dict]:+ twilio_phone_numbers = self.twilio_provider.get_phone_numbers()++ if not twilio_phone_numbers:+ raise Exception(f"There was an internal error")++ return twilio_phone_numbers++ def integration_from_keys(self) -> model.Integration:+ account_info = self.twilio_provider.get_account_info()++ if not account_info.get("sid"):+ raise ValidationError({"account_info": "Failed to get account info"})++ integration, created = model.Integration.objects.update_or_create(+ team_id=self.integration.team_id,+ kind="twilio",+ integration_id=account_info["sid"],+ defaults={+ "config": {+ "account_sid": account_info["sid"],+ },+ "sensitive_config": {+ "auth_token": self.integration.sensitive_config["auth_token"],+ },+ "created_by": self.integration.created_by,+ },+ )+ if integration.errors:+ integration.errors = ""+ integration.save()++ return integrationdiff --git a/posthog/models/test/integration/__init__.py b/posthog/models/test/integration/__init__.pynew file mode 100644index 000000000000..215d59ffb308--- /dev/null+++ b/posthog/models/test/integration/__init__.py@@ -0,0 +1,4 @@+# Package marker, not optional: posthog/models/test/ is a package, so without this file+# pytest names these modules by bare basename (test_github, test_jira, ...) and they+# collide with same-named test files elsewhere in the repo, knocking those out of+# collection in any session that spans both trees.diff --git a/posthog/models/test/integration/test_aws.py b/posthog/models/test/integration/test_aws.pynew file mode 100644index 000000000000..36563c8bddec--- /dev/null+++ b/posthog/models/test/integration/test_aws.py@@ -0,0 +1,170 @@+"""Tests for AWS role/credential-based integrations."""++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.test import override_settings++from posthog.models.integration import (+ AWSS3Integration,+ DuplicateNameError,+ Integration,+ IntegrationError,+ S3CompatibleIntegration,+ validate_aws_credentials,+)+++class TestAWSS3IntegrationModel(BaseTest):+ @patch("posthog.models.integration.aws.validate_aws_credentials", return_value="123456789012")+ def test_integration_from_config_with_valid_config(self, mock_validate):+ integration = AWSS3Integration.integration_from_config(+ team_id=self.team.pk,+ name="prod-aws",+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret",+ created_by=self.user,+ )+ assert integration.team == self.team+ assert integration.created_by == self.user+ assert integration.kind == Integration.IntegrationKind.AWS_S3+ # The identifier is the user-supplied name, never a credential.+ assert integration.integration_id == "prod-aws"+ # The account id resolved from STS is stored in non-sensitive config.+ assert integration.config == {"name": "prod-aws", "aws_account_id": "123456789012"}+ assert integration.sensitive_config == {+ "aws_access_key_id": "AKIAEXAMPLE",+ "aws_secret_access_key": "secret",+ }+ # display_name surfaces AWS account so users can tell integrations apart.+ assert integration.display_name == "prod-aws (AWS account 123456789012)"+ assert AWSS3Integration(integration).aws_account_id == "123456789012"++ def test_integration_from_config_requires_name(self):+ with pytest.raises(IntegrationError, match="A name is required"):+ AWSS3Integration.integration_from_config(+ team_id=self.team.pk,+ name="",+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret",+ )++ @patch("posthog.models.integration.aws.validate_aws_credentials", return_value="123456789012")+ def test_integration_from_config_rejects_duplicate_name(self, mock_validate):+ AWSS3Integration.integration_from_config(+ team_id=self.team.pk,+ name="prod-aws",+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret",+ )+ with pytest.raises(DuplicateNameError, match="An integration named 'prod-aws' already exists"):+ AWSS3Integration.integration_from_config(+ team_id=self.team.pk,+ name="prod-aws",+ aws_access_key_id="AKIAOTHER",+ aws_secret_access_key="other-secret",+ )+ assert Integration.objects.filter(team=self.team, integration_id="prod-aws").count() == 1++ @patch("boto3.client")+ def test_validate_aws_credentials_returns_account_id(self, mock_boto_client):+ mock_boto_client.return_value.get_caller_identity.return_value = {"Account": "123456789012"}+ assert validate_aws_credentials("key", "secret") == "123456789012"++ @patch("boto3.client")+ def test_validate_aws_credentials_raises_on_invalid_credentials(self, mock_boto_client):+ from botocore.exceptions import ClientError++ mock_boto_client.return_value.get_caller_identity.side_effect = ClientError(+ {"Error": {"Code": "InvalidClientTokenId", "Message": "The security token is invalid."}},+ "GetCallerIdentity",+ )+ with pytest.raises(IntegrationError, match="AWS credentials are not valid: The security token is invalid."):+ validate_aws_credentials("key", "secret")++ def test_wrapping_wrong_kind_raises(self):+ integration = Integration.objects.create(+ team=self.team, kind=Integration.IntegrationKind.S3_COMPATIBLE, integration_id="x"+ )+ with pytest.raises(IntegrationError, match="is not the expected AWS integration"):+ AWSS3Integration(integration)++ def test_wrapping_missing_credentials_raises(self):+ integration = Integration.objects.create(+ team=self.team, kind=Integration.IntegrationKind.AWS_S3, integration_id="x", sensitive_config={}+ )+ with pytest.raises(IntegrationError, match="missing"):+ AWSS3Integration(integration)+++class TestS3CompatibleIntegrationModel(BaseTest):+ def test_integration_from_config_with_valid_config(self):+ integration = S3CompatibleIntegration.integration_from_config(+ team_id=self.team.pk,+ name="my-r2",+ endpoint_url="https://account.r2.cloudflarestorage.com",+ aws_access_key_id="key",+ aws_secret_access_key="secret",+ created_by=self.user,+ )+ assert integration.kind == Integration.IntegrationKind.S3_COMPATIBLE+ assert integration.integration_id == "my-r2"+ # endpoint_url is non-sensitive and lives in config.+ assert integration.config == {"name": "my-r2", "endpoint_url": "https://account.r2.cloudflarestorage.com"}+ assert integration.sensitive_config == {"aws_access_key_id": "key", "aws_secret_access_key": "secret"}+ wrapped = S3CompatibleIntegration(integration)+ assert wrapped.endpoint_url == "https://account.r2.cloudflarestorage.com"+ # display_name surfaces auth type and endpoint so users can tell integrations apart.+ assert integration.display_name == "my-r2 (access key, https://account.r2.cloudflarestorage.com)"++ def test_integration_from_config_requires_endpoint_url(self):+ with pytest.raises(IntegrationError, match="Endpoint URL is required"):+ S3CompatibleIntegration.integration_from_config(+ team_id=self.team.pk,+ name="my-r2",+ endpoint_url="",+ aws_access_key_id="key",+ aws_secret_access_key="secret",+ )++ def test_integration_from_config_rejects_duplicate_name(self):+ S3CompatibleIntegration.integration_from_config(+ team_id=self.team.pk,+ name="my-r2",+ endpoint_url="https://account.r2.cloudflarestorage.com",+ aws_access_key_id="key",+ aws_secret_access_key="secret",+ )+ with pytest.raises(DuplicateNameError, match="An integration named 'my-r2' already exists"):+ S3CompatibleIntegration.integration_from_config(+ team_id=self.team.pk,+ name="my-r2",+ endpoint_url="https://other.r2.cloudflarestorage.com",+ aws_access_key_id="key2",+ aws_secret_access_key="secret2",+ )+ assert Integration.objects.filter(team=self.team, integration_id="my-r2").count() == 1++ # is_url_allowed bypasses validation in DEBUG/test mode, so force the production path to exercise rejection.+ @override_settings(FORCE_URL_VALIDATION=True)+ def test_integration_from_config_rejects_internal_endpoint(self):+ with pytest.raises(IntegrationError, match="Invalid endpoint URL"):+ S3CompatibleIntegration.integration_from_config(+ team_id=self.team.pk,+ name="my-r2",+ endpoint_url="https://169.254.169.254",+ aws_access_key_id="key",+ aws_secret_access_key="secret",+ )++ def test_wrapping_missing_endpoint_url_raises(self):+ integration = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.S3_COMPATIBLE,+ integration_id="x",+ config={"name": "x"},+ sensitive_config={"aws_access_key_id": "key", "aws_secret_access_key": "secret"},+ )+ with pytest.raises(IntegrationError, match="missing required field: 'endpoint_url'"):+ S3CompatibleIntegration(integration)diff --git a/posthog/models/test/integration/test_databricks.py b/posthog/models/test/integration/test_databricks.pynew file mode 100644index 000000000000..47ebffb2116f--- /dev/null+++ b/posthog/models/test/integration/test_databricks.py@@ -0,0 +1,36 @@+"""Tests for the Databricks integration."""++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from posthog.models.integration import DatabricksIntegration, DatabricksIntegrationError+++class TestDatabricksIntegrationModel(BaseTest):+ @patch("posthog.models.integration.databricks.is_url_allowed", return_value=(True, None))+ def test_integration_from_config_with_valid_config(self, mock_is_url_allowed):+ integration = DatabricksIntegration.integration_from_config(+ team_id=self.team.pk,+ server_hostname="databricks.com",+ client_id="client_id",+ client_secret="client_secret",+ created_by=self.user,+ )+ assert integration.team == self.team+ assert integration.created_by == self.user+ assert integration.config == {"server_hostname": "databricks.com"}+ assert integration.sensitive_config == {"client_id": "client_id", "client_secret": "client_secret"}++ @patch("posthog.models.integration.databricks.is_url_allowed", return_value=(False, "Could not resolve host"))+ def test_integration_from_config_with_invalid_server_hostname(self, mock_is_url_allowed):+ with pytest.raises(+ DatabricksIntegrationError, match="Databricks integration error: could not validate hostname 'invalid'"+ ):+ DatabricksIntegration.integration_from_config(+ team_id=self.team.pk,+ server_hostname="invalid",+ client_id="client_id",+ client_secret="client_secret",+ created_by=self.user,+ )diff --git a/posthog/models/test/integration/test_email.py b/posthog/models/test/integration/test_email.pynew file mode 100644index 000000000000..38680b953d1f--- /dev/null+++ b/posthog/models/test/integration/test_email.py@@ -0,0 +1,342 @@+"""Tests for the native email-sending integration."""++import pytest+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from disposable_email_domains import blocklist as disposable_email_domains_list+from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from posthog.models.integration import EmailIntegration, Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.workflows.backend.providers import SESProvider+++class TestEmailIntegrationDomainValidation(BaseTest):+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_successful_domain_creation_ses(self, mock_create_email_domain):+ mock_create_email_domain.return_value = {"status": "success", "domain": "successdomain.com"}+ config = {"email": "[email protected]", "name": "Test User", "provider": "ses"}+ integration = EmailIntegration.create_native_integration(+ config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user+ )+ assert integration.team == self.team+ assert integration.config["email"] == "[email protected]"+ assert integration.config["provider"] == "ses"+ assert integration.config["domain"] == "successdomain.com"+ assert integration.config["name"] == "Test User"+ assert integration.config["verified"] is False++ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ @patch("products.workflows.backend.providers.SESProvider.verify_email_domain")+ def test_duplicate_domain_in_another_organization(self, mock_create_email_domain, mock_verify_email_domain):+ mock_create_email_domain.return_value = {"status": "success", "domain": "successdomain.com"}+ mock_verify_email_domain.return_value = {"status": "verified", "domain": "example.com"}+ # Create an integration with a domain in another organization+ other_org = Organization.objects.create(name="other org")+ other_team = Team.objects.create(organization=other_org, name="other team")+ config = {"email": "[email protected]", "name": "Test User"}+ EmailIntegration.create_native_integration(+ config, team_id=other_team.id, organization_id=str(other_org.id), created_by=self.user+ )++ # Attempt to create the same domain in a different organization should raise ValidationError+ with pytest.raises(ValidationError) as exc:+ EmailIntegration.create_native_integration(+ config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user+ )+ assert "already exists in another organization" in str(exc.value)++ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_duplicate_domain_in_same_organization_allowed(self, mock_create_email_domain):+ mock_create_email_domain.return_value = {"status": "success", "domain": "example.com"}+ # Create an integration with a domain in one team+ other_team = Team.objects.create(organization=self.organization, name="other team")+ config = {"email": "[email protected]", "name": "Test User"}+ integration1 = EmailIntegration.create_native_integration(+ config, team_id=other_team.id, organization_id=str(self.organization.id), created_by=self.user+ )++ # Creating the same domain in a different team in the same organization should succeed+ integration2 = EmailIntegration.create_native_integration(+ config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user+ )++ assert integration1.config["domain"] == "example.com"+ assert integration2.config["domain"] == "example.com"+ assert integration1.team_id == other_team.id+ assert integration2.team_id == self.team.id++ def test_unsupported_email_domain(self):+ # Test with a free email domain+ config = {"email": "[email protected]", "name": "Test User"}++ with pytest.raises(ValidationError) as exc:+ EmailIntegration.create_native_integration(+ config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user+ )+ assert "not supported" in str(exc.value)++ # Test with a disposable email domain+ disposable_domain = next(iter(disposable_email_domains_list))+ config = {"email": f"user@{disposable_domain}", "name": "Test User"}++ with pytest.raises(ValidationError) as exc:+ EmailIntegration.create_native_integration(+ config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user+ )+ assert disposable_domain in str(exc.value)+ assert "not supported" in str(exc.value)++ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_cross_org_guard_blocks_mixed_case_domain(self, mock_create_email_domain):+ mock_create_email_domain.return_value = {"status": "success", "domain": "example.com"}+ other_org = Organization.objects.create(name="other org")+ other_team = Team.objects.create(organization=other_org, name="other team")+ EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Owner"},+ team_id=other_team.id,+ organization_id=str(other_org.id),+ created_by=self.user,+ )++ with pytest.raises(ValidationError) as exc:+ EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Attacker"},+ team_id=self.team.id,+ organization_id=str(self.organization.id),+ created_by=self.user,+ )+ assert "already exists in another organization" in str(exc.value)++ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_stored_domain_is_lowercased(self, mock_create_email_domain):+ mock_create_email_domain.return_value = {"status": "success", "domain": "successdomain.com"}+ integration = EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Test User", "provider": "ses"},+ team_id=self.team.id,+ organization_id=str(self.organization.id),+ created_by=self.user,+ )+ assert integration.config["domain"] == "successdomain.com"++ @parameterized.expand(+ [+ ("gmail_titlecase", "[email protected]"),+ ("gmail_uppercase", "[email protected]"),+ ("gmail_mixed", "[email protected]"),+ ("yahoo_titlecase", "[email protected]"),+ ("hotmail_uppercase", "[email protected]"),+ ]+ )+ def test_free_email_block_is_case_insensitive(self, _name, email):+ config = {"email": email, "name": "Test User"}+ with pytest.raises(ValidationError) as exc:+ EmailIntegration.create_native_integration(+ config,+ team_id=self.team.id,+ organization_id=str(self.organization.id),+ created_by=self.user,+ )+ assert "not supported" in str(exc.value)+++class TestEmailIntegrationCrossTenantStaleVerification(BaseTest):+ def _build_ses_provider(self, tenants_for_domain: dict[str, list[str]] | None = None) -> SESProvider:+ patcher = patch("products.workflows.backend.providers.ses.boto3.client")+ patcher.start()+ self.addCleanup(patcher.stop)++ provider = SESProvider()+ provider.ses_client = MagicMock()+ provider.ses_v2_client = MagicMock()+ provider.sts_client = MagicMock()+ provider.sts_client.get_caller_identity.return_value = {"Account": "123456789012"}++ provider.ses_client.verify_domain_identity.return_value = {"VerificationToken": "tok"}+ provider.ses_client.verify_domain_dkim.return_value = {"DkimTokens": ["t1", "t2", "t3"]}+ provider.ses_client.set_identity_mail_from_domain.return_value = {}++ def _list_resource_tenants(ResourceArn: str) -> dict:+ domain = ResourceArn.split("/")[-1]+ return {"ResourceTenants": [{"TenantName": t} for t in (tenants_for_domain or {}).get(domain, [])]}++ provider.ses_v2_client.list_resource_tenants.side_effect = _list_resource_tenants+ return provider++ def _set_global_ses_success(self, provider, domain: str) -> None:+ provider.ses_client.get_identity_verification_attributes.return_value = {+ "VerificationAttributes": {domain: {"VerificationStatus": "Success"}}+ }+ provider.ses_client.get_identity_dkim_attributes.return_value = {+ "DkimAttributes": {domain: {"DkimVerificationStatus": "Success"}}+ }+ provider.ses_client.get_identity_mail_from_domain_attributes.return_value = {+ "MailFromDomainAttributes": {domain: {"MailFromDomainStatus": "Success"}}+ }++ @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")+ def test_verify_email_domain_requires_team_tenant_association(self, mock_resolver_cls):+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})+ self._set_global_ses_success(provider, "partner.com")+ dmarc_answer = MagicMock()+ dmarc_answer.strings = [b"v=DMARC1; p=none;"]+ mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]++ result_team_a = provider.verify_email_domain("partner.com", "feedback", team_id=1)+ result_team_b = provider.verify_email_domain("partner.com", "feedback", team_id=999)++ assert result_team_a["status"] == "success"+ assert result_team_b["status"] == "pending"++ @patch("products.workflows.backend.providers.SESProvider.delete_identity")+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_destroy_email_integration_deletes_ses_identity(self, mock_create_email_domain, mock_delete_identity):+ from posthog.api.integration import IntegrationViewSet++ mock_create_email_domain.return_value = {"status": "success"}+ integration = EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Owner"},+ team_id=self.team.id,+ organization_id=str(self.organization.id),+ created_by=self.user,+ )++ with self.captureOnCommitCallbacks(execute=True):+ IntegrationViewSet().perform_destroy(integration)++ mock_delete_identity.assert_called_once_with("partner.com")+ assert not Integration.objects.filter(pk=integration.pk).exists()++ @patch("products.workflows.backend.providers.SESProvider.delete_identity")+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_destroy_email_integration_skips_ses_delete_when_sibling_exists(+ self, mock_create_email_domain, mock_delete_identity+ ):+ from posthog.api.integration import IntegrationViewSet++ mock_create_email_domain.return_value = {"status": "success"}+ sibling_team = Team.objects.create(organization=self.organization, name="sibling team")+ EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Sibling"},+ team_id=sibling_team.id,+ organization_id=str(self.organization.id),+ created_by=self.user,+ )+ integration = EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Owner"},+ team_id=self.team.id,+ organization_id=str(self.organization.id),+ created_by=self.user,+ )++ with self.captureOnCommitCallbacks(execute=True):+ IntegrationViewSet().perform_destroy(integration)++ assert mock_delete_identity.call_count == 0++ def test_create_email_domain_rejects_foreign_tenant_owner(self):+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})++ with pytest.raises(Exception) as exc:+ provider.create_email_domain("partner.com", "feedback", team_id=999, org_team_ids=[999])+ assert "already associated with another organization" in str(exc.value)++ def test_create_email_domain_allows_sibling_team_in_same_org(self):+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})++ provider.create_email_domain(+ "partner.com",+ "feedback",+ team_id=2,+ org_team_ids=[1, 2, 3, 4, 5],+ )++ @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")+ def test_takeover_after_owner_deletes_integration_is_blocked(self, mock_create_email_domain, mock_resolver_cls):+ from posthog.api.integration import IntegrationViewSet++ mock_create_email_domain.return_value = {"status": "success"}+ dmarc_answer = MagicMock()+ dmarc_answer.strings = [b"v=DMARC1; p=none;"]+ mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]++ org_a = Organization.objects.create(name="org a")+ team_a = Team.objects.create(organization=org_a, name="team a")+ org_b = Organization.objects.create(name="org b")+ team_b = Team.objects.create(organization=org_b, name="team b")++ integration_a = EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Owner A"},+ team_id=team_a.id,+ organization_id=str(org_a.id),+ created_by=self.user,+ )+ with patch("products.workflows.backend.providers.SESProvider.delete_identity") as mock_delete:+ with self.captureOnCommitCallbacks(execute=True):+ IntegrationViewSet().perform_destroy(integration_a)+ mock_delete.assert_called_once_with("partner.com")++ integration_b = EmailIntegration.create_native_integration(+ {"email": "[email protected]", "name": "Attacker B"},+ team_id=team_b.id,+ organization_id=str(org_b.id),+ created_by=self.user,+ )++ provider = self._build_ses_provider(tenants_for_domain={"partner.com": []})+ self._set_global_ses_success(provider, "partner.com")++ email_b = EmailIntegration(integration_b)+ with patch.object(type(email_b), "ses_provider", new=provider):+ result = email_b.verify()++ assert result["status"] == "pending"+ integration_b.refresh_from_db()+ assert integration_b.config.get("verified") is False++ def test_aws_account_id_is_cached_per_provider(self):+ provider = self._build_ses_provider()+ provider.sts_client.get_caller_identity.reset_mock()++ for _ in range(5):+ provider._identity_arn("partner.com")+ provider._identity_arn("other.com")++ assert provider.sts_client.get_caller_identity.call_count == 1+++class TestEmailIntegrationSESCleanupOnDelete(BaseTest):+ def _create_email_integration(self, email: str, team_id: int, organization_id: str) -> Integration:+ with patch("products.workflows.backend.providers.SESProvider.create_email_domain"):+ return EmailIntegration.create_native_integration(+ {"email": email, "name": "Test"},+ team_id=team_id,+ organization_id=organization_id,+ created_by=self.user,+ )++ @patch("products.workflows.backend.providers.SESProvider.delete_identity")+ def test_team_cascade_delete_cleans_up_ses_identity(self, mock_delete_identity):+ team = Team.objects.create(organization=self.organization, name="doomed team")+ self._create_email_integration("[email protected]", team.id, str(self.organization.id))++ with self.captureOnCommitCallbacks(execute=True):+ team.delete()++ mock_delete_identity.assert_called_once_with("partner.com")++ @patch("products.workflows.backend.providers.SESProvider.delete_identity")+ def test_cascade_delete_skips_ses_cleanup_while_domain_still_in_use(self, mock_delete_identity):+ team = Team.objects.create(organization=self.organization, name="doomed team")+ self._create_email_integration("[email protected]", team.id, str(self.organization.id))+ self._create_email_integration("[email protected]", self.team.id, str(self.organization.id))++ with self.captureOnCommitCallbacks(execute=True):+ team.delete()++ mock_delete_identity.assert_not_called()diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pynew file mode 100644index 000000000000..483e771df26e--- /dev/null+++ b/posthog/models/test/integration/test_github.py@@ -0,0 +1,2102 @@+"""Tests for the GitHub App integration."""++import time+from datetime import UTC, datetime, timedelta+from typing import Optional++import pytest+from freezegun import freeze_time+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, call, patch++from django.core.cache import cache+from django.test import SimpleTestCase+from django.utils import timezone++import requests+from parameterized import parameterized+from prometheus_client import REGISTRY++from posthog.egress.github.transport import (+ GitHubEgressBudgetExhausted,+ GitHubRateLimitError,+ raise_if_github_rate_limited,+)+from posthog.egress.limiter.policies import Priority+from posthog.models.github_integration_base import (+ GITHUB_BRANCH_CACHE_TTL_SECONDS,+ GITHUB_REPOSITORY_CACHE_TTL_SECONDS,+ GitHubIntegrationBase,+)+from posthog.models.integration import (+ GitHubIntegration,+ GitHubIntegrationError,+ Integration,+ invalidate_github_repository_caches_for_installation,+)+++class TestExtractFailingChecks(SimpleTestCase):+ @parameterized.expand(+ [+ ("failure", "FAILURE", True),+ ("timed_out", "TIMED_OUT", True),+ ("action_required", "ACTION_REQUIRED", True),+ ("startup_failure", "STARTUP_FAILURE", True),+ ("cancelled", "CANCELLED", True),+ ("stale", "STALE", True),+ ("success", "SUCCESS", False),+ ("neutral", "NEUTRAL", False),+ ("skipped", "SKIPPED", False),+ ]+ )+ def test_check_run_is_reported_only_when_its_conclusion_blocks_merge(self, _name, conclusion, expected_reported):+ rollup = {+ "contexts": {+ "nodes": [+ {+ "__typename": "CheckRun",+ "conclusion": conclusion,+ "name": "unit tests",+ "checkSuite": {"workflowRun": {"workflow": {"name": "CI"}}},+ "detailsUrl": "https://ci/1",+ }+ ]+ }+ }++ failing = GitHubIntegrationBase._extract_failing_checks(rollup)++ assert (failing == [{"key": "CI/unit tests", "details_url": "https://ci/1"}]) is expected_reported+++class TestGitHubIntegrationModel(BaseTest):+ def setUp(self):+ super().setUp()+ cache.clear()++ def create_integration(self, config: Optional[dict] = None, sensitive_config: Optional[dict] = None) -> Integration:+ _config = {"expires_at": 3600}+ _sensitive_config = {"token": "REFRESH"}+ _config.update(config or {})+ _sensitive_config.update(sensitive_config or {})++ # Mirror production (integration_from_installation_id): the model integration_id field holds the+ # GitHub App installation id, which is what egress telemetry keys its gauges on.+ return Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id=(config or {}).get("installation_id"),+ config=_config,+ sensitive_config=_sensitive_config,+ )++ def mock_github_client_request(+ self,+ status_code=201,+ token="ACCESS_TOKEN",+ repository_selection="all",+ expires_in_hours=1,+ error_text=None,+ permissions=None,+ ):+ def _client_request(endpoint, method="GET"):+ mock_response = MagicMock()+ if method == "POST":+ mock_response.status_code = status_code+ dt = datetime.now(UTC) + timedelta(hours=expires_in_hours)+ iso_time = dt.replace(tzinfo=None).isoformat(timespec="seconds") + "Z"++ if status_code == 201:+ mock_response.json.return_value = {+ "token": token,+ "repository_selection": repository_selection,+ "expires_at": iso_time,+ **({"permissions": permissions} if permissions is not None else {}),+ }+ else:+ mock_response.text = error_text or "error"+ mock_response.json.return_value = {}+ else:+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "account": {"type": "Organization", "login": "PostHog"},+ **({"permissions": permissions} if permissions is not None else {}),+ }+ return mock_response++ return _client_request++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_mint_scoped_installation_token_marks_uninstalled_installation(self, mock_client_request):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "expires_in": 3600, "refreshed_at": 1704110400},+ {"access_token": "FULL_TOKEN"},+ )+ mock_response = MagicMock(status_code=404, text="Not Found")+ mock_response.json.return_value = {"message": "Not Found"}+ mock_client_request.return_value = mock_response++ github = GitHubIntegration(integration)+ with pytest.raises(GitHubIntegrationError):+ github.mint_scoped_installation_token({"contents": "read"})++ # Without the permanently-gone marker, every scheduled run re-mints a dead installation+ # forever — the marker is what lets callers skip it until the customer reconnects.+ integration.refresh_from_db()+ assert GitHubIntegration(integration).installation_unavailable() is True+ assert "expires_in" not in integration.config++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_mint_scoped_installation_token_downscopes_without_persisting(self, mock_client_request):+ integration = self.create_integration({"installation_id": "INSTALL"}, {"access_token": "FULL_TOKEN"})+ mock_response = MagicMock(status_code=201)+ mock_response.json.return_value = {"token": "SCOPED_TOKEN", "expires_at": "2024-01-01T13:00:00Z"}+ mock_client_request.return_value = mock_response++ token = GitHubIntegration(integration).mint_scoped_installation_token({"contents": "read"})++ assert token == "SCOPED_TOKEN"+ # Without the permissions body the mint returns a FULL-permission token — a silent+ # privilege escalation for every read-only sandbox.+ assert mock_client_request.call_args.kwargs["json_body"] == {"permissions": {"contents": "read"}}+ # The scoped token must never clobber the shared full-permission credential other flows read.+ integration.refresh_from_db()+ assert integration.sensitive_config == {"token": "REFRESH", "access_token": "FULL_TOKEN"}++ def test_get_diff_compares_branch_tips(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200, text="diff --git a b")+ with patch.object(github, "api_request", return_value=mock_response) as mock_get:+ result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")+ assert result == {+ "success": True,+ "diff": "diff --git a b",+ "truncated": False,+ }+ mock_get.assert_called_once()+ assert "/compare/master...feature/foo" in mock_get.call_args.args[1]++ def test_get_diff_pins_to_shas_when_given(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200, text="diff --git a b")+ with patch.object(github, "api_request", return_value=mock_response) as mock_get:+ result = github.get_diff(+ "PostHog/posthog",+ target_branch="feature/foo",+ base_branch="master",+ target_sha="abc123f",+ base_sha="def456a",+ )+ assert result["success"] is True+ assert "/compare/def456a...abc123f" in mock_get.call_args.args[1]++ def test_get_diff_maps_upstream_error(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=404, text="Not Found")+ with patch.object(github, "api_request", return_value=mock_response):+ result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")+ assert result == {"success": False, "error": "Not Found", "status_code": 404}++ def test_get_diff_handles_request_exception(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ with patch.object(github, "api_request", side_effect=GitHubIntegrationError("network error")):+ result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")+ assert result["success"] is False+ assert result["status_code"] == 502++ def _github_for_org(self) -> GitHubIntegration:+ integration = self.create_integration(+ config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}+ )+ return GitHubIntegration(integration)++ @staticmethod+ def _git_data_api_request(*, ref_status: int = 201):+ calls: list[tuple[str, str, Optional[dict]]] = []++ def _request(method, path, **kwargs):+ calls.append((method, path, kwargs.get("json_body")))+ if "/git/ref/heads/" in path and method == "GET":+ return MagicMock(status_code=200, **{"json.return_value": {"object": {"sha": "base-sha"}}})+ if "/git/commits/" in path:+ return MagicMock(status_code=200, **{"json.return_value": {"tree": {"sha": "base-tree"}}})+ if path.endswith("/git/trees"):+ return MagicMock(status_code=201, **{"json.return_value": {"sha": "new-tree"}})+ if path.endswith("/git/commits"):+ return MagicMock(status_code=201, **{"json.return_value": {"sha": "new-commit"}})+ if path.endswith("/git/refs"):+ return MagicMock(status_code=ref_status, text="Reference already exists")+ if "/git/refs/heads/" in path and method == "PATCH":+ return MagicMock(status_code=200)+ raise AssertionError(f"unexpected request {method} {path}")++ return _request, calls++ def test_commit_files_to_branch_writes_every_file_in_one_commit(self):+ github = self._github_for_org()+ request, calls = self._git_data_api_request()++ with patch.object(github, "api_request", side_effect=request):+ result = github.commit_files_to_branch(+ "community-skills", "community-skill/x", "main", {"a.md": "A", "b/c.md": "C"}, "msg"+ )++ assert result["success"] is True+ assert result["commit_sha"] == "new-commit"+ tree_body = next(body for _, path, body in calls if path.endswith("/git/trees"))+ assert {entry["path"] for entry in tree_body["tree"]} == {"a.md", "b/c.md"}+ assert tree_body["base_tree"] == "base-tree"+ # The branch reference is written last, so a failure earlier leaves no branch in the repo.+ assert calls[-1][1].endswith("/git/refs")++ def test_commit_files_to_branch_replaces_a_directory_rather_than_merging_into_it(self):+ github = self._github_for_org()+ request, calls = self._git_data_api_request()++ with patch.object(github, "api_request", side_effect=request):+ result = github.commit_files_to_branch(+ "community-skills",+ "community-skill/x",+ "main",+ {"skills/x/SKILL.md": "S", "skills/x/refs/g.md": "G", "README.md": "R"},+ "msg",+ replace_directory="skills/x",+ )++ assert result["success"] is True+ subtree_body, tree_body = (body for _, path, body in calls if path.endswith("/git/trees"))+ # No base_tree on the subtree, so it holds these files and nothing else. That is what makes a+ # path the caller dropped disappear instead of surviving from the base.+ assert "base_tree" not in subtree_body+ assert {entry["path"] for entry in subtree_body["tree"]} == {"SKILL.md", "refs/g.md"}+ assert tree_body["base_tree"] == "base-tree"+ assert {(entry["path"], entry["type"]) for entry in tree_body["tree"]} == {+ ("skills/x", "tree"),+ ("README.md", "blob"),+ }++ def test_commit_files_to_branch_force_updates_an_existing_branch(self):+ github = self._github_for_org()+ request, calls = self._git_data_api_request(ref_status=422)++ with patch.object(github, "api_request", side_effect=request):+ result = github.commit_files_to_branch(+ "community-skills", "community-skill/x", "main", {"a.md": "A"}, "msg"+ )++ assert result["success"] is True+ assert result["created_branch"] is False+ method, path, body = calls[-1]+ assert (method, path) == ("PATCH", "/repos/PostHog/community-skills/git/refs/heads/community-skill/x")+ assert body == {"sha": "new-commit", "force": True}++ @parameterized.expand([("deleted", 204), ("already gone", 404)])+ def test_delete_branch_treats_a_missing_branch_as_deleted(self, _name: str, status_code: int):+ github = self._github_for_org()+ with patch.object(github, "api_request", return_value=MagicMock(status_code=status_code)):+ assert github.delete_branch("community-skills", "community-skill/x")["success"] is True++ @parameterized.expand([("the ref is gone", 404, True), ("the ref is still there", 200, False)])+ def test_delete_branch_reads_the_ref_back_after_an_ambiguous_422(self, _name: str, recheck: int, deleted: bool):+ github = self._github_for_org()++ def _request(method, path, **kwargs):+ if method == "DELETE":+ return MagicMock(status_code=422, text="Validation failed")+ return MagicMock(status_code=recheck, **{"json.return_value": {"object": {"sha": "abc"}}})++ with patch.object(github, "api_request", side_effect=_request):+ result = github.delete_branch("community-skills", "community-skill/x")++ # A 422 the caller reads as success is a branch left on a public repo with nobody warned.+ assert result["success"] is deleted++ @parameterized.expand([("the expected commit", "mine", True), ("someone else's commit", "theirs", False)])+ def test_delete_branch_with_an_expected_sha_only_deletes_its_own_commit(+ self, _name: str, head_sha: str, deleted: bool+ ):+ github = self._github_for_org()+ methods: list[str] = []++ def _request(method, path, **kwargs):+ methods.append(method)+ if method == "GET":+ return MagicMock(status_code=200, **{"json.return_value": {"object": {"sha": head_sha}}})+ return MagicMock(status_code=204)++ with patch.object(github, "api_request", side_effect=_request):+ result = github.delete_branch("community-skills", "community-skill/x", expected_sha="mine")++ assert result["success"] is True+ assert ("DELETE" in methods) is deleted++ def test_get_open_pull_request_for_head_returns_number_and_url(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200)+ mock_response.json.return_value = [+ {+ "number": 7,+ "html_url": "https://github.com/PostHog/posthog/pull/7",+ "base": {"ref": "master"},+ }+ ]+ with patch.object(github, "_installation_authenticated_get", return_value=mock_response):+ assert github.get_open_pull_request_for_head("PostHog/posthog", "posthog-code/fix") == {+ "number": 7,+ "url": "https://github.com/PostHog/posthog/pull/7",+ "base": "master",+ }++ def test_get_open_pr_base_for_head_returns_base_ref_of_open_pr(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200)+ mock_response.json.return_value = [+ {+ "number": 7,+ "html_url": "https://github.com/PostHog/posthog/pull/7",+ "base": {"ref": "master"},+ "head": {"ref": "posthog-code/fix"},+ }+ ]+ with patch.object(github, "_installation_authenticated_get", return_value=mock_response) as mock_get:+ result = github.get_open_pr_base_for_head("PostHog/posthog", "posthog-code/fix")+ assert result == "master"+ # Query is scoped to open PRs whose head is the branch, in the repo owner's namespace.+ assert mock_get.call_args.kwargs["params"] == {+ "head": "PostHog:posthog-code/fix",+ "state": "open",+ "per_page": 1,+ }++ def test_get_open_pr_base_for_head_returns_none_when_no_open_pr(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200)+ mock_response.json.return_value = []+ with patch.object(github, "_installation_authenticated_get", return_value=mock_response):+ assert github.get_open_pr_base_for_head("PostHog/posthog", "master") is None++ def test_get_open_pr_base_for_head_returns_none_on_error(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ with patch.object(github, "_installation_authenticated_get", return_value=None):+ assert github.get_open_pr_base_for_head("PostHog/posthog", "posthog-code/fix") is None++ def test_get_pull_request_comments_merges_conversation_and_review_sorted(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)++ def fake_get(url, **kwargs):+ response = MagicMock(status_code=200)+ if "/issues/" in url:+ response.json.return_value = [+ {+ "id": 2,+ "user": {"login": "bob", "avatar_url": "https://a/bob.png"},+ "body": "second",+ "created_at": "2026-07-06T10:00:00Z",+ "html_url": "https://github.com/PostHog/posthog/pull/1#issuecomment-2",+ }+ ]+ else: # /pulls/{n}/comments — review comments+ response.json.return_value = [+ {+ "id": 1,+ "user": {"login": "alice", "avatar_url": "https://a/alice.png"},+ "body": "first",+ "created_at": "2026-07-06T09:00:00Z",+ "html_url": "https://github.com/PostHog/posthog/pull/1#discussion_r1",+ "path": "posthog/models.py",+ }+ ]+ return response++ with patch.object(github, "_installation_authenticated_get", side_effect=fake_get):+ result = github.get_pull_request_comments("PostHog/posthog", 1)++ assert result["success"] is True+ # Merged and sorted oldest-first across both sources; review comment carries its file path,+ # conversation comment does not.+ assert [(c["author"], c["comment_type"], c["path"]) for c in result["comments"]] == [+ ("alice", "review", "posthog/models.py"),+ ("bob", "conversation", None),+ ]++ def test_get_pull_request_comments_best_effort_when_one_source_fails(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)++ def fake_get(url, **kwargs):+ if "/issues/" in url:+ return None # conversation fetch fails+ response = MagicMock(status_code=200)+ response.json.return_value = [+ {"id": 1, "user": {"login": "alice"}, "body": "x", "created_at": "2026-07-06T09:00:00Z"}+ ]+ return response++ with patch.object(github, "_installation_authenticated_get", side_effect=fake_get):+ result = github.get_pull_request_comments("PostHog/posthog", 1)++ assert result["success"] is True+ assert [c["author"] for c in result["comments"]] == ["alice"]++ @parameterized.expand(+ [+ ("success", "success", ("completed", "success")),+ ("failure", "failure", ("completed", "failure")),+ ("error", "error", ("completed", "failure")),+ ("pending", "pending", ("in_progress", None)),+ ("unknown", None, ("in_progress", None)),+ ]+ )+ def test_map_commit_status_state(self, _name, state, expected):+ assert GitHubIntegration._map_commit_status_state(state) == expected++ def test_get_pull_request_checks_merges_check_runs_and_statuses(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)++ def fake_get(url, **kwargs):+ response = MagicMock(status_code=200)+ if "/check-runs" in url:+ response.json.return_value = {+ "check_runs": [+ {+ "name": "unit",+ "status": "completed",+ "conclusion": "failure",+ "html_url": "https://github.com/checks/1",+ }+ ]+ }+ else: # /status — legacy commit statuses+ response.json.return_value = {+ "statuses": [{"context": "buildkite", "state": "success", "target_url": "https://bk/1"}]+ }+ return response++ with (+ patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}),+ patch.object(github, "_installation_authenticated_get", side_effect=fake_get),+ ):+ result = github.get_pull_request_checks("PostHog/posthog", 1)++ assert result["success"] is True+ assert result["checks"] == [+ {"name": "unit", "status": "completed", "conclusion": "failure", "url": "https://github.com/checks/1"},+ {"name": "buildkite", "status": "completed", "conclusion": "success", "url": "https://bk/1"},+ ]++ def test_get_pull_request_checks_follows_pagination(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)++ def fake_get(url, **kwargs):+ response = MagicMock(status_code=200)+ response.links = {}+ if "/check-runs" not in url:+ response.json.return_value = {"statuses": []}+ elif "page=2" in url:+ response.json.return_value = {+ "check_runs": [+ {+ "name": "second page",+ "status": "completed",+ "conclusion": "success",+ }+ ]+ }+ else:+ response.json.return_value = {+ "check_runs": [+ {+ "name": "first page",+ "status": "completed",+ "conclusion": "success",+ }+ ]+ }+ response.links = {+ "next": {"url": "https://api.github.com/repos/PostHog/posthog/commits/abc123f/check-runs?page=2"}+ }+ return response++ with (+ patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}),+ patch.object(github, "_installation_authenticated_get", side_effect=fake_get),+ ):+ result = github.get_pull_request_checks("PostHog/posthog", 1)++ assert [check["name"] for check in result["checks"]] == ["first page", "second page"]++ @parameterized.expand([("check_runs",), ("statuses",)])+ def test_get_pull_request_checks_fails_when_later_page_is_unavailable(self, failing_source):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)++ def fake_get(url, **kwargs):+ source = "check_runs" if "/check-runs" in url else "statuses"+ if source == failing_source and "page=2" in url:+ return None++ response = MagicMock(status_code=200)+ response.links = {}+ response.json.return_value = {"check_runs": []} if source == "check_runs" else {"statuses": []}+ if source == failing_source:+ next_path = "check-runs" if source == "check_runs" else "status"+ response.links = {+ "next": {"url": f"https://api.github.com/repos/PostHog/posthog/commits/abc123f/{next_path}?page=2"}+ }+ return response++ with (+ patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}),+ patch.object(github, "_installation_authenticated_get", side_effect=fake_get),+ ):+ result = github.get_pull_request_checks("PostHog/posthog", 1)++ expected_noun = "check run" if failing_source == "check_runs" else "commit status"+ assert result == {"success": False, "error": f"GitHub could not return every {expected_noun}"}++ def test_get_pull_request_checks_fails_when_pr_unavailable(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ with patch.object(github, "get_pull_request", return_value={"success": False, "error": "nope"}):+ result = github.get_pull_request_checks("PostHog/posthog", 1)+ assert result["success"] is False++ def test_get_diff_truncates_oversized_diff(self):+ from posthog.models.integration.github import _MAX_DIFF_CHARS++ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ oversized = "x" * (_MAX_DIFF_CHARS + 100)+ mock_response = MagicMock(status_code=200, text=oversized)+ with patch.object(github, "api_request", return_value=mock_response):+ result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")+ assert result["success"] is True+ assert result["truncated"] is True+ assert len(result["diff"]) < len(oversized)+ assert result["diff"].startswith("x" * 100)+ assert "truncated" in result["diff"]++ @parameterized.expand(+ [+ ("repo_traversal", {"repository": "../../other/repo"}),+ ("repo_extra_path", {"repository": "owner/repo/contents/x"}),+ ("target_branch_traversal", {"target_branch": "../../../etc"}),+ ("target_branch_query", {"target_branch": "main?ref=x"}),+ ("base_branch_traversal", {"base_branch": "..%2f"}),+ ("target_sha_not_hex", {"target_sha": "main?ref=x"}),+ ("base_sha_not_hex", {"base_sha": "../../x"}),+ ]+ )+ def test_get_diff_rejects_unsafe_values(self, _name, overrides):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ kwargs: dict = {"repository": "PostHog/posthog", "target_branch": "feature/foo", "base_branch": "master"}+ kwargs.update(overrides)+ with patch.object(github, "api_request") as mock_get:+ result = github.get_diff(**kwargs)+ assert result["success"] is False+ assert result["status_code"] == 400+ mock_get.assert_not_called()++ def test_get_diff_allows_nested_branch_names(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200, text="diff --git a b")+ with patch.object(github, "api_request", return_value=mock_response) as mock_get:+ result = github.get_diff(+ "PostHog/posthog", target_branch="feature/nested/branch", base_branch="release/v1.2"+ )+ assert result["success"] is True+ mock_get.assert_called_once()++ @parameterized.expand(+ [+ ("traversal", "../../other/repo"),+ ("extra_path_segment", "owner/repo/contents/secret"),+ ("query_injection", "owner/repo?ref=x"),+ ("fragment", "owner/repo#"),+ ("bare_name", "repo"),+ ]+ )+ def test_first_for_team_repository_rejects_unsafe_path_without_probing(self, _name, repository):+ # The access check interpolates `repository` into an authenticated GET /repos/{repository};+ # an unsafe path must be rejected before any request fires, so it can't probe other endpoints.+ self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ with patch.object(GitHubIntegration, "installation_can_access_repository") as mock_access:+ result = GitHubIntegration.first_for_team_repository(self.team.id, repository)+ assert result is None+ mock_access.assert_not_called()++ def test_first_for_team_repository_allows_owner_repo(self):+ self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ with patch.object(GitHubIntegration, "installation_can_access_repository", return_value=True) as mock_access:+ result = GitHubIntegration.first_for_team_repository(self.team.id, "PostHog/posthog")+ assert result is not None+ mock_access.assert_called_once_with("PostHog/posthog")++ @parameterized.expand(+ [+ ("owner_repo", "PostHog/posthog", "https://api.github.com/repos/PostHog/posthog/pulls/123"),+ ("bare_repo", "posthog", "https://api.github.com/repos/PostHog/posthog/pulls/123"),+ ]+ )+ def test_close_pull_request_patches_state_closed(self, _name, repository, expected_url):+ # account.name lets a bare repo name resolve to {org}/{repo} via organization().+ integration = self.create_integration(+ config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}+ )+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200)+ mock_response.json.return_value = {"number": 123, "state": "closed"}+ with patch.object(github, "_installation_authenticated_patch", return_value=mock_response) as mock_patch:+ result = github.close_pull_request(repository, 123)+ assert result == {"success": True, "number": 123, "state": "closed"}+ assert mock_patch.call_args.args[0] == expected_url+ assert mock_patch.call_args.kwargs["json_body"] == {"state": "closed"}++ def test_close_pull_request_maps_upstream_error(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=404, text="Not Found")+ with patch.object(github, "_installation_authenticated_patch", return_value=mock_response):+ result = github.close_pull_request("PostHog/posthog", 123)+ assert result == {"success": False, "error": "Failed to close pull request: Not Found", "status_code": 404}++ def test_close_pull_request_from_url_parses_and_closes(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200)+ mock_response.json.return_value = {"number": 42, "state": "closed"}+ with patch.object(github, "_installation_authenticated_patch", return_value=mock_response) as mock_patch:+ result = github.close_pull_request_from_url("https://github.com/PostHog/posthog/pull/42")+ assert result["success"] is True+ assert mock_patch.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/pulls/42"++ def test_close_pull_request_from_url_rejects_non_pr_url(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ with patch.object(github, "_installation_authenticated_patch") as mock_patch:+ result = github.close_pull_request_from_url("https://github.com/PostHog/posthog/issues/42")+ assert result["success"] is False+ mock_patch.assert_not_called()++ def test_search_issues_drops_results_from_other_repositories(self):+ # Search-syntax operators in the query (e.g. "foo OR bar") can escape the repo:+ # qualifier, so results must be filtered by the repository they actually belong to.+ integration = self.create_integration(+ config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}+ )+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200)+ mock_response.json.return_value = {+ "items": [+ {+ "number": 1,+ "title": "In repo",+ "html_url": "https://github.com/PostHog/posthog/issues/1",+ "repository_url": "https://api.github.com/repos/PostHog/posthog",+ },+ {+ "number": 2,+ "title": "Other repo",+ "html_url": "https://github.com/PostHog/other/issues/2",+ "repository_url": "https://api.github.com/repos/PostHog/other",+ },+ {+ "number": 3,+ "title": "A pull request",+ "html_url": "https://github.com/PostHog/posthog/pull/3",+ "repository_url": "https://api.github.com/repos/PostHog/posthog",+ "pull_request": {"url": "https://api.github.com/repos/PostHog/posthog/pulls/3"},+ },+ ]+ }+ with patch.object(github, "api_request", return_value=mock_response) as mock_request:+ results = github.search_issues("posthog", 'crash" repo:microsoft/vscode "')+ assert [result["id"] for result in results] == ["1"]+ assert results[0]["external_context"] == {"repository": "posthog", "number": 1}+ # The user's text is quoted so its qualifiers and operators match literally instead of+ # rewriting the query and filling the result page with foreign matches.+ sent_query = mock_request.call_args.kwargs["params"]["q"]+ assert sent_query == 'repo:PostHog/posthog "crash repo:microsoft/vscode" in:title type:issue'++ def test_comment_on_pull_request_posts_to_issues_endpoint(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=201)+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:+ result = github.comment_on_pull_request("PostHog/posthog", 123, "hello")+ assert result == {"success": True}+ # PR comments go through the issues endpoint, not /pulls.+ assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/123/comments"+ assert mock_post.call_args.kwargs["json_body"] == {"body": "hello"}++ def test_comment_on_pull_request_from_url_parses_and_posts(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=201)+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:+ result = github.comment_on_pull_request_from_url("https://github.com/PostHog/posthog/pull/42", "note")+ assert result["success"] is True+ assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/42/comments"++ @parameterized.expand(+ [+ (+ "complete_headers",+ {+ "X-RateLimit-Resource": "core",+ "X-RateLimit-Remaining": "4998",+ "X-RateLimit-Limit": "5000",+ "X-RateLimit-Reset": "1704117600",+ },+ "core",+ 4998,+ 5000,+ 1704117600,+ ),+ ("no_headers", {}, "unknown", None, None, None),+ (+ "no_resource_header",+ {+ "X-RateLimit-Remaining": "4997",+ "X-RateLimit-Limit": "5000",+ "X-RateLimit-Reset": "1704117601",+ },+ "unknown",+ 4997,+ 5000,+ 1704117601,+ ),+ ]+ )+ @patch("posthog.egress.transport.transport.requests.request")+ def test_github_api_request_metrics_include_integration_and_rate_limit_headers(+ self,+ _name: str,+ response_headers: dict[str, str],+ expected_resource: str,+ expected_remaining: int | None,+ expected_limit: int | None,+ expected_reset: int | None,+ mock_get,+ ):+ # Distinct installation id per case: the gauges are keyed by installation_id on a process-global+ # registry that isn't reset between methods, so a shared id would make the no_headers "== None"+ # assertion depend on parametrize ordering (another case sets the same (id, "unknown") series).+ integration = self.create_integration(+ {"installation_id": f"INSTALL-{_name}", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ response = MagicMock()+ response.status_code = 200+ response.headers = response_headers+ mock_get.return_value = response++ labels = {+ "installation_id": integration.integration_id,+ "method": "GET",+ "endpoint": "/repos/{owner}/{repo}",+ "status_code": "200",+ "source": "integration",+ }+ previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0++ with patch.object(GitHubIntegration, "access_token_expired", return_value=False):+ GitHubIntegration(integration).api_request(+ "GET",+ "/repos/PostHog/posthog",+ endpoint="/repos/{owner}/{repo}",+ )++ assert REGISTRY.get_sample_value("github_integration_api_requests_total", labels) == previous_count + 1+ assert (+ REGISTRY.get_sample_value(+ "github_integration_api_rate_limit_remaining",+ {"installation_id": integration.integration_id, "resource": expected_resource},+ )+ == expected_remaining+ )+ assert (+ REGISTRY.get_sample_value(+ "github_integration_api_rate_limit_limit",+ {"installation_id": integration.integration_id, "resource": expected_resource},+ )+ == expected_limit+ )+ assert (+ REGISTRY.get_sample_value(+ "github_integration_api_rate_limit_reset_timestamp_seconds",+ {"installation_id": integration.integration_id, "resource": expected_resource},+ )+ == expected_reset+ )++ @patch("posthog.egress.transport.transport.requests.request")+ def test_github_api_request_metrics_include_request_exceptions(self, mock_get):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ mock_get.side_effect = requests.RequestException("network failure")++ labels = {+ "installation_id": integration.integration_id,+ "method": "GET",+ "endpoint": "/repos/{owner}/{repo}",+ "status_code": "exception",+ "source": "integration",+ }+ previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0++ with (+ patch.object(GitHubIntegration, "access_token_expired", return_value=False),+ pytest.raises(GitHubIntegrationError),+ ):+ GitHubIntegration(integration).api_request(+ "GET",+ "/repos/PostHog/posthog",+ endpoint="/repos/{owner}/{repo}",+ )++ # GET retries the network error once; both attempts record an exception sample.+ assert REGISTRY.get_sample_value("github_integration_api_requests_total", labels) == previous_count + 2++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_github_integration_refresh_token(self, mock_client_request):+ mock_client_request.side_effect = self.mock_github_client_request(status_code=201)++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = GitHubIntegration.integration_from_installation_id(+ "INSTALLATION_ID",+ self.team.id,+ self.user,+ )++ assert GitHubIntegration(integration).access_token_expired() is False++ with freeze_time("2024-01-01T14:00:00Z"):+ assert GitHubIntegration(integration).access_token_expired() is True++ GitHubIntegration(integration).refresh_access_token()+ assert GitHubIntegration(integration).access_token_expired() is False++ assert integration.config == {+ "installation_id": "INSTALLATION_ID",+ "account": {+ "name": "PostHog",+ "type": "Organization",+ },+ "repository_selection": "all",+ "refreshed_at": 1704117600,+ "expires_in": 3600,+ }++ assert integration.sensitive_config == {+ "access_token": "ACCESS_TOKEN",+ }++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_github_integration_persists_installation_permissions(self, mock_client_request):+ # The warehouse schema picker reads config["permissions"] to mark tables the installation+ # can't sync. Dropping this on connect or refresh silently returns the picker to offering+ # tables whose every sync 403s.+ mock_client_request.side_effect = self.mock_github_client_request(+ permissions={"contents": "read", "metadata": "read"}+ )+ integration = GitHubIntegration.integration_from_installation_id("INSTALLATION_ID", self.team.id, self.user)+ assert integration.config["permissions"] == {"contents": "read", "metadata": "read"}++ # A permission update to the App shows up on the next hourly token refresh, including for+ # integrations connected before this key was persisted at all.+ mock_client_request.side_effect = self.mock_github_client_request(+ permissions={"contents": "read", "metadata": "read", "deployments": "read"}+ )+ GitHubIntegration(integration).refresh_access_token()+ assert integration.config["permissions"] == {"contents": "read", "metadata": "read", "deployments": "read"}++ @patch("posthog.models.integration.github.reload_integrations_on_workers")+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_github_refresh_access_token_handles_errors(self, mock_client_request, mock_reload):+ """Test that errors field is set if refresh_access_token fails"""+ integration = self.create_integration({"expires_at": 3600}, {"token": "REFRESH"})+ mock_client_request.side_effect = self.mock_github_client_request(status_code=400, error_text="error")++ with freeze_time("2024-01-01T12:00:00Z"):+ integration.errors = ""+ integration.save()++ with pytest.raises(Exception):+ GitHubIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.errors == "TOKEN_REFRESH_FAILED"+ assert integration.config["refresh_failure_count"] == 1++ @patch("posthog.models.integration.github.reload_integrations_on_workers")+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_github_refresh_access_token_resets_errors(self, mock_client_request, mock_reload):+ """Test that errors field is reset to empty string after successful refresh_access_token"""+ mock_client_request.side_effect = self.mock_github_client_request(status_code=201)++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = GitHubIntegration.integration_from_installation_id(+ "INSTALLATION_ID",+ self.team.id,+ self.user,+ )+ integration.errors = "TOKEN_REFRESH_FAILED"+ integration.save()++ GitHubIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.errors == ""++ @parameterized.expand(+ [+ ("uninstalled_404", 404, "Not Found", {}, True),+ ("suspended_403", 403, "This installation has been suspended.", {}, True),+ ("rate_limited_403", 403, "You have exceeded a secondary rate limit", {"retry-after": "60"}, False),+ ("transient_500", 500, "Server Error", {}, False),+ ]+ )+ @patch("posthog.models.integration.github.reload_integrations_on_workers")+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_github_refresh_disarms_proactive_refresh_only_for_dead_installation(+ self, _name, status_code, text, headers, expected_disarmed, mock_client_request, _mock_reload+ ):+ response = MagicMock(spec=requests.Response)+ response.status_code = status_code+ response.text = text+ response.headers = headers+ response.json.return_value = {}+ mock_client_request.return_value = response++ integration = self.create_integration(+ config={"installation_id": "INSTALL", "expires_in": 3600, "refreshed_at": int(time.time()) - 3600},+ sensitive_config={"access_token": "ACCESS_TOKEN"},+ )++ with pytest.raises(GitHubIntegrationError):+ GitHubIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ if expected_disarmed:+ assert "expires_in" not in integration.config+ assert "refreshed_at" not in integration.config+ assert GitHubIntegration(integration).access_token_expired() is False+ assert integration.config["installation_unavailable_since"]+ assert GitHubIntegration(integration).installation_unavailable() is True+ else:+ assert integration.config["expires_in"] == 3600+ assert "refreshed_at" in integration.config+ assert "installation_unavailable_since" not in integration.config+ assert GitHubIntegration(integration).installation_unavailable() is False++ @patch("posthog.models.integration.github.reload_integrations_on_workers")+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_github_refresh_success_clears_installation_unavailable_marker(self, mock_client_request, _mock_reload):+ mock_client_request.side_effect = self.mock_github_client_request(status_code=201)+ integration = self.create_integration(+ config={"installation_id": "INSTALL", "installation_unavailable_since": 1700000000},+ sensitive_config={"access_token": "STALE_TOKEN"},+ )++ GitHubIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert "installation_unavailable_since" not in integration.config+ assert GitHubIntegration(integration).installation_unavailable() is False+ assert integration.sensitive_config["access_token"] == "ACCESS_TOKEN"+ assert "expires_in" in integration.config++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_list_repositories_retries_transient_non_json_response(self, _mock_expired, mock_get):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )++ transient = MagicMock()+ transient.status_code = 502+ transient.json.side_effect = ValueError("not json")++ success = MagicMock()+ success.status_code = 200+ success.json.return_value = {+ "repositories": [+ {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},+ ]+ }++ mock_get.side_effect = [transient, success]++ repos, has_more = GitHubIntegration(integration).list_repositories()++ assert repos == [+ {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},+ ]+ assert has_more is False+ assert mock_get.call_count == 2++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_list_repositories_raises_after_repeated_transient_non_json(self, _mock_expired, mock_get):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )++ transient_1 = MagicMock()+ transient_1.status_code = 502+ transient_1.json.side_effect = ValueError("not json")++ transient_2 = MagicMock()+ transient_2.status_code = 502+ transient_2.json.side_effect = ValueError("not json")++ mock_get.side_effect = [transient_1, transient_2]++ with pytest.raises(GitHubIntegrationError, match="list_repositories non-JSON response"):+ GitHubIntegration(integration).list_repositories()++ assert mock_get.call_count == 2++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_list_all_repositories_raises_when_later_page_fails(self, _mock_expired, mock_get):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )++ first_page = MagicMock()+ first_page.status_code = 200+ first_page.json.return_value = {+ "repositories": [{"id": i, "name": f"repo-{i}", "full_name": f"PostHog/repo-{i}"} for i in range(100)]+ }++ second_page = MagicMock()+ second_page.status_code = 502+ second_page.json.return_value = {"message": "bad gateway"}++ # Page-1 succeeds. Page-2 fetch is retried once after transient 502.+ mock_get.side_effect = [first_page, second_page, second_page]++ with pytest.raises(GitHubIntegrationError, match="failed to list repositories"):+ GitHubIntegration(integration).list_all_repositories()++ assert mock_get.call_count == 3++ @patch("posthog.models.integration.github.GitHubIntegration.list_repositories")+ def test_list_all_repositories_fetches_all_pages(self, mock_list):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )++ first_page = [{"id": i, "name": f"repo-{i}", "full_name": f"PostHog/repo-{i}"} for i in range(100)]+ second_page = [{"id": i, "name": f"repo-{i}", "full_name": f"PostHog/repo-{i}"} for i in range(100, 130)]+ mock_list.side_effect = [+ (first_page, True),+ (second_page, False),+ ]++ repos = GitHubIntegration(integration).list_all_repositories()++ assert len(repos) == 130+ assert repos == first_page + second_page+ assert mock_list.call_args_list == [+ call(page=1, per_page=100),+ call(page=2, per_page=100),+ ]++ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_list_cached_repositories_uses_cached_data_when_fresh(self, mock_list_all):+ cached_repositories = [+ {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},+ ]+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ integration.repository_cache = cached_repositories+ integration.repository_cache_updated_at = timezone.now()+ integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])++ labels = {+ "integration_id": str(integration.id),+ "cache": "repositories",+ "repository": "__all__",+ "result": "hit",+ }+ previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0++ repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=1, offset=1)++ assert repos == [{"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"}]+ assert has_more is False+ mock_list_all.assert_not_called()+ assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1++ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_list_cached_repositories_surfaces_optional_fields_when_present(self, mock_list_all):+ cached_repositories = [+ {+ "id": 1,+ "name": "posthog",+ "full_name": "PostHog/posthog",+ "private": True,+ "default_branch": "master",+ "language": "Python",+ "pushed_at": "2026-06-01T00:00:00Z",+ "archived": False,+ "can_push": True,+ },+ {"id": 2, "name": "legacy", "full_name": "PostHog/legacy"},+ ]+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ integration.repository_cache = cached_repositories+ integration.repository_cache_updated_at = timezone.now()+ integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])++ repos, _ = GitHubIntegration(integration).list_cached_repositories()++ assert repos[0] == {+ "id": 1,+ "name": "posthog",+ "full_name": "PostHog/posthog",+ "private": True,+ "default_branch": "master",+ "language": "Python",+ "pushed_at": "2026-06-01T00:00:00Z",+ "archived": False,+ "can_push": True,+ }+ # Repos cached before these fields existed keep their original shape — optional keys are omitted, not nulled.+ assert repos[1] == {"id": 2, "name": "legacy", "full_name": "PostHog/legacy"}+ mock_list_all.assert_not_called()++ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_sync_repository_cache_respects_refresh_cooldown(self, mock_list_all):+ cached_repositories = [+ {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},+ ]+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ integration.repository_cache = cached_repositories+ integration.repository_cache_updated_at = timezone.now()+ integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])++ repos = GitHubIntegration(integration).sync_repository_cache(min_refresh_interval_seconds=60)++ assert repos == cached_repositories+ mock_list_all.assert_not_called()++ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_sync_repository_cache_only_updates_timestamp_when_snapshot_unchanged(self, mock_list_all):+ cached_repositories = [+ {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},+ ]+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ original_updated_at = timezone.now() - timedelta(minutes=5)+ integration.repository_cache = cached_repositories+ integration.repository_cache_updated_at = original_updated_at+ integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])+ mock_list_all.return_value = cached_repositories++ with patch.object(integration, "save", wraps=integration.save) as mock_save:+ repos = GitHubIntegration(integration).sync_repository_cache()++ assert repos == cached_repositories+ mock_save.assert_called_once_with(update_fields=["repository_cache_updated_at"])+ integration.refresh_from_db()+ assert integration.repository_cache == cached_repositories+ assert integration.repository_cache_updated_at is not None+ assert integration.repository_cache_updated_at > original_updated_at++ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_list_cached_repositories_populates_cache_on_miss(self, mock_list_all):+ fetched_repositories = [+ {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},+ ]+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ mock_list_all.return_value = fetched_repositories++ labels = {+ "integration_id": str(integration.id),+ "cache": "repositories",+ "repository": "__all__",+ "result": "miss",+ }+ previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0++ repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=1, offset=0)++ integration.refresh_from_db()+ assert repos == [{"id": 1, "name": "posthog", "full_name": "PostHog/posthog"}]+ assert has_more is True+ assert integration.repository_cache == fetched_repositories+ assert integration.repository_cache_updated_at is not None+ mock_list_all.assert_called_once_with()+ assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1++ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_list_cached_repositories_returns_stale_cache_on_refresh_error(self, mock_list_all):+ stale_repositories = [+ {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},+ ]+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ integration.repository_cache = stale_repositories+ integration.repository_cache_updated_at = timezone.now() - timedelta(+ seconds=GITHUB_REPOSITORY_CACHE_TTL_SECONDS + 1+ )+ integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])+ mock_list_all.side_effect = Exception("GitHub is slow")++ repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=10, offset=0)++ integration.refresh_from_db()+ assert repos == stale_repositories+ assert has_more is False+ assert integration.repository_cache == stale_repositories+ mock_list_all.assert_called_once_with()++ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_list_cached_repositories_raises_on_refresh_error_without_cache(self, mock_list_all):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ mock_list_all.side_effect = Exception("GitHub is slow")++ with pytest.raises(Exception, match="GitHub is slow"):+ GitHubIntegration(integration).list_cached_repositories(limit=10, offset=0)++ integration.refresh_from_db()+ assert integration.repository_cache == []+ assert integration.repository_cache_updated_at is None+ mock_list_all.assert_called_once_with()++ def test_invalidate_github_repository_caches_for_installation_clears_team_and_personal_rows(self):+ from posthog.models.user_integration import UserIntegration++ team_integration = self.create_integration(+ {"installation_id": "12345", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ team_integration.integration_id = "12345"+ team_integration.repository_cache = [{"id": 1, "name": "a", "full_name": "org/a"}]+ team_integration.repository_cache_updated_at = timezone.now()+ team_integration.save(update_fields=["integration_id", "repository_cache", "repository_cache_updated_at"])++ user_integration = UserIntegration.objects.create(+ user=self.user,+ kind=UserIntegration.IntegrationKind.GITHUB,+ integration_id="12345",+ config={"installation_id": "12345"},+ sensitive_config={"access_token": "ACCESS_TOKEN"},+ repository_cache=[{"id": 2, "name": "b", "full_name": "org/b"}],+ repository_cache_updated_at=timezone.now(),+ )++ invalidate_github_repository_caches_for_installation("12345")++ team_integration = Integration.objects.get(pk=team_integration.pk)+ user_integration = UserIntegration.objects.get(pk=user_integration.pk)+ assert team_integration.repository_cache_updated_at is None+ assert user_integration.repository_cache_updated_at is None+ assert team_integration.repository_cache == [{"id": 1, "name": "a", "full_name": "org/a"}]++ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_list_cached_repositories_pages_with_full_cached_snapshot(self, mock_list_all):+ fetched_repositories = [{"id": i, "name": f"repo-{i}", "full_name": f"PostHog/repo-{i}"} for i in range(650)]+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ mock_list_all.return_value = fetched_repositories++ repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=25, offset=600)++ assert repos == fetched_repositories[600:625]+ assert has_more is True+ mock_list_all.assert_called_once_with()++ @parameterized.expand(+ [+ ("blank_search_returns_all", " ", 10, 0, [1, 2, 3, 4], False),+ ("no_match_returns_empty", "missing", 10, 0, [], False),+ ("casefold_matches_owner_prefix", "POSTHOG", 10, 0, [1, 2, 3, 4], False),+ ("pagination_applies_after_filter", "posthog", 1, 1, [2], True),+ ]+ )+ @patch("posthog.models.integration.github.GitHubIntegration.list_all_repositories")+ def test_list_cached_repositories_filters_search_before_pagination(+ self,+ _name,+ search,+ limit,+ offset,+ expected_ids,+ expected_has_more,+ mock_list_all,+ ):+ fetched_repositories = [+ {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},+ {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},+ {"id": 3, "name": "code", "full_name": "PostHog/code"},+ {"id": 4, "name": "posthog-python", "full_name": "PostHog/posthog-python"},+ ]+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ mock_list_all.return_value = fetched_repositories++ repos, has_more = GitHubIntegration(integration).list_cached_repositories(+ search=search, limit=limit, offset=offset+ )++ assert [repo["id"] for repo in repos] == expected_ids+ assert has_more is expected_has_more+ mock_list_all.assert_called_once_with()++ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")+ def test_list_cached_branches_uses_cached_data_when_fresh(self, mock_default_branch, mock_list_branches):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ cache.set(+ GitHubIntegration(integration)._get_branch_cache_key(repo),+ {+ "branches": ["main", "develop", "feature/test"],+ "default_branch": "main",+ "updated_at": time.time(),+ },+ )++ labels = {+ "integration_id": str(integration.id),+ "cache": "branches",+ "repository": repo,+ "result": "hit",+ }+ previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0++ branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(+ repo, limit=2, offset=1+ )++ assert branches == ["develop", "feature/test"]+ assert default_branch == "main"+ assert has_more is False+ mock_list_branches.assert_not_called()+ mock_default_branch.assert_not_called()+ assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1++ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")+ def test_list_cached_branches_filters_search_before_pagination(self, mock_default_branch, mock_list_branches):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ cache.set(+ GitHubIntegration(integration)._get_branch_cache_key(repo),+ {+ "branches": [+ "main",+ "feature/agent-cache",+ "feature/agent-branch-search",+ "fix/refresh-button",+ ],+ "default_branch": "main",+ "updated_at": time.time(),+ },+ )++ branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(+ repo, search="feature/agent", limit=1, offset=1+ )++ assert branches == ["feature/agent-branch-search"]+ assert default_branch == "main"+ assert has_more is False+ mock_list_branches.assert_not_called()+ mock_default_branch.assert_not_called()++ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")+ def test_list_cached_branches_populates_cache_on_miss(self, mock_default_branch, mock_list_branches):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ mock_list_branches.return_value = (["develop", "feature/test"], False)+ mock_default_branch.return_value = "main"++ labels = {+ "integration_id": str(integration.id),+ "cache": "branches",+ "repository": repo,+ "result": "miss",+ }+ previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0++ branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(+ repo, limit=2, offset=0+ )++ cached = cache.get(GitHubIntegration(integration)._get_branch_cache_key(repo))+ assert branches == ["develop", "feature/test"]+ assert default_branch == "main"+ assert has_more is False+ assert cached["branches"] == ["develop", "feature/test"]+ assert cached["default_branch"] == "main"+ mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)+ mock_default_branch.assert_called_once_with(repo)+ assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1++ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")+ def test_list_cached_branches_returns_stale_cache_on_refresh_error(self, mock_default_branch, mock_list_branches):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ cache.set(+ GitHubIntegration(integration)._get_branch_cache_key(repo),+ {+ "branches": ["main", "develop"],+ "default_branch": "main",+ "updated_at": time.time() - (GITHUB_BRANCH_CACHE_TTL_SECONDS + 1),+ },+ )+ mock_list_branches.side_effect = Exception("GitHub is slow")++ branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(+ repo, limit=10, offset=0+ )++ assert branches == ["main", "develop"]+ assert default_branch == "main"+ assert has_more is False+ mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)+ mock_default_branch.assert_not_called()++ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")+ def test_list_cached_branches_keeps_cached_default_branch_on_refresh_failure(+ self, mock_default_branch, mock_list_branches+ ):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ cache.set(+ GitHubIntegration(integration)._get_branch_cache_key(repo),+ {+ "branches": ["main", "develop"],+ "default_branch": "main",+ "updated_at": time.time() - (GITHUB_BRANCH_CACHE_TTL_SECONDS + 1),+ },+ )+ mock_list_branches.return_value = (["main", "develop", "feature/test"], False)+ mock_default_branch.side_effect = Exception("GitHub is slow")++ branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(+ repo, limit=10, offset=0+ )++ cached = cache.get(GitHubIntegration(integration)._get_branch_cache_key(repo))+ assert branches == ["main", "develop", "feature/test"]+ assert default_branch == "main"+ assert has_more is False+ assert cached["branches"] == ["main", "develop", "feature/test"]+ assert cached["default_branch"] == "main"+ mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)+ mock_default_branch.assert_called_once_with(repo)++ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")+ def test_list_cached_branches_raises_on_refresh_error_without_cache(self, mock_list_branches):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ mock_list_branches.side_effect = Exception("GitHub is slow")++ with pytest.raises(Exception, match="GitHub is slow"):+ GitHubIntegration(integration).list_cached_branches(repo, limit=10, offset=0)++ mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)++ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")+ def test_list_all_branches_fetches_all_pages(self, mock_list_branches):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ first_page = [f"branch-{i}" for i in range(100)]+ second_page = [f"branch-{i}" for i in range(100, 230)]+ mock_list_branches.side_effect = [+ (first_page, True),+ (second_page, False),+ ]++ branches = GitHubIntegration(integration).list_all_branches(repo)++ assert branches == first_page + second_page+ assert mock_list_branches.call_args_list == [+ call(repo, limit=100, offset=0),+ call(repo, limit=100, offset=100),+ ]++ @patch("posthog.models.integration.github.GitHubIntegration.list_branches")+ @patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")+ def test_list_cached_branches_pages_with_full_cached_snapshot(self, mock_default_branch, mock_list_branches):+ integration = self.create_integration(+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ {"access_token": "ACCESS_TOKEN"},+ )+ repo = "posthog/posthog"+ first_page = [f"branch-{i}" for i in range(100)]+ second_page = [f"branch-{i}" for i in range(100, 200)]+ remaining_branches = [f"branch-{i}" for i in range(200, 1500)]+ mock_list_branches.side_effect = [+ (first_page, True),+ (second_page, True),+ (remaining_branches, False),+ ]+ mock_default_branch.return_value = "branch-1200"++ branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(+ repo, limit=25, offset=1200+ )++ expected_branches = ["branch-1199"] + [f"branch-{i}" for i in range(1201, 1225)]+ assert branches == expected_branches+ assert default_branch == "branch-1200"+ assert has_more is True+ assert mock_list_branches.call_args_list == [+ call(repo, limit=100, offset=0),+ call(repo, limit=100, offset=100),+ call(repo, limit=100, offset=200),+ ]++ # --- raise_if_github_rate_limited ---++ @parameterized.expand(+ [+ ("429_no_body", 429, "", True),+ ("403_rate_limit_body", 403, "API rate limit exceeded for installation", True),+ ("403_other_body", 403, "Forbidden", False),+ ("200_ok", 200, "", False),+ ("404_not_found", 404, "", False),+ ]+ )+ def test_raise_if_github_rate_limited_detection(self, _name, status_code, body, should_raise):+ response = MagicMock()+ response.status_code = status_code+ response.text = body+ response.headers = {}++ if should_raise:+ with pytest.raises(GitHubRateLimitError):+ raise_if_github_rate_limited(response)+ else:+ raise_if_github_rate_limited(response) # must not raise++ @freeze_time("2024-01-01 12:00:00")+ def test_raise_if_github_rate_limited_populates_fields(self):+ reset_timestamp = int(time.time()) + 60+ response = MagicMock()+ response.status_code = 429+ response.text = ""+ response.headers = {+ "x-ratelimit-reset": str(reset_timestamp),+ "retry-after": "30",+ }++ with pytest.raises(GitHubRateLimitError) as exc_info:+ raise_if_github_rate_limited(response)++ assert exc_info.value.reset_at == reset_timestamp+ assert exc_info.value.retry_after == 30++ @freeze_time("2024-01-01 12:00:00")+ def test_raise_if_github_rate_limited_derives_retry_after_from_reset_at(self):+ reset_timestamp = int(time.time()) + 45+ response = MagicMock()+ response.status_code = 429+ response.text = ""+ response.headers = {"x-ratelimit-reset": str(reset_timestamp)}++ with pytest.raises(GitHubRateLimitError) as exc_info:+ raise_if_github_rate_limited(response)++ assert exc_info.value.retry_after == 45++ # --- exception hierarchy ---++ def test_github_rate_limit_error_is_egress_error_not_fatal_integration_error(self):+ # Deliberately NOT a GitHubIntegrationError: a transient rate limit is retryable, not a fatal+ # integration failure, and it lives in the egress layer. Backoff filters key off these fields.+ err = GitHubRateLimitError("test", retry_after=45)+ assert not isinstance(err, GitHubIntegrationError)+ assert err.retry_after == 45++ # --- get_access_token ---++ def test_get_access_token_returns_token_when_not_expired(self):+ integration = self.create_integration(+ config={"expires_in": 3600, "refreshed_at": int(time.time())},+ sensitive_config={"access_token": "valid-token"},+ )+ github = GitHubIntegration(integration)+ assert github.get_access_token() == "valid-token"++ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ @patch("posthog.models.integration.github.reload_integrations_on_workers")+ def test_get_access_token_refreshes_when_expired(self, mock_reload, mock_client_request):+ integration = self.create_integration(+ config={"expires_in": 3600, "refreshed_at": int(time.time()) - 7200}, # expired: refreshed 2h ago+ sensitive_config={"access_token": "old-token"},+ )+ mock_response = MagicMock()+ mock_response.status_code = 201+ dt = datetime.now(UTC) + timedelta(hours=1)+ mock_response.json.return_value = {+ "token": "new-token",+ "expires_at": dt.replace(tzinfo=None).isoformat(timespec="seconds") + "Z",+ }+ mock_client_request.return_value = mock_response++ github = GitHubIntegration(integration)+ token = github.get_access_token()++ assert token == "new-token"+ mock_client_request.assert_called_once()++ def test_get_access_token_raises_when_token_missing_after_refresh(self):+ integration = self.create_integration(+ config={"expires_in": 3600, "refreshed_at": int(time.time())},+ sensitive_config={}, # no access_token key+ )+ github = GitHubIntegration(integration)++ with pytest.raises(GitHubIntegrationError, match="Access token unavailable"):+ github.get_access_token()+++def _create_github_integration(team) -> Integration:+ # integration_id mirrors production (set from config on install) — the egress gate and+ # tier store key on it; without it every call is identity-blind and skips both.+ return Integration.objects.create(+ team=team,+ kind="github",+ integration_id="INSTALL",+ config={"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ sensitive_config={"access_token": "ACCESS_TOKEN"},+ )+++class TestGitHubIntegrationGhApiGet(BaseTest):+ def _create_integration(self) -> Integration:+ return _create_github_integration(self.team)++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_returns_parsed_json_body(self, _mock_expired, mock_get):+ ok = MagicMock()+ ok.status_code = 200+ ok.json.return_value = {"default_branch": "main"}+ mock_get.return_value = ok++ integration = self._create_integration()+ body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")+ assert body == {"default_branch": "main"}++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.egress.github.transport.consume_github_installation_sync", return_value=False)+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_batch_instance_is_shed_when_budget_denied(self, _mock_expired, _mock_consume, mock_request):+ # Guards the lane plumbing: if the instance priority stops reaching the transport, BATCH+ # callers silently ride the never-shed CRITICAL lane again and denials stop deferring work.+ integration = self._create_integration()+ github = GitHubIntegration(integration, priority=Priority.BATCH)+ with pytest.raises(GitHubEgressBudgetExhausted):+ github.api_request("GET", "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")+ mock_request.assert_not_called()++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.egress.github.transport.consume_github_installation_sync", return_value=False)+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_critical_default_proceeds_when_budget_denied(self, _mock_expired, _mock_consume, mock_request):+ ok = MagicMock()+ ok.status_code = 200+ mock_request.return_value = ok++ integration = self._create_integration()+ response = GitHubIntegration(integration).api_request(+ "GET", "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"+ )+ assert response.status_code == 200+ mock_request.assert_called_once()++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_retries_once_on_transient_5xx(self, _mock_expired, mock_get):+ transient = MagicMock()+ transient.status_code = 503+ transient.json.return_value = {}+ ok = MagicMock()+ ok.status_code = 200+ ok.json.return_value = {"ok": True}+ mock_get.side_effect = [transient, ok]++ integration = self._create_integration()+ body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")+ assert body == {"ok": True}+ assert mock_get.call_count == 2++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_raises_rate_limit_error_on_secondary_limit(self, _mock_expired, mock_get):+ resp = MagicMock()+ resp.status_code = 403+ resp.headers = {"retry-after": "5"}+ resp.json.return_value = {"message": "secondary rate limit"}+ mock_get.return_value = resp++ integration = self._create_integration()+ with pytest.raises(GitHubRateLimitError) as excinfo:+ GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")+ assert excinfo.value.retry_after == 5++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_detects_secondary_limit_from_body_when_headers_missing(self, _mock_expired, mock_get):+ resp = MagicMock()+ resp.status_code = 403+ resp.headers = {}+ resp.text = '{"message": "You have exceeded a secondary rate limit."}'+ resp.json.return_value = {"message": "You have exceeded a secondary rate limit."}+ mock_get.return_value = resp++ integration = self._create_integration()+ with pytest.raises(GitHubRateLimitError) as excinfo:+ GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")+ assert excinfo.value.retry_after == 60++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.refresh_access_token")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_refreshes_token_on_401(self, _mock_expired, mock_refresh, mock_get):+ unauth = MagicMock()+ unauth.status_code = 401+ unauth.json.return_value = {}+ ok = MagicMock()+ ok.status_code = 200+ ok.json.return_value = {"after_refresh": True}+ mock_get.side_effect = [unauth, ok]++ integration = self._create_integration()+ body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")+ assert body == {"after_refresh": True}+ assert mock_refresh.called++ def test_rejects_path_without_leading_slash(self):+ integration = self._create_integration()+ with pytest.raises(ValueError, match="must start with"):+ GitHubIntegration(integration)._gh_api_get("repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")+++class TestGitHubIntegrationGraphQL(BaseTest):+ def _create_integration(self) -> Integration:+ return _create_github_integration(self.team)++ @staticmethod+ def _graphql_response(body: dict) -> MagicMock:+ # GitHub returns transient GraphQL server errors as an HTTP 200 with an ``errors`` body,+ # so the retry decision hinges on the body, not the status code.+ resp = MagicMock()+ resp.status_code = 200+ resp.json.return_value = body+ return resp++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_retries_transient_server_error_and_returns_data(self, _mock_expired, mock_request):+ # A 200-with-`errors` "Something went wrong" server error must be retried, not raised —+ # otherwise a transient GitHub blip permanently kills the in-flight follow-up run.+ transient = self._graphql_response(+ {"data": None, "errors": [{"message": "Something went wrong while executing your query. (abc123)"}]}+ )+ ok = self._graphql_response({"data": {"repository": {"name": "posthog"}}})+ mock_request.side_effect = [transient, ok]++ github = GitHubIntegration(self._create_integration())+ data = github._gh_graphql("query {}", {}, endpoint="/graphql:test")+ assert data == {"repository": {"name": "posthog"}}+ assert mock_request.call_count == 2++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_gives_up_after_exhausting_transient_retries(self, _mock_expired, mock_request):+ # Guards against both a run-killing single attempt and an unbounded retry loop.+ transient = self._graphql_response(+ {"data": None, "errors": [{"type": "SERVICE_UNAVAILABLE", "message": "unavailable"}]}+ )+ mock_request.return_value = transient++ github = GitHubIntegration(self._create_integration())+ with pytest.raises(GitHubIntegrationError):+ github._gh_graphql("query {}", {}, endpoint="/graphql:test")+ assert mock_request.call_count == GitHubIntegration._GRAPHQL_TRANSIENT_ATTEMPTS++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_does_not_retry_deterministic_error(self, _mock_expired, mock_request):+ # A deterministic error (bad query, missing field, permission) will never succeed on+ # retry, so it must raise on the first attempt rather than burn the retry budget.+ mock_request.return_value = self._graphql_response(+ {"data": None, "errors": [{"type": "FORBIDDEN", "message": "Resource not accessible by integration"}]}+ )++ github = GitHubIntegration(self._create_integration())+ with pytest.raises(GitHubIntegrationError):+ github._gh_graphql("query {}", {}, endpoint="/graphql:test")+ assert mock_request.call_count == 1++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.github.GitHubIntegration.access_token_expired", return_value=False)+ def test_returns_partial_data_with_field_errors(self, _mock_expired, mock_request):+ # When GitHub returns usable data alongside field-level errors, keep the data rather+ # than treating the response as a failure.+ mock_request.return_value = self._graphql_response(+ {"data": {"repository": {"name": "posthog"}}, "errors": [{"message": "field-level error"}]}+ )++ github = GitHubIntegration(self._create_integration())+ data = github._gh_graphql("query {}", {}, endpoint="/graphql:test")+ assert data == {"repository": {"name": "posthog"}}+ assert mock_request.call_count == 1+++BABYSIT_PR_URL = "https://github.com/acme/widgets/pull/7"+++def _babysit_thread(thread_id: str, *, is_resolved: bool = False, author: str = "reviewer", body: str = "fix this"):+ return {+ "id": thread_id,+ "isResolved": is_resolved,+ "path": "posthog/api.py",+ "comments": {+ "nodes": [+ {+ "id": f"{thread_id}-C1",+ "url": f"{BABYSIT_PR_URL}#discussion_{thread_id}",+ "body": body,+ "author": {"login": author},+ "authorAssociation": "MEMBER",+ }+ ]+ },+ }+++def _babysit_feedback(node_id: str, *, author: str = "reviewer", body: str = "please rename"):+ return {+ "id": node_id,+ "url": f"{BABYSIT_PR_URL}#issuecomment-{node_id}",+ "body": body,+ "author": {"login": author},+ "authorAssociation": "MEMBER",+ }+++class TestGitHubIntegrationPullRequestBabysitSnapshot(BaseTest):+ def _github(self) -> GitHubIntegration:+ return GitHubIntegration(_create_github_integration(self.team))++ @staticmethod+ def _payload(**overrides) -> dict:+ pull_request: dict = {+ "url": BABYSIT_PR_URL,+ "state": "OPEN",+ "isDraft": False,+ "mergeable": "MERGEABLE",+ "headRefOid": "head1",+ "author": {"login": "posthog-bot"},+ "reviewThreads": {"nodes": []},+ "comments": {"nodes": []},+ "reviews": {"nodes": []},+ "commits": {"nodes": [{"commit": {"statusCheckRollup": None}}]},+ }+ pull_request.update(overrides)+ return {"repository": {"pullRequest": pull_request}}++ _FAILING_CONTEXT = {+ "__typename": "CheckRun",+ "name": "backend",+ "conclusion": "FAILURE",+ "detailsUrl": "https://ci.example.com/1",+ "checkSuite": None,+ }++ def test_resolved_threads_and_self_or_empty_feedback_are_dropped(self):+ payload = self._payload(+ reviewThreads={"nodes": [_babysit_thread("T1", is_resolved=True), _babysit_thread("T2")]},+ comments={+ "nodes": [+ _babysit_feedback("M1", author="posthog-bot"),+ _babysit_feedback("M2", body=" "),+ _babysit_feedback("M3"),+ ]+ },+ reviews={"nodes": [_babysit_feedback("R1", author="posthog-bot"), _babysit_feedback("R2")]},+ )++ with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):+ result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)++ assert [thread["id"] for thread in result["unresolved_threads"]] == ["T2"]+ assert [comment["id"] for comment in result["comments"]] == ["M3", "R2"]++ @parameterized.expand(+ [+ ("MERGED", False, "merged"),+ ("CLOSED", False, "closed"),+ ("OPEN", True, "draft"),+ ("OPEN", False, "open"),+ ]+ )+ def test_pr_state_mapping(self, gql_state, is_draft, expected):+ payload = self._payload(state=gql_state, isDraft=is_draft)++ with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):+ result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)++ assert result["state"] == expected++ @parameterized.expand(+ [+ ("CONFLICTING", True),+ ("MERGEABLE", False),+ ("UNKNOWN", False),+ ]+ )+ def test_only_a_conflicting_merge_state_flags_a_conflict(self, gql_mergeable, expected):+ payload = self._payload(mergeable=gql_mergeable)++ with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):+ result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)++ assert result["has_conflict"] is expected++ def test_extracts_only_failing_checks_with_workflow_scoped_keys(self):+ rollup = {+ "contexts": {+ "nodes": [+ {+ "__typename": "CheckRun",+ "name": "backend",+ "conclusion": "FAILURE",+ "detailsUrl": "https://ci.example.com/1",+ "checkSuite": {"workflowRun": {"workflow": {"name": "CI"}}},+ },+ {"__typename": "CheckRun", "name": "frontend", "conclusion": "SUCCESS", "checkSuite": None},+ {"__typename": "CheckRun", "name": "flaky", "conclusion": "TIMED_OUT", "checkSuite": None},+ {+ "__typename": "StatusContext",+ "context": "vercel",+ "state": "ERROR",+ "targetUrl": "https://vercel.example.com/1",+ },+ {"__typename": "StatusContext", "context": "netlify", "state": "SUCCESS"},+ ]+ },+ }+ payload = self._payload(commits={"nodes": [{"commit": {"statusCheckRollup": rollup}}]})++ with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):+ result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)++ assert [check["key"] for check in result["failing_checks"]] == ["CI/backend", "flaky", "vercel"]+ assert result["failing_checks"][0]["details_url"] == "https://ci.example.com/1"++ @parameterized.expand(+ [+ ("FAILURE", [], [("ci-rollup-failing", f"{BABYSIT_PR_URL}/checks")]),+ ("ERROR", [], [("ci-rollup-failing", f"{BABYSIT_PR_URL}/checks")]),+ ("FAILURE", [_FAILING_CONTEXT], [("backend", "https://ci.example.com/1")]),+ ("SUCCESS", [], []),+ ("PENDING", [], []),+ ]+ )+ def test_rollup_state_backstops_checks_missing_from_the_context_page(self, rollup_state, context_nodes, expected):+ rollup = {"state": rollup_state, "contexts": {"nodes": context_nodes}}+ payload = self._payload(commits={"nodes": [{"commit": {"statusCheckRollup": rollup}}]})++ with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):+ result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)++ assert [(check["key"], check["details_url"]) for check in result["failing_checks"]] == expected++ def test_invalid_pull_request_url_is_reported_as_failure_without_calling_github(self):+ with patch.object(GitHubIntegration, "_gh_graphql") as mock_graphql:+ result = self._github().get_pull_request_babysit_snapshot("https://example.com/not/a/pull-request")++ assert result["success"] is False+ mock_graphql.assert_not_called()++ def test_missing_pull_request_is_reported_as_failure(self):+ with patch.object(GitHubIntegration, "_gh_graphql", return_value={"repository": {"pullRequest": None}}):+ result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)++ assert result["success"] is Falsediff --git a/posthog/models/test/integration/test_gitlab.py b/posthog/models/test/integration/test_gitlab.pynew file mode 100644index 000000000000..8fbf55f8c56a--- /dev/null+++ b/posthog/models/test/integration/test_gitlab.py@@ -0,0 +1,64 @@+"""Tests for the GitLab integration."""++import pytest+from unittest.mock import patch+++class TestGitLabIntegrationSSRFProtection:+ """Test SSRF protections in GitLabIntegration."""++ @patch("posthog.models.integration.gitlab.requests.get")+ @patch("posthog.models.integration.gitlab.is_url_allowed")+ def test_get_uses_allow_redirects_false(self, mock_is_url_allowed, mock_get):+ """GET requests must use allow_redirects=False to prevent redirect-based SSRF bypass."""+ from posthog.models.integration import GitLabIntegration++ mock_is_url_allowed.return_value = (True, None)+ mock_get.return_value.json.return_value = {"data": "test"}++ GitLabIntegration.get("https://gitlab.com", "projects/1", "token123")++ mock_get.assert_called_once()+ call_kwargs = mock_get.call_args.kwargs+ assert call_kwargs.get("allow_redirects") is False, "GET must use allow_redirects=False for SSRF protection"++ @patch("posthog.models.integration.gitlab.requests.post")+ @patch("posthog.models.integration.gitlab.is_url_allowed")+ def test_post_uses_allow_redirects_false(self, mock_is_url_allowed, mock_post):+ """POST requests must use allow_redirects=False to prevent redirect-based SSRF bypass."""+ from posthog.models.integration import GitLabIntegration++ mock_is_url_allowed.return_value = (True, None)+ mock_post.return_value.json.return_value = {"data": "test"}++ GitLabIntegration.post("https://gitlab.com", "projects/1/issues", "token123", {"title": "test"})++ mock_post.assert_called_once()+ call_kwargs = mock_post.call_args.kwargs+ assert call_kwargs.get("allow_redirects") is False, "POST must use allow_redirects=False for SSRF protection"++ @patch("posthog.models.integration.gitlab.requests.get")+ @patch("posthog.models.integration.gitlab.is_url_allowed")+ def test_get_validates_url_before_request(self, mock_is_url_allowed, mock_get):+ """URL validation must happen before the request is made."""+ from posthog.models.integration import GitLabIntegration, GitLabIntegrationError++ mock_is_url_allowed.return_value = (False, "Private IP address not allowed")++ with pytest.raises(GitLabIntegrationError, match="Invalid GitLab hostname"):+ GitLabIntegration.get("http://192.168.1.1", "projects/1", "token123")++ mock_get.assert_not_called()++ @patch("posthog.models.integration.gitlab.requests.post")+ @patch("posthog.models.integration.gitlab.is_url_allowed")+ def test_post_validates_url_before_request(self, mock_is_url_allowed, mock_post):+ """URL validation must happen before the request is made."""+ from posthog.models.integration import GitLabIntegration, GitLabIntegrationError++ mock_is_url_allowed.return_value = (False, "Private IP address not allowed")++ with pytest.raises(GitLabIntegrationError, match="Invalid GitLab hostname"):+ GitLabIntegration.post("http://192.168.1.1", "projects/1/issues", "token123", {"title": "test"})++ mock_post.assert_not_called()diff --git a/posthog/models/test/integration/test_google_ads.py b/posthog/models/test/integration/test_google_ads.pynew file mode 100644index 000000000000..f056c89beb56--- /dev/null+++ b/posthog/models/test/integration/test_google_ads.py@@ -0,0 +1,156 @@+"""Tests for the Google Ads integration."""++from typing import Optional++import pytest+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.test import override_settings++import requests++from posthog.models.integration import GoogleAdsIntegration, Integration+++class TestGoogleAdsIntegrationModel(BaseTest):+ def _integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="google-ads",+ config={},+ sensitive_config={"access_token": "token"},+ integration_id="google_ads_test",+ )++ @staticmethod+ def _customer_client(+ customer_id: str, name: str, level: Optional[str] = None, manager: bool = False, status: str = "ENABLED"+ ) -> dict:+ client: dict = {"clientCustomer": f"customers/{customer_id}", "descriptiveName": name, "status": status}+ # Google's REST responses omit proto3 defaults, so level 0 and manager=false are absent.+ if level is not None:+ client["level"] = level+ if manager:+ client["manager"] = True+ return {"customerClient": client}++ @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")+ @patch("posthog.models.integration.google_ads.requests.request")+ def test_accessible_accounts_reads_every_search_stream_chunk(self, mock_request):+ accessible = MagicMock(status_code=200)+ accessible.json.return_value = {"resourceNames": ["customers/6501924158"]}+ # searchStream's REST body is an array of batches; a large hierarchy spans several.+ stream = MagicMock(status_code=200)+ stream.json.return_value = [+ {"results": [self._customer_client("6501924158", "Acme Corp", manager=True)]},+ {"results": [self._customer_client("1234567890", "Client One", level="1")]},+ ]+ mock_request.side_effect = [accessible, stream]++ accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()++ assert [account["id"] for account in accounts] == ["6501924158", "1234567890"]+ assert accounts[0]["manager"] is True+ assert accounts[1]["parent_id"] == "6501924158"++ @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")+ @patch("posthog.models.integration.google_ads.requests.request")+ def test_accessible_accounts_dedupes_an_account_reachable_from_two_roots(self, mock_request):+ # A user with direct access to both a manager and one of its clients gets both in+ # `resourceNames`, so the client is walked twice: once as a root (level absent, i.e. 0) and once+ # under the manager (level "1"). Those two levels must be compared as numbers — comparing the raw+ # values raises TypeError (None vs "1") and 500s the picker.+ accessible = MagicMock(status_code=200)+ accessible.json.return_value = {"resourceNames": ["customers/1234567890", "customers/6501924158"]}+ client_walk = MagicMock(status_code=200)+ client_walk.json.return_value = [{"results": [self._customer_client("1234567890", "Client One")]}]+ manager_walk = MagicMock(status_code=200)+ manager_walk.json.return_value = [+ {+ "results": [+ self._customer_client("6501924158", "Acme Corp", manager=True),+ self._customer_client("1234567890", "Client One", level="1"),+ ]+ }+ ]+ mock_request.side_effect = [accessible, client_walk, manager_walk]++ accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()++ # The client is kept once, at its shallowest sighting: reachable directly, so it needs no manager+ # to log in as.+ assert [account["id"] for account in accounts] == ["1234567890", "6501924158"]+ assert accounts[0]["level"] is None+ assert accounts[0]["parent_id"] == "1234567890"++ @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")+ @patch("posthog.models.integration.google_ads.requests.request")+ def test_accessible_accounts_keeps_enabled_sighting_when_shallower_root_is_disabled(self, mock_request):+ # The same client is reachable enabled under a manager (level "1") and directly as a disabled root+ # (level 0). The enabled path is walked first and kept; the disabled shallower root must not evict+ # it — otherwise the account vanishes from the picker even though Google returned an enabled path.+ accessible = MagicMock(status_code=200)+ accessible.json.return_value = {"resourceNames": ["customers/6501924158", "customers/1234567890"]}+ manager_walk = MagicMock(status_code=200)+ manager_walk.json.return_value = [+ {+ "results": [+ self._customer_client("6501924158", "Acme Corp", manager=True),+ self._customer_client("1234567890", "Client One", level="1"),+ ]+ }+ ]+ disabled_root_walk = MagicMock(status_code=200)+ disabled_root_walk.json.return_value = [+ {"results": [self._customer_client("1234567890", "Client One", status="DISABLED")]}+ ]+ mock_request.side_effect = [accessible, manager_walk, disabled_root_walk]++ accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()++ client = next(account for account in accounts if account["id"] == "1234567890")+ assert client["level"] == "1"+ assert client["parent_id"] == "6501924158"++ @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")+ @patch("posthog.models.integration.google_ads.requests.request")+ def test_accessible_accounts_empty_when_login_has_no_accessible_customers(self, mock_request):+ # A Google login with no accessible Ads accounts gets a 200 with an empty body, so `resourceNames`+ # is absent rather than an empty list — this must yield no accounts, not raise KeyError.+ accessible = MagicMock(status_code=200)+ accessible.json.return_value = {}+ mock_request.return_value = accessible++ accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()++ assert accounts == []++ @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")+ @patch("tenacity.nap.time.sleep")+ @patch("posthog.models.integration.google_ads.requests.request")+ def test_accessible_accounts_rides_out_one_transient_read_timeout(self, mock_request, mock_sleep):+ # The walk is a chain of sequential requests; a single timed-out request used to fail the whole+ # walk. It must instead be retried once and succeed.+ accessible = MagicMock(status_code=200)+ accessible.json.return_value = {"resourceNames": ["customers/6501924158"]}+ stream = MagicMock(status_code=200)+ stream.json.return_value = [{"results": [self._customer_client("1234567890", "Client One", level="1")]}]+ mock_request.side_effect = [accessible, requests.exceptions.ReadTimeout("read timed out"), stream]++ accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()++ assert [account["id"] for account in accounts] == ["1234567890"]++ @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")+ @patch("tenacity.nap.time.sleep")+ @patch("posthog.models.integration.google_ads.requests.request")+ def test_accessible_accounts_raises_after_repeated_read_timeouts(self, mock_request, mock_sleep):+ # Retries must be bounded: a persistently unreachable endpoint should still fail rather than+ # retry forever or get silently swallowed.+ mock_request.side_effect = requests.exceptions.ReadTimeout("read timed out")++ with pytest.raises(requests.exceptions.ReadTimeout):+ GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()++ assert mock_request.call_count == 3diff --git a/posthog/models/test/integration/test_google_cloud.py b/posthog/models/test/integration/test_google_cloud.pynew file mode 100644index 000000000000..fb40f119079d--- /dev/null+++ b/posthog/models/test/integration/test_google_cloud.py@@ -0,0 +1,219 @@+"""Tests for the Google Cloud service-account and Pub/Sub / Cloud Storage integrations."""++import time+from datetime import datetime+from typing import Optional++import pytest+from freezegun import freeze_time+from posthog.test.base import BaseTest+from unittest.mock import patch++from rest_framework.exceptions import ValidationError++from posthog.models.integration import GoogleCloudIntegration, GoogleCloudServiceAccountIntegration, Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team+++class TestGoogleCloudIntegrationModel(BaseTest):+ mock_keyfile = {+ "type": "service_account",+ "project_id": "posthog-616",+ "private_key_id": "df3e129a722a865cc3539b4e69507bad",+ "private_key": "-----BEGIN PRIVATE KEY-----\nTHISISTHEKEY==\n-----END PRIVATE KEY-----\n",+ "client_email": "[email protected]",+ "client_id": "11223344556677889900",+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",+ "token_uri": "https://oauth2.googleapis.com/token",+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/not-a-topic%40posthog-616.iam.gserviceaccount.com",+ "universe_domain": "googleapis.com",+ }++ def create_integration(+ self, kind: str, config: Optional[dict] = None, sensitive_config: Optional[dict] = None+ ) -> Integration:+ _config = {"refreshed_at": int(time.time()), "expires_in": 3600}+ _sensitive_config = self.mock_keyfile+ _config.update(config or {})+ _sensitive_config.update(sensitive_config or {})++ return Integration.objects.create(team=self.team, kind=kind, config=_config, sensitive_config=_sensitive_config)++ @patch("google.oauth2.service_account.Credentials.from_service_account_info")+ def test_integration_from_key(self, mock_credentials):+ mock_credentials.return_value.project_id = "posthog-616"+ mock_credentials.return_value.service_account_email = "posthog@"+ mock_credentials.return_value.token = "ACCESS_TOKEN"+ mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)+ mock_credentials.return_value.refresh = lambda _: None++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = GoogleCloudIntegration.integration_from_key(+ "google-pubsub",+ self.mock_keyfile,+ self.team.id,+ self.user,+ )++ assert integration.team == self.team+ assert integration.created_by == self.user++ assert integration.config == {+ "refreshed_at": 1704110400,+ "expires_in": 3600,+ }+ assert integration.sensitive_config == {+ "key_info": self.mock_keyfile,+ "access_token": "ACCESS_TOKEN",+ }++ @patch("google.oauth2.service_account.Credentials.from_service_account_info")+ def test_integration_refresh_token(self, mock_credentials):+ mock_credentials.return_value.project_id = "posthog-616"+ mock_credentials.return_value.service_account_email = "posthog@"+ mock_credentials.return_value.token = "ACCESS_TOKEN"+ mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)+ mock_credentials.return_value.refresh = lambda _: None++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = GoogleCloudIntegration.integration_from_key(+ "google-pubsub",+ self.mock_keyfile,+ self.team.id,+ self.user,+ )++ with freeze_time("2024-01-01T12:00:00Z"):+ assert GoogleCloudIntegration(integration).access_token_expired() is False++ with freeze_time("2024-01-01T14:00:00Z"):+ assert GoogleCloudIntegration(integration).access_token_expired() is True++ mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600 * 3)++ GoogleCloudIntegration(integration).refresh_access_token()+ assert GoogleCloudIntegration(integration).access_token_expired() is False++ assert integration.config == {+ "refreshed_at": 1704110400 + 3600 * 2,+ "expires_in": 3600,+ }+ assert integration.sensitive_config["access_token"] == "ACCESS_TOKEN"++ # Verify refresh used the nested key_info, not the whole sensitive_config+ refresh_call = mock_credentials.call_args_list[-1]+ assert refresh_call[0][0] == self.mock_keyfile++ @patch("google.oauth2.service_account.Credentials.from_service_account_info")+ def test_refresh_token_fallback_pre_migration_sensitive_config(self, mock_credentials):+ """Pre-migration integrations store key_info directly in sensitive_config (not nested under 'key_info').+ The refresh logic should fall back to using the entire sensitive_config as key_info."""+ mock_credentials.return_value.project_id = "posthog-616"+ mock_credentials.return_value.service_account_email = "posthog@"+ mock_credentials.return_value.token = "REFRESHED_TOKEN"+ mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)+ mock_credentials.return_value.refresh = lambda _: None++ # Simulate pre-migration state: key_info stored directly as sensitive_config,+ # access_token in config+ integration = Integration.objects.create(+ team=self.team,+ kind="google-pubsub",+ integration_id="posthog@",+ config={+ "refreshed_at": 1704110400,+ "expires_in": 1,+ "access_token": "OLD_TOKEN",+ },+ sensitive_config=self.mock_keyfile,+ )++ with freeze_time("2024-01-01T14:00:00Z"):+ GoogleCloudIntegration(integration).refresh_access_token()++ # After refresh, sensitive_config should be migrated to the nested structure+ assert integration.sensitive_config == {+ "key_info": self.mock_keyfile,+ "access_token": "REFRESHED_TOKEN",+ }+ assert "access_token" not in integration.config++ # Verify refresh used the whole sensitive_config as key_info (pre-migration fallback)+ assert mock_credentials.call_args[0][0] == self.mock_keyfile++ @patch("google.oauth2.service_account.Credentials.from_service_account_info")+ def test_get_access_token_reads_from_sensitive_config(self, mock_credentials):+ mock_credentials.return_value.project_id = "posthog-616"+ mock_credentials.return_value.service_account_email = "posthog@"+ mock_credentials.return_value.token = "ACCESS_TOKEN"+ mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)+ mock_credentials.return_value.refresh = lambda _: None++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = GoogleCloudIntegration.integration_from_key(+ "google-pubsub",+ self.mock_keyfile,+ self.team.id,+ self.user,+ )++ with freeze_time("2024-01-01T12:00:00Z"):+ token = GoogleCloudIntegration(integration).get_access_token()++ assert token == "ACCESS_TOKEN"+ assert "access_token" not in integration.config+++class TestGoogleCloudServiceAccountIntegration(BaseTest):+ def test_raises_on_duplicate_service_account_email(self):+ _ = GoogleCloudServiceAccountIntegration.integration_from_service_account(+ team_id=self.team.pk,+ organization_id=str(self.team.organization.id),+ service_account_email="[email protected]",+ project_id="test",+ )+ with pytest.raises(ValidationError):+ _ = GoogleCloudServiceAccountIntegration.integration_from_service_account(+ team_id=self.team.pk + 1,+ organization_id="a-different-org",+ service_account_email="[email protected]",+ project_id="test",+ )++ def test_allows_duplicate_service_account_email_when_using_key(self):+ key_file_integration = GoogleCloudServiceAccountIntegration.integration_from_service_account(+ team_id=self.team.pk,+ organization_id=str(self.team.organization.id),+ service_account_email="[email protected]",+ project_id="test",+ private_key="something",+ private_key_id="something",+ token_uri="something",+ )++ other_org = Organization.objects.create(name="other org")+ other_team = Team.objects.create(organization=other_org, name="other team")+ new_impersonated_integration = GoogleCloudServiceAccountIntegration.integration_from_service_account(+ team_id=other_team.id,+ organization_id=other_org.id,+ service_account_email="[email protected]",+ project_id="test",+ )++ new_key_file_integration = GoogleCloudServiceAccountIntegration.integration_from_service_account(+ team_id=other_team.pk,+ organization_id=other_org.id,+ service_account_email="[email protected]",+ project_id="test",+ private_key="something",+ private_key_id="something",+ token_uri="something",+ )++ assert (+ GoogleCloudServiceAccountIntegration(key_file_integration).service_account_email+ == GoogleCloudServiceAccountIntegration(new_impersonated_integration).service_account_email+ == GoogleCloudServiceAccountIntegration(new_key_file_integration).service_account_email+ )diff --git a/posthog/models/test/integration/test_jira.py b/posthog/models/test/integration/test_jira.pynew file mode 100644index 000000000000..f9f528d12c49--- /dev/null+++ b/posthog/models/test/integration/test_jira.py@@ -0,0 +1,72 @@+"""Tests for the Jira integration."""++import pytest+from unittest.mock import MagicMock, patch++from rest_framework.exceptions import ValidationError++from posthog.models.integration import Integration, JiraIntegration+++class TestJiraIntegrationModel:+ @staticmethod+ def integration() -> MagicMock:+ return MagicMock(+ id=123,+ team_id=456,+ kind=Integration.IntegrationKind.JIRA,+ config={"cloud_id": "cloud-id"},+ sensitive_config={"access_token": "access-token"},+ )++ @patch("posthog.models.integration.jira.capture_exception")+ @patch("posthog.models.integration.jira.requests.post")+ def test_create_issue_captures_structured_error_details(self, mock_post, mock_capture_exception):+ mock_post.return_value.status_code = 400+ mock_post.return_value.headers = {"Content-Type": "application/json"}+ mock_post.return_value.json.return_value = {+ "errorMessages": ["Issue type is not available"],+ "errors": {"summary": "Summary is required"},+ }++ with pytest.raises(ValidationError) as error:+ JiraIntegration(self.integration()).create_issue(+ {"project_key": "ENG", "title": "Checkout failed", "description": "Details"}+ )++ assert error.value.args[0] == (+ "Could not create the Jira issue. Check the project's issue settings and try again."+ )+ captured_error = mock_capture_exception.call_args.args[0]+ assert str(captured_error) == "Jira issue creation failed"+ assert mock_capture_exception.call_args.kwargs["additional_properties"] == {+ "jira_status_code": 400,+ "jira_response_content_type": "application/json",+ "integration_id": 123,+ "team_id": 456,+ "jira_error_messages": ["Issue type is not available"],+ "jira_field_errors": {"summary": "Summary is required"},+ "jira_response_keys": ["errorMessages", "errors"],+ }++ @patch("posthog.models.integration.jira.capture_exception")+ @patch("posthog.models.integration.jira.requests.post")+ def test_create_issue_captures_non_json_response_metadata(self, mock_post, mock_capture_exception):+ mock_post.return_value.status_code = 502+ mock_post.return_value.headers = {"Content-Type": "text/html"}+ mock_post.return_value.json.side_effect = ValueError++ with pytest.raises(ValidationError) as error:+ JiraIntegration(self.integration()).create_issue(+ {"project_key": "ENG", "title": "Checkout failed", "description": "Details"}+ )++ assert error.value.args[0] == (+ "Could not create the Jira issue. Check the project's issue settings and try again."+ )+ assert mock_capture_exception.call_args.kwargs["additional_properties"] == {+ "jira_status_code": 502,+ "jira_response_content_type": "text/html",+ "integration_id": 123,+ "team_id": 456,+ }diff --git a/posthog/models/test/integration/test_linear.py b/posthog/models/test/integration/test_linear.pynew file mode 100644index 000000000000..0f352f76a946--- /dev/null+++ b/posthog/models/test/integration/test_linear.py@@ -0,0 +1,109 @@+"""Tests for the Linear integration."""++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from posthog.models.integration import Integration, LinearIntegration+++class TestLinearIntegrationModel(BaseTest):+ def create_integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="linear",+ config={"data": {"viewer": {"organization": {"urlKey": "posthog"}}}},+ sensitive_config={"access_token": "ACCESS_TOKEN"},+ )++ def test_search_issues_raises_on_graphql_errors(self):+ # An expired token or GraphQL error must not be reported as a valid empty result.+ linear = LinearIntegration(self.create_integration())+ with patch.object(linear, "query", return_value={"errors": [{"message": "unauthorized"}]}):+ with self.assertRaises(ValidationError):+ linear.search_issues("boom")++ @parameterized.expand(+ [+ ("top_level_errors", {"errors": [{"message": "forbidden"}]}),+ ("mutation_failure", {"data": {"attachmentCreate": {"success": False}}}),+ ]+ )+ def test_create_attachment_raises_on_failure(self, _name, response_body):+ # Linear reports failures in a 200 body; treating them as success would let callers+ # persist references whose promised back-link was never created.+ linear = LinearIntegration(self.create_integration())+ with patch.object(linear, "query", return_value=response_body):+ with self.assertRaises(ValidationError):+ linear.create_attachment("LIN-123", "https://us.posthog.com/error_tracking/issue-id")++ def test_create_issue_raises_when_issue_creation_fails(self):+ # A failed issueCreate must not fall through to an attachment attempt and a+ # persisted {"id": None} reference.+ linear = LinearIntegration(self.create_integration())+ with patch.object(linear, "query", return_value={"errors": [{"message": "forbidden"}]}) as mock_query:+ with self.assertRaises(ValidationError):+ linear.create_issue(+ "https://us.posthog.com/error_tracking/issue-id",+ {"team_id": "team-id", "title": "Title", "description": "Description"},+ )+ assert mock_query.call_count == 1++ def test_create_issue_succeeds_when_attachment_fails(self):+ # The Linear issue already exists when the attachment fires, so a failed back-link+ # must not fail the create (retrying would duplicate the issue).+ linear = LinearIntegration(self.create_integration())+ with patch.object(+ linear,+ "query",+ side_effect=[+ {"data": {"issueCreate": {"issue": {"identifier": "LIN-123"}}}},+ {"errors": [{"message": "rate limited"}]},+ ],+ ):+ result = linear.create_issue(+ "https://us.posthog.com/error_tracking/issue-id",+ {"team_id": "team-id", "title": "Title", "description": "Description"},+ )++ assert result == {"id": "LIN-123"}++ def test_create_issue_passes_user_fields_as_graphql_variables(self):+ linear = LinearIntegration(self.create_integration())+ with patch.object(+ linear,+ "query",+ side_effect=[+ {"data": {"issueCreate": {"issue": {"identifier": "LIN-123"}}}},+ {"data": {"attachmentCreate": {"success": True}}},+ ],+ ) as mock_query:+ attachment_url = f'https://us.posthog.com/project/{self.team.id}/error_tracking/issue-id" }} mutation {{'+ result = linear.create_issue(+ attachment_url,+ {+ "team_id": 'team-id" } mutation {',+ "title": 'Title "quoted"',+ "description": "Description",+ },+ )++ assert result == {"id": "LIN-123"}+ issue_query = mock_query.call_args_list[0].args[0]+ issue_variables = mock_query.call_args_list[0].kwargs["variables"]+ attachment_query = mock_query.call_args_list[1].args[0]+ attachment_variables = mock_query.call_args_list[1].kwargs["variables"]++ assert 'team-id" } mutation {' not in issue_query+ assert 'Title "quoted"' not in issue_query+ assert issue_variables == {+ "title": 'Title "quoted"',+ "description": "Description",+ "teamId": 'team-id" } mutation {',+ }+ assert 'issue-id" } mutation {' not in attachment_query+ assert attachment_variables["issueId"] == "LIN-123"+ assert attachment_variables["title"] == "PostHog issue"+ assert attachment_variables["url"].endswith(f'/project/{self.team.id}/error_tracking/issue-id" }} mutation {{')diff --git a/posthog/models/test/integration/test_meta.py b/posthog/models/test/integration/test_meta.pynew file mode 100644index 000000000000..d2a50f45a7e3--- /dev/null+++ b/posthog/models/test/integration/test_meta.py@@ -0,0 +1,72 @@+"""Tests for the Meta Graph API integrations."""++import time++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.test import override_settings++from posthog.models.integration import InstagramIntegration, Integration, OauthIntegration+++@override_settings(INSTAGRAM_APP_CLIENT_ID="instagram-client-id", INSTAGRAM_APP_CLIENT_SECRET="instagram-client-secret")+class TestInstagramIntegrationModel(BaseTest):+ def test_oauth_config(self):+ config = OauthIntegration.oauth_config_for_kind("instagram")++ # Same Graph version as the other Meta kinds: an older pin here makes the OAuth dialog+ # reject the permission set before anyone reaches a consent screen.+ assert config.authorize_url == "https://www.facebook.com/v25.0/dialog/oauth"+ assert config.token_url == "https://graph.facebook.com/v25.0/oauth/access_token"+ assert config.token_info_url == "https://graph.facebook.com/v25.0/me"+ assert config.client_id == "instagram-client-id"+ assert config.client_secret == "instagram-client-secret"+ assert config.id_path == "id"+ assert config.name_path == "name"+ # Instagram is reached through the Facebook page it is linked to, so the page scopes+ # are as load-bearing as the Instagram ones.+ assert set(config.scope.split(" ")) == {+ "instagram_business_basic",+ "instagram_business_manage_insights",+ "instagram_business_manage_comments",+ "pages_show_list",+ "pages_read_engagement",+ }++ @override_settings(INSTAGRAM_APP_CLIENT_ID="", INSTAGRAM_APP_CLIENT_SECRET="")+ def test_oauth_config_unconfigured_raises(self):+ with pytest.raises(NotImplementedError, match="Instagram app not configured"):+ OauthIntegration.oauth_config_for_kind("instagram")++ def test_the_instagram_grant_is_separate_from_the_meta_ads_one(self):+ # Both ride the same Meta app, but an ads grant carries none of the Instagram scopes,+ # so pointing the Instagram source at a meta-ads integration must not be possible.+ integration = Integration.objects.create(team=self.team, kind="meta-ads", integration_id="1")++ with pytest.raises(Exception, match="wrong 'kind'"):+ InstagramIntegration(integration)++ @patch("posthog.models.integration.meta.requests.post")+ def test_refresh_exchanges_the_long_lived_token_rather_than_a_refresh_token(self, mock_post):+ # Meta issues no refresh token: the current access token is swapped for a fresh one.+ integration = Integration.objects.create(+ team=self.team,+ kind="instagram",+ integration_id="fb-user-1",+ config={"expires_in": 100, "refreshed_at": int(time.time()) - 90},+ sensitive_config={"access_token": "old-token"},+ )+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"access_token": "new-token", "expires_in": 5184000}++ InstagramIntegration(integration).refresh_access_token()++ sent = mock_post.call_args.kwargs["data"]+ assert sent["grant_type"] == "fb_exchange_token"+ assert sent["fb_exchange_token"] == "old-token"+ assert sent["client_id"] == "instagram-client-id"+ integration.refresh_from_db()+ assert integration.sensitive_config["access_token"] == "new-token"+ assert integration.errors == ""diff --git a/posthog/models/test/integration/test_model.py b/posthog/models/test/integration/test_model.pynew file mode 100644index 000000000000..71efff5c7f3b--- /dev/null+++ b/posthog/models/test/integration/test_model.py@@ -0,0 +1,194 @@+"""Tests for the Integration model: encryption, display_name dispatch."""++import json+import time+from typing import Optional, cast++import pytest+from freezegun import freeze_time+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.db import connection+from django.test import override_settings++from parameterized import parameterized++from posthog.helpers.encrypted_fields import EncryptedJSONField+from posthog.models.instance_setting import set_instance_setting+from posthog.models.integration import Integration, SlackIntegration, UndecryptedIntegrationSecretError+++def get_db_field_value(field, model_id):+ cursor = connection.cursor()+ cursor.execute(f"select {field} from posthog_integration where id='{model_id}';")+ return cursor.fetchone()[0]+++def update_db_field_value(field, model_id, value):+ cursor = connection.cursor()+ cursor.execute(f"update posthog_integration set {field}='{value}' where id='{model_id}';")+++class TestIntegrationModel(BaseTest):+ def create_integration(+ self, kind: str, config: Optional[dict] = None, sensitive_config: Optional[dict] = None+ ) -> Integration:+ _config = {"refreshed_at": int(time.time()), "expires_in": 3600}+ _sensitive_config = {"refresh_token": "REFRESH", "id_token": None}+ _config.update(config or {})+ _sensitive_config.update(sensitive_config or {})++ return Integration.objects.create(team=self.team, kind=kind, config=_config, sensitive_config=_sensitive_config)++ def test_sensitive_config_encrypted(self):+ # Fernet encryption is deterministic, but has a temporal component and utilizes os.urandom() for the IV+ with freeze_time("2024-01-01T00:01:00Z"):+ with patch("os.urandom", return_value=b"\x00" * 16):+ integration = self.create_integration("slack")++ assert integration.sensitive_config == {"refresh_token": "REFRESH", "id_token": None}+ assert (+ get_db_field_value("sensitive_config", integration.id)+ == '{"id_token": null, "refresh_token": "gAAAAABlkgC8AAAAAAAAAAAAAAAAAAAAAJgmFh-MNX9haUNHNfYLvULI6vSRYVd3o8xd4f8xBkWEWAa5RJ2ikOM2dsW5_9F7Mw=="}'+ )++ # update the value to non-encrypted and check it still loads++ update_db_field_value(+ "sensitive_config", integration.id, '{"id_token": null, "refresh_token": "REFRESH2"}'+ )+ integration.refresh_from_db()+ assert integration.sensitive_config == {"id_token": None, "refresh_token": "REFRESH2"}+ assert (+ get_db_field_value("sensitive_config", integration.id)+ == '{"id_token": null, "refresh_token": "REFRESH2"}'+ )++ integration.save()+ # The field should now be encrypted+ assert integration.sensitive_config == {"id_token": None, "refresh_token": "REFRESH2"}+ assert (+ get_db_field_value("sensitive_config", integration.id)+ == '{"id_token": null, "refresh_token": "gAAAAABlkgC8AAAAAAAAAAAAAAAAAAAAAHlWz9QOMnXDvmix-z5lNG4v0VcO9lGWejmcE_BXHXPZ1wNkb-38JupntWbshBrfFQ=="}'+ )++ @parameterized.expand([("access_token",), ("refresh_token",)])+ def test_oauth_token_property_raises_if_still_encrypted(self, field_name: str) -> None:+ # `sensitive_config` uses `ignore_decrypt_errors=True`, so a value that fails to decrypt+ # under every configured key comes back as raw Fernet ciphertext instead of raising. If the+ # `access_token`/`refresh_token` properties didn't check for that, this ciphertext would+ # get sent straight to the third-party API as the live credential.+ integration = Integration(team=self.team, kind="stripe", sensitive_config={field_name: "gAAAAABleftover=="})+ with pytest.raises(UndecryptedIntegrationSecretError):+ getattr(integration, field_name)++ @parameterized.expand([("access_token",), ("refresh_token",)])+ def test_oauth_token_property_passes_through_decrypted_value(self, field_name: str) -> None:+ integration = Integration(team=self.team, kind="stripe", sensitive_config={field_name: "a-real-token"})+ assert getattr(integration, field_name) == "a-real-token"++ @parameterized.expand([("access_token",), ("refresh_token",)])+ def test_oauth_token_property_recovers_an_over_encrypted_value(self, field_name: str) -> None:+ # Saving an integration whose secret failed to decrypt re-encrypts the ciphertext, so the+ # stored value ends up with an extra layer and one decrypt still leaves ciphertext behind.+ # The secret is intact underneath, so the connection must keep working.+ integration = self.create_integration("stripe", sensitive_config={field_name: "a-real-token"})+ field = cast(EncryptedJSONField, Integration._meta.get_field("sensitive_config")) # type: ignore[misc]+ stored = json.loads(get_db_field_value("sensitive_config", integration.id))+ update_db_field_value(+ "sensitive_config",+ integration.id,+ json.dumps({**stored, field_name: field.encrypt(stored[field_name])}),+ )++ integration.refresh_from_db()++ assert getattr(integration, field_name) == "a-real-token"++ def test_slack_integration_config(self):+ set_instance_setting("SLACK_APP_CLIENT_ID", None)+ set_instance_setting("SLACK_APP_CLIENT_SECRET", None)+ set_instance_setting("SLACK_APP_SIGNING_SECRET", None)++ assert not SlackIntegration.slack_config() == {}++ set_instance_setting("SLACK_APP_CLIENT_ID", "client-id")+ set_instance_setting("SLACK_APP_CLIENT_SECRET", "client-secret")+ set_instance_setting("SLACK_APP_SIGNING_SECRET", "not-so-secret")++ assert SlackIntegration.slack_config() == {+ "SLACK_APP_CLIENT_ID": "client-id",+ "SLACK_APP_CLIENT_SECRET": "client-secret",+ "SLACK_APP_SIGNING_SECRET": "not-so-secret",+ }+++class TestPinterestAdsIntegrationDisplayName(BaseTest):+ @parameterized.expand(+ [+ (+ "business",+ {"id": "1", "username": "13x6ppss87fecv1q790xh1orhyp9th", "business_name": "Posthog Inc"},+ "Posthog Inc",+ ),+ ("personal", {"id": "1", "username": "javierposthog", "business_name": ""}, "javierposthog"),+ # Older connections predate business_name being stored.+ ("legacy", {"id": "1", "username": "javierposthog"}, "javierposthog"),+ ]+ )+ def test_display_name_prefers_business_name(self, _name: str, config: dict, expected: str) -> None:+ integration = Integration.objects.create(+ team=self.team,+ kind="pinterest-ads",+ config=config,+ integration_id=config["id"],+ )+ assert integration.display_name == expected+++class TestTikTokAdsIntegrationDisplayName(BaseTest):+ @parameterized.expand(+ [+ (+ "email_wins_over_display_name",+ {+ "advertiser_ids": ["7554133187111469074"],+ "user_email": "e***[email protected]",+ "user_display_name": "user1140434302514",+ },+ "e***[email protected]",+ ),+ ("neither_fetched_falls_back_to_id", {"advertiser_ids": ["7554133187111469074"]}, "7554133187111469074"),+ ]+ )+ def test_display_name_prefers_user_email(self, _name: str, config: dict, expected: str) -> None:+ integration = Integration.objects.create(+ team=self.team,+ kind="tiktok-ads",+ config=config,+ integration_id=",".join(config["advertiser_ids"]),+ )+ assert integration.display_name == expected+++@override_settings(REDDIT_ADS_CLIENT_ID="reddit-client-id", REDDIT_ADS_CLIENT_SECRET="reddit-client-secret")+class TestRedditAdsIntegrationDisplayName(BaseTest):+ @parameterized.expand(+ [+ (+ "username",+ {"reddit_user_id": "t2_1tqubocxl4", "data.reddit_username": "javierposthog"},+ "javierposthog",+ ),+ ("legacy", {"reddit_user_id": "t2_1tqubocxl4"}, "t2_1tqubocxl4"),+ ]+ )+ def test_display_name_prefers_username(self, _name: str, config: dict, expected: str) -> None:+ integration = Integration.objects.create(+ team=self.team,+ kind="reddit-ads",+ config=config,+ integration_id=config["reddit_user_id"],+ )+ assert integration.display_name == expecteddiff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.pynew file mode 100644index 000000000000..a260a3fa2a6f--- /dev/null+++ b/posthog/models/test/integration/test_oauth.py@@ -0,0 +1,1584 @@+"""Tests for the generic OAuth connect/refresh dispatcher, including kinds with no dedicated business-logic class (Resend, Pardot, YouTube Analytics, PostHog connect)."""++import json+import time+import base64+import hashlib+from datetime import datetime, timedelta+from typing import Optional+from urllib.parse import parse_qs, urlencode++import pytest+from freezegun import freeze_time+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.core.cache import cache+from django.db import connection+from django.test import override_settings++import requests+from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from posthog.models.integration import (+ CONFIG_LEGACY_OAUTH_CLIENT,+ POSTHOG_CONNECT_DEFAULT_SCOPES,+ POSTHOG_CONNECT_IDENTITY_SCOPES,+ Integration,+ OauthIntegration,+ oauth_refresh_failure_reason,+ oauth_refresh_terminal_counter,+ refresh_backoff_active,+)+++def get_db_field_value(field, model_id):+ cursor = connection.cursor()+ cursor.execute(f"select {field} from posthog_integration where id='{model_id}';")+ return cursor.fetchone()[0]+++def test_slack_oauth_requests_the_recently_approved_scopes_on_every_instance():+ # These waited on Slack app-directory review and were only requested on DEV/local. They're+ # approved now, so every instance asks for them — the features behind them (DM assistant,+ # canvas and file artifact delivery, inbox channel creation) are dark without them.+ from posthog.models.integration import POSTHOG_SLACK_SCOPE++ requested = set(POSTHOG_SLACK_SCOPE.split(","))++ assert {"assistant:write", "im:history", "canvases:write", "files:write", "channels:manage"} <= requested+++class TestOauthIntegrationModel(BaseTest):+ mock_settings = {+ "SALESFORCE_CONSUMER_KEY": "salesforce-client-id",+ "SALESFORCE_CONSUMER_SECRET": "salesforce-client-secret",+ "HUBSPOT_APP_CLIENT_ID": "hubspot-client-id",+ "HUBSPOT_APP_CLIENT_SECRET": "hubspot-client-secret",+ "GOOGLE_ADS_APP_CLIENT_ID": "google-client-id",+ "GOOGLE_ADS_APP_CLIENT_SECRET": "google-client-secret",+ "GOOGLE_CALENDAR_APP_CLIENT_ID": "google-calendar-client-id",+ "GOOGLE_CALENDAR_APP_CLIENT_SECRET": "google-calendar-client-secret",+ "LINKEDIN_APP_CLIENT_ID": "linkedin-client-id",+ "LINKEDIN_APP_CLIENT_SECRET": "linkedin-client-secret",+ "TIKTOK_ADS_CLIENT_ID": "tiktok-app-id",+ "TIKTOK_ADS_CLIENT_SECRET": "tiktok-secret",+ }++ def create_integration(+ self, kind: str, config: Optional[dict] = None, sensitive_config: Optional[dict] = None+ ) -> Integration:+ _config = {"refreshed_at": int(time.time()), "expires_in": 3600}+ _sensitive_config = {"refresh_token": "REFRESH"}+ _config.update(config or {})+ _sensitive_config.update(sensitive_config or {})++ return Integration.objects.create(team=self.team, kind=kind, config=_config, sensitive_config=_sensitive_config)++ def test_authorize_url_raises_if_not_configured(self):+ with pytest.raises(NotImplementedError):+ OauthIntegration.authorize_url("salesforce", token="state_token", next="/projects/test")++ def test_authorize_url(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url("salesforce", token="state_token", next="/projects/test")+ base, _, query = url.partition("?")+ params = {k: v[0] for k, v in parse_qs(query).items()}+ assert base == "https://login.salesforce.com/services/oauth2/authorize"+ assert params == {+ "client_id": "salesforce-client-id",+ "scope": "full refresh_token",+ "redirect_uri": "https://localhost:8010/integrations/salesforce/callback",+ "response_type": "code",+ "state": "next=%2Fprojects%2Ftest&token=state_token",+ "code_challenge": params["code_challenge"],+ "code_challenge_method": "S256",+ }++ def test_authorize_url_carries_initiating_team_id_in_state(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url(+ "salesforce", token="state_token", next="/projects/test", team_id=228502+ )+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}+ state = {k: v[0] for k, v in parse_qs(params["state"]).items()}+ assert state["team_id"] == "228502"++ def test_authorize_url_omits_team_id_when_not_provided(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url("salesforce", token="state_token", next="/projects/test")+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}+ assert "team_id" not in parse_qs(params["state"])++ def test_authorize_url_pkce_challenge_matches_cached_verifier(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url("salesforce", token="pkce_state_token", next="/projects/test")+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}+ verifier = cache.get("oauth_pkce_verifier/pkce_state_token")+ assert verifier+ expected_challenge = (+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()+ )+ assert params["code_challenge"] == expected_challenge++ def test_authorize_url_without_pkce_has_no_challenge(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url("hubspot", token="no_pkce_state_token", next="/projects/test")+ assert "code_challenge" not in url+ assert cache.get("oauth_pkce_verifier/no_pkce_state_token") is None++ def test_authorize_url_with_additional_authorize_params(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url("google-ads", token="state_token", next="/projects/test")+ assert (+ url+ == "https://accounts.google.com/o/oauth2/v2/auth?client_id=google-client-id&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fadwords+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&redirect_uri=https%3A%2F%2Flocalhost%3A8010%2Fintegrations%2Fgoogle-ads%2Fcallback&response_type=code&state=next%3D%252Fprojects%252Ftest%26token%3Dstate_token&access_type=offline&prompt=consent"+ )++ def test_authorize_url_google_calendar(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url("google-calendar", token="state_token", next="/projects/test")+ assert (+ url+ == "https://accounts.google.com/o/oauth2/v2/auth?client_id=google-calendar-client-id&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&redirect_uri=https%3A%2F%2Flocalhost%3A8010%2Fintegrations%2Fgoogle-calendar%2Fcallback&response_type=code&state=next%3D%252Fprojects%252Ftest%26token%3Dstate_token&access_type=offline&prompt=consent"+ )++ @patch("posthog.models.integration.oauth.requests.post")+ def test_integration_from_oauth_response(self, mock_post):+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "FAKES_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "instance_url": "https://fake.salesforce.com",+ "expires_in": 3600,+ }++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = OauthIntegration.integration_from_oauth_response(+ "salesforce",+ self.team.id,+ self.user,+ {+ "code": "code",+ "state": "next=/projects/test",+ },+ )++ assert integration.team == self.team+ assert integration.created_by == self.user++ assert integration.config == {+ "instance_url": "https://fake.salesforce.com",+ "refreshed_at": 1704110400,+ "expires_in": 3600,+ }+ assert integration.sensitive_config == {+ "access_token": "FAKES_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "id_token": None,+ }++ @patch("posthog.models.integration.oauth.requests.post")+ def test_integration_from_oauth_response_sends_pkce_verifier(self, mock_post):+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "FAKES_ACCESS_TOKEN",+ "instance_url": "https://fake.salesforce.com",+ "expires_in": 3600,+ }++ # authorize_url caches the verifier; the exchange must send that exact value and consume it+ url = OauthIntegration.authorize_url("salesforce", token="exchange_state_token", next="/projects/test")+ challenge = parse_qs(url.partition("?")[2])["code_challenge"][0]+ verifier = cache.get("oauth_pkce_verifier/exchange_state_token")++ OauthIntegration.integration_from_oauth_response(+ "salesforce",+ self.team.id,+ self.user,+ {"code": "code", "state": "next=%2Fprojects%2Ftest&token=exchange_state_token"},+ )++ sent = mock_post.call_args.kwargs["data"]+ assert sent["code_verifier"] == verifier+ assert (+ base64.urlsafe_b64encode(hashlib.sha256(sent["code_verifier"].encode()).digest()).rstrip(b"=").decode()+ == challenge+ )+ assert cache.get("oauth_pkce_verifier/exchange_state_token") is None++ @parameterized.expand(+ [+ (+ "json_error_body",+ 400,+ {+ "error": "invalid_grant",+ "error_description": "Authorization code does not exist or has expired.",+ },+ None,+ '{"error":"invalid_grant","error_description":"Authorization code does not exist or has expired."}',+ ["invalid_grant", "Authorization code does not exist"],+ ),+ (+ "non_json_error_body",+ 502,+ None,+ ValueError("not json"),+ "<html>Bad Gateway</html>",+ ["salesforce"],+ ),+ ]+ )+ @patch("posthog.models.integration.oauth.requests.post")+ def test_oauth_token_exchange_failure_raises_validation_error(+ self, _name, status_code, json_return, json_side_effect, body_text, expected_in_message, mock_post+ ):+ """A failed token exchange must surface a ValidationError (→ DRF 400 with `detail`) so the+ frontend toast renders something useful. Covers both well-formed JSON error bodies (where+ we extract `error_description`) and non-JSON bodies (where the helper falls back to the+ raw text or a status-only message)."""+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = status_code+ if json_side_effect is not None:+ mock_post.return_value.json.side_effect = json_side_effect+ else:+ mock_post.return_value.json.return_value = json_return+ mock_post.return_value.text = body_text++ with pytest.raises(ValidationError) as e:+ OauthIntegration.integration_from_oauth_response(+ "salesforce",+ self.team.id,+ self.user,+ {"code": "code", "state": "next=/projects/test"},+ )++ message = str(e.value).lower()+ for fragment in expected_in_message:+ assert fragment.lower() in message++ @patch("posthog.models.integration.oauth.requests.post")+ def test_integration_errors_if_id_cannot_be_generated(self, mock_post):+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "FAKES_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "not_instance_url": "https://fake.salesforce.com",+ "expires_in": 3600,+ }++ with pytest.raises(Exception):+ OauthIntegration.integration_from_oauth_response(+ "salesforce",+ self.team.id,+ self.user,+ {+ "code": "code",+ "state": "next=/projects/test",+ },+ )++ @patch("posthog.models.integration.oauth.requests.post")+ def test_tiktok_ads_oauth_without_advertiser_accounts_raises_validation_error(self, mock_post):+ # TikTok completes OAuth even when the user granted no advertiser account, leaving+ # `advertiser_ids` empty. That must surface as a ValidationError (→ 400 with an actionable+ # message) rather than the bare Exception (→ 500) the missing-id guard would otherwise raise.+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "code": 0,+ "data": {"access_token": "FAKE_ACCESS_TOKEN", "advertiser_ids": []},+ }++ with pytest.raises(ValidationError, match="ad accounts"):+ OauthIntegration.integration_from_oauth_response(+ "tiktok-ads",+ self.team.id,+ self.user,+ {"code": "code", "state": "next=/projects/test"},+ )++ @patch("posthog.models.integration.oauth.requests.post")+ @patch("posthog.models.integration.oauth.requests.get")+ def test_integration_fetches_info_from_token_info_url(self, mock_get, mock_post):+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "FAKES_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "expires_in": 3600,+ }++ mock_get.return_value.status_code = 200+ mock_get.return_value.json.return_value = {+ "hub_id": "hub_id",+ "hub_domain": "hub_domain",+ "user": "user",+ "user_id": "user_id",+ "should_not": "be_saved",+ "scopes": [+ "crm.objects.contacts.read",+ "crm.objects.contacts.write",+ ],+ }++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = OauthIntegration.integration_from_oauth_response(+ "hubspot",+ self.team.id,+ self.user,+ {+ "code": "code",+ "state": "next=/projects/test",+ },+ )++ assert integration.config == {+ "expires_in": 3600,+ "hub_id": "hub_id",+ "hub_domain": "hub_domain",+ "user": "user",+ "user_id": "user_id",+ "refreshed_at": 1704110400,+ "scopes": [+ "crm.objects.contacts.read",+ "crm.objects.contacts.write",+ ],+ }+ assert integration.sensitive_config == {+ "access_token": "FAKES_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "id_token": None,+ }++ @patch("posthog.models.integration.oauth.requests.post")+ def test_linkedin_integration_extracts_user_info_from_id_token(self, mock_post):+ """+ LinkedIn's /v2/userinfo endpoint has intermittent REVOKED_ACCESS_TOKEN errors,+ so we extract user info from the id_token JWT instead.+ """+ import json++ # Create a mock JWT id_token with sub and email in the payload+ jwt_payload = {"sub": "linkedin_user_123", "email": "[email protected]", "iat": 1704110400}+ encoded_payload = base64.urlsafe_b64encode(json.dumps(jwt_payload).encode()).decode().rstrip("=")+ mock_id_token = f"eyJhbGciOiJSUzI1NiJ9.{encoded_payload}.fake_signature"++ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "FAKE_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "id_token": mock_id_token,+ "expires_in": 3600,+ }++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = OauthIntegration.integration_from_oauth_response(+ "linkedin-ads",+ self.team.id,+ self.user,+ {+ "code": "code",+ "state": "next=/projects/test",+ },+ )++ assert integration.team == self.team+ assert integration.created_by == self.user+ # Verify sub and email were extracted from JWT+ assert integration.config["sub"] == "linkedin_user_123"+ assert integration.config["email"] == "[email protected]"+ assert integration.config["refreshed_at"] == 1704110400+ assert integration.config["expires_in"] == 3600++ assert integration.sensitive_config == {+ "access_token": "FAKE_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "id_token": mock_id_token,+ }++ def test_integration_access_token_expired(self):+ now = datetime.now()+ with freeze_time(now):+ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})++ with freeze_time(now):+ # Access token is not expired+ assert not OauthIntegration(integration).access_token_expired()++ with freeze_time(now + timedelta(seconds=1000) - timedelta(seconds=501)):+ # After the expiry but before the threshold it is not expired+ assert not OauthIntegration(integration).access_token_expired()++ with freeze_time(now + timedelta(seconds=1000) - timedelta(seconds=499)):+ # After the threshold it is expired+ assert OauthIntegration(integration).access_token_expired()++ with freeze_time(now + timedelta(seconds=1000)):+ # After the threshold it is expired+ assert OauthIntegration(integration).access_token_expired()++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_access_token(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "REFRESHED_ACCESS_TOKEN",+ "expires_in": 1000,+ }++ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ mock_post.assert_called_with(+ "https://api.hubapi.com/oauth/v1/token",+ data={+ "grant_type": "refresh_token",+ "client_id": "hubspot-client-id",+ "client_secret": "hubspot-client-secret",+ "refresh_token": "REFRESH",+ },+ timeout=10,+ allow_redirects=False,+ )++ assert integration.config["expires_in"] == 1000+ assert integration.config["refreshed_at"] == 1704117600+ assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"++ mock_reload.assert_called_once_with(self.team.id, [integration.id])++ @parameterized.expand(+ [+ (+ "rotated",+ {+ "access_token": "REFRESHED_ACCESS_TOKEN",+ "refresh_token": "ROTATED_REFRESH_TOKEN",+ "expires_in": 1000,+ },+ "ROTATED_REFRESH_TOKEN",+ ),+ ("not_rotated", {"access_token": "REFRESHED_ACCESS_TOKEN", "expires_in": 1000}, "REFRESH"),+ ]+ )+ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_access_token_refresh_token_handling(+ self, _name, token_response, expected_refresh_token, mock_post, mock_reload+ ):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = token_response++ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"+ assert integration.sensitive_config["refresh_token"] == expected_refresh_token++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_tiktok_ads_refresh_uses_business_api_and_unwraps_data(self, mock_post, mock_reload):+ # TikTok Business API refreshes against its own endpoint with app_id/secret (JSON) and nests+ # the refreshed tokens under `data` — not the Login Kit client_key/open.tiktokapis.com flow.+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "code": 0,+ "data": {"access_token": "REFRESHED_ACCESS_TOKEN", "refresh_token": "ROTATED_REFRESH_TOKEN"},+ }++ integration = self.create_integration(kind="tiktok-ads", config={"expires_in": 1000})++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ mock_post.assert_called_with(+ "https://business-api.tiktok.com/open_api/v1.3/oauth2/refresh_token/",+ json={+ "app_id": "tiktok-app-id",+ "secret": "tiktok-secret",+ "refresh_token": "REFRESH",+ "grant_type": "refresh_token",+ },+ headers={"Content-Type": "application/json"},+ timeout=10,+ )+ assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"+ assert integration.sensitive_config["refresh_token"] == "ROTATED_REFRESH_TOKEN"++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_access_token_handles_errors(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 401+ mock_post.return_value.json.return_value = {"error": "BROKEN"}++ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000, "refreshed_at": 1700000000})++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ assert integration.config["expires_in"] == 1000+ assert integration.config["refreshed_at"] == 1700000000+ assert integration.errors == "TOKEN_REFRESH_FAILED"++ mock_reload.assert_not_called()++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_failed_refresh_leaves_stored_secrets_byte_identical(self, mock_post, mock_reload):+ # A failed refresh has no new secrets to store, and rewriting the ones already there is how+ # a secret that couldn't be decrypted (handed back as raw ciphertext by+ # `ignore_decrypt_errors`) gains a permanent extra encryption layer.+ mock_post.return_value.status_code = 401+ mock_post.return_value.json.return_value = {"error": "BROKEN"}++ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})+ stored_before = get_db_field_value("sensitive_config", integration.id)++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ assert get_db_field_value("sensitive_config", integration.id) == stored_before+ assert integration.errors == "TOKEN_REFRESH_FAILED"++ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_with_unreadable_secret_goes_terminal_without_calling_the_provider(self, mock_post):+ # Posting ciphertext as the refresh token just earns an invalid_grant every minute forever.+ # Nothing about the stored secret can change, so the sweep must stop and the reconnect+ # prompt must show instead.+ integration = self.create_integration(kind="hubspot", sensitive_config={"refresh_token": "gAAAAAleftover=="})++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ mock_post.assert_not_called()+ assert integration.errors == "TOKEN_REFRESH_FAILED"+ assert refresh_backoff_active(integration) is True++ integration.refresh_from_db()+ assert integration.config["refresh_terminal"] is True++ def _mock_token_response(self, status_code: int, token: Optional[str]) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = {"access_token": token, "expires_in": 1000} if token else {}+ response.text = "error"+ return response++ @parameterized.expand(+ [+ # Primary works: the fallback must not fire, even when configured, and the grant is no+ # longer tied to the legacy app - so the reconnect prompt must stop showing.+ ("primary_ok", True, [(200, "primary-token")], "primary-token", "", 1, True, False),+ # A token issued by the previous app only refreshes with the fallback pair. Flagging it+ # is what identifies the connections that break when the legacy app is retired.+ ("fallback_rescues", True, [(401, None), (200, "fallback-token")], "fallback-token", "", 2, False, True),+ # Both credentials failing still marks the integration errored so the reconnect banner shows.+ ("both_fail", True, [(401, None), (401, None)], None, "TOKEN_REFRESH_FAILED", 2, True, True),+ # Without a fallback configured, behavior is identical to before: a single attempt, no retry.+ ("no_fallback_no_retry", False, [(401, None)], None, "TOKEN_REFRESH_FAILED", 1, False, False),+ ]+ )+ def test_refresh_falls_back_to_previous_credentials(+ self,+ _name,+ has_fallback,+ responses,+ expected_token,+ expected_errors,+ expected_calls,+ initial_legacy_flag,+ expected_legacy_flag,+ ):+ fallbacks = {"bing-ads": {"client_id": "old-app-id", "client_secret": "old-app-secret"}} if has_fallback else {}+ config = {"expires_in": 1000}+ if initial_legacy_flag:+ config[CONFIG_LEGACY_OAUTH_CLIENT] = True+ integration = self.create_integration(kind="bing-ads", config=config)++ with (+ self.settings(+ BING_ADS_CLIENT_ID="new-app-id",+ BING_ADS_CLIENT_SECRET="new-app-secret",+ OAUTH_CLIENT_FALLBACKS=fallbacks,+ ),+ patch("posthog.models.integration.oauth.reload_integrations_on_workers"),+ patch(+ "posthog.models.integration.oauth.requests.post",+ side_effect=[self._mock_token_response(status, token) for status, token in responses],+ ) as mock_post,+ ):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert mock_post.call_count == expected_calls+ assert integration.errors == expected_errors+ assert integration.config.get(CONFIG_LEGACY_OAUTH_CLIENT, False) == expected_legacy_flag+ if expected_token is not None:+ assert integration.sensitive_config["access_token"] == expected_token++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_network_error_marks_failed_without_raising(self, mock_post, mock_reload):+ # A timeout must not escape refresh_access_token: the Celery sweep would error out before+ # recording the failure, leaving the integration without a backoff or the reconnect state.+ mock_post.side_effect = requests.Timeout("timed out")+ integration = self.create_integration(kind="bing-ads", config={"expires_in": 1000})++ with self.settings(BING_ADS_CLIENT_ID="new-app-id", BING_ADS_CLIENT_SECRET="new-app-secret"):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.errors == "TOKEN_REFRESH_FAILED"+ assert integration.config.get("refresh_failure_count") == 1+ assert integration.config.get("refresh_next_attempt_at")++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_primary_network_error_still_tries_fallback(self, mock_post, mock_reload):+ # A network error on the primary credentials must not skip the fallback attempt.+ mock_post.side_effect = [requests.Timeout("timed out"), self._mock_token_response(200, "fallback-token")]+ integration = self.create_integration(kind="bing-ads", config={"expires_in": 1000})++ with self.settings(+ BING_ADS_CLIENT_ID="new-app-id",+ BING_ADS_CLIENT_SECRET="new-app-secret",+ OAUTH_CLIENT_FALLBACKS={"bing-ads": {"client_id": "old-app-id", "client_secret": "old-app-secret"}},+ ):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert mock_post.call_count == 2+ assert integration.errors == ""+ assert integration.sensitive_config["access_token"] == "fallback-token"++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_access_token_resets_errors(self, mock_post, mock_reload):+ """Test that errors field is reset to empty string after successful refresh_access_token"""+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "REFRESHED_ACCESS_TOKEN",+ "expires_in": 1000,+ }++ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})+ integration.errors = "TOKEN_REFRESH_FAILED"+ integration.save()++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.errors == ""++ @parameterized.expand(+ [+ ("first_failure", 0, 120),+ ("second_failure", 1, 240),+ ("capped", 10, 3600),+ ]+ )+ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_failure_schedules_backoff(self, _name, prior_failures, expected_delay, mock_post, mock_reload):+ mock_post.return_value.status_code = 401+ mock_post.return_value.json.return_value = {"error": "BROKEN"}++ config: dict = {"expires_in": 1000}+ if prior_failures:+ config["refresh_failure_count"] = prior_failures+ integration = self.create_integration(kind="hubspot", config=config)++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.config["refresh_failure_count"] == prior_failures + 1+ assert integration.config["refresh_next_attempt_at"] == 1704117600 + expected_delay+ assert "refresh_terminal" not in integration.config++ @parameterized.expand(+ [+ # (error, prior total failures, prior invalid_grant streak, expect terminal)+ ("invalid_grant_below_threshold", "invalid_grant", 3, 3, False),+ ("invalid_grant_at_threshold", "invalid_grant", 4, 4, True),+ ("invalid_client_never_terminal", "invalid_client", 10, 0, False),+ # A single invalid_grant after a run of other failures must not go terminal - the+ # streak has to be invalid_grant all the way through+ ("mixed_failures_not_terminal", "invalid_grant", 4, 0, False),+ ]+ )+ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_failure_terminal_state(+ self, _name, error, prior_failures, prior_grant_streak, expected_terminal, mock_post, mock_reload+ ):+ mock_post.return_value.status_code = 400+ mock_post.return_value.json.return_value = {"error": error}++ config: dict = {"expires_in": 1000, "refresh_failure_count": prior_failures}+ if prior_grant_streak:+ config["refresh_invalid_grant_count"] = prior_grant_streak+ integration = self.create_integration(kind="hubspot", config=config)++ terminal_counter = oauth_refresh_terminal_counter.labels(kind="hubspot")+ counter_before = terminal_counter._value.get()++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert bool(integration.config.get("refresh_terminal")) is expected_terminal+ # The transition is the fleet die-off signal: exactly one increment when a row goes+ # terminal, none otherwise+ assert terminal_counter._value.get() - counter_before == (1 if expected_terminal else 0)++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_already_terminal_row_does_not_recount_on_bypassing_refresh(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 400+ mock_post.return_value.json.return_value = {"error": "invalid_grant"}++ # On-demand refreshes bypass the backoff, so a dead row can keep failing after the+ # transition - it must not inflate the die-off counter again+ integration = self.create_integration(+ kind="hubspot",+ config={+ "expires_in": 1000,+ "refresh_failure_count": 6,+ "refresh_invalid_grant_count": 6,+ "refresh_terminal": True,+ },+ )++ terminal_counter = oauth_refresh_terminal_counter.labels(kind="hubspot")+ counter_before = terminal_counter._value.get()++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.config.get("refresh_terminal") is True+ assert terminal_counter._value.get() == counter_before++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_non_invalid_grant_failure_resets_grant_streak(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 503+ mock_post.return_value.json.return_value = {"error": "server_error"}++ integration = self.create_integration(+ kind="hubspot",+ config={"expires_in": 1000, "refresh_failure_count": 4, "refresh_invalid_grant_count": 4},+ )++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert "refresh_invalid_grant_count" not in integration.config+ assert "refresh_terminal" not in integration.config++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_success_clears_backoff_state(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"access_token": "REFRESHED_ACCESS_TOKEN", "expires_in": 1000}++ integration = self.create_integration(+ kind="hubspot",+ config={+ "expires_in": 1000,+ "refresh_failure_count": 5,+ "refresh_invalid_grant_count": 5,+ "refresh_next_attempt_at": 1704117600,+ "refresh_terminal": True,+ },+ )++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert "refresh_failure_count" not in integration.config+ assert "refresh_invalid_grant_count" not in integration.config+ assert "refresh_next_attempt_at" not in integration.config+ assert "refresh_terminal" not in integration.config++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_failure_with_non_json_body_still_backs_off(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 502+ mock_post.return_value.json.side_effect = ValueError("not json")+ mock_post.return_value.text = "<html>Bad Gateway</html>"++ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.errors == "TOKEN_REFRESH_FAILED"+ assert integration.config["refresh_failure_count"] == 1++ @parameterized.expand(+ [+ ("invalid_grant", 400, {"error": "invalid_grant"}, None, "invalid_grant"),+ ("invalid_client", 401, {"error": "invalid_client"}, None, "invalid_client"),+ ("server_error", 502, {}, None, "http_5xx"),+ ("other_4xx", 400, {"error": "temporarily_unavailable"}, None, "other"),+ ("non_string_error", 400, {"error": {"code": 1}}, None, "other"),+ ("reddit_dead_grant_shape", 400, {"message": "Bad Request", "error": 400}, "reddit-ads", "invalid_grant"),+ ("reddit_shape_on_other_kind", 400, {"message": "Bad Request", "error": 400}, "hubspot", "other"),+ ("reddit_5xx", 502, {"message": "Bad Gateway", "error": 502}, "reddit-ads", "http_5xx"),+ ("reddit_oauth_error_code", 400, {"error": "invalid_grant"}, "reddit-ads", "invalid_grant"),+ (+ "hubspot_dead_hub_shape",+ 400,+ {"status": "BAD_HUB", "message": "missing or unknown hub id", "error": "access_denied"},+ "hubspot",+ "invalid_grant",+ ),+ (+ "hubspot_shape_on_other_kind",+ 400,+ {"status": "BAD_HUB", "error": "access_denied"},+ "salesforce",+ "other",+ ),+ ("hubspot_bad_hub_5xx_is_outage", 502, {"status": "BAD_HUB"}, "hubspot", "http_5xx"),+ (+ "hubspot_bad_refresh_token_still_oauth_code",+ 400,+ {"status": "BAD_REFRESH_TOKEN", "error": "invalid_grant"},+ "hubspot",+ "invalid_grant",+ ),+ ("rate_limited", 429, {"status": "error", "errorType": "RATE_LIMIT"}, "hubspot", "rate_limited"),+ ("rate_limited_any_kind", 429, {}, None, "rate_limited"),+ (+ "meta_dead_token",+ 400,+ {+ "error": {+ "message": "Error validating access token: The session has been invalidated because the user changed their password.",+ "type": "OAuthException",+ "code": 190,+ "error_subcode": 460,+ }+ },+ "meta-ads",+ "invalid_grant",+ ),+ (+ "instagram_dead_token",+ 400,+ {"error": {"type": "OAuthException", "code": 190}},+ "instagram",+ "invalid_grant",+ ),+ ("meta_shape_on_other_kind", 400, {"error": {"code": 190}}, "hubspot", "other"),+ ("meta_non_grant_error_code", 400, {"error": {"type": "OAuthException", "code": 10}}, "meta-ads", "other"),+ ("meta_190_5xx_is_outage", 502, {"error": {"code": 190}}, "meta-ads", "http_5xx"),+ ]+ )+ def test_oauth_refresh_failure_reason(self, _name, status_code, body, kind, expected):+ assert oauth_refresh_failure_reason(status_code, body, kind=kind) == expected++ @patch("posthog.models.integration.oauth.requests.post")+ def test_reconnect_clears_backoff_state(self, mock_post):+ # A customer re-authing must un-brick a terminal integration, or "please reconnect"+ # comms leave them permanently dead.+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ # integration_from_oauth_response pops fields out of the response dict, so each call+ # needs a fresh one+ mock_post.return_value.json.side_effect = lambda: {+ "access_token": "FAKES_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "instance_url": "https://fake.salesforce.com",+ "expires_in": 3600,+ }+ oauth_payload = {"code": "code", "state": "next=/projects/test"}++ integration = OauthIntegration.integration_from_oauth_response(+ "salesforce", self.team.id, self.user, oauth_payload+ )+ integration.config.update(+ {"refresh_failure_count": 5, "refresh_next_attempt_at": 1704117600, "refresh_terminal": True}+ )+ integration.save()++ reconnected = OauthIntegration.integration_from_oauth_response(+ "salesforce", self.team.id, self.user, oauth_payload+ )++ assert reconnected.id == integration.id+ assert "refresh_failure_count" not in reconnected.config+ assert "refresh_next_attempt_at" not in reconnected.config+ assert "refresh_terminal" not in reconnected.config++ @patch("posthog.models.integration.oauth.requests.post")+ def test_salesforce_integration_without_expires_in_initial_response(self, mock_post):+ """Test that Salesforce integrations without expires_in get default 1 hour expiry"""+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "FAKES_ACCESS_TOKEN",+ "refresh_token": "FAKE_REFRESH_TOKEN",+ "instance_url": "https://fake.salesforce.com",+ # Note: no expires_in field+ }++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = OauthIntegration.integration_from_oauth_response(+ "salesforce",+ self.team.id,+ self.user,+ {+ "code": "code",+ "state": "next=/projects/test",+ },+ )++ # Should have default 1 hour (3600 seconds) expiry+ assert integration.config["expires_in"] == 3600+ assert integration.config["refreshed_at"] == 1704110400++ def test_salesforce_access_token_expired_without_expires_in(self):+ """Test that Salesforce tokens without expires_in info use 1 hour default"""+ now = datetime.now()+ with freeze_time(now):+ # Create integration without expires_in+ integration = self.create_integration(+ kind="salesforce",+ config={"refreshed_at": int(time.time())}, # No expires_in+ sensitive_config={"refresh_token": "REFRESH"},+ )++ oauth_integration = OauthIntegration(integration)++ with freeze_time(now):+ # Token should not be expired initially+ assert not oauth_integration.access_token_expired()++ with freeze_time(now + timedelta(minutes=29)):+ # Should not be expired before 30 minutes (half of 1 hour default)+ assert not oauth_integration.access_token_expired()++ with freeze_time(now + timedelta(minutes=31)):+ # Should be expired after 30 minutes (halfway point of 1 hour)+ assert oauth_integration.access_token_expired()++ def test_non_salesforce_access_token_expired_without_expires_in(self):+ """Test that non-Salesforce integrations without expires_in return False"""+ now = datetime.now()+ with freeze_time(now):+ # Create non-Salesforce integration without expires_in - override the default+ integration = Integration.objects.create(+ team=self.team,+ kind="hubspot",+ config={"refreshed_at": int(time.time())}, # No expires_in+ sensitive_config={"refresh_token": "REFRESH"},+ )++ oauth_integration = OauthIntegration(integration)++ with freeze_time(now + timedelta(hours=5)):+ # Should never expire without expires_in for non-Salesforce+ assert not oauth_integration.access_token_expired()++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_salesforce_refresh_access_token_without_expires_in_response(self, mock_post, mock_reload):+ """Test that Salesforce refresh without expires_in in response gets 1 hour default"""+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "REFRESHED_ACCESS_TOKEN",+ # Note: no expires_in field in refresh response+ }++ integration = self.create_integration(kind="salesforce", config={"expires_in": 1000})++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ # Should have default 1 hour (3600 seconds) expiry+ assert integration.config["expires_in"] == 3600+ assert integration.config["refreshed_at"] == 1704117600+ assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"++ mock_reload.assert_called_once_with(self.team.id, [integration.id])++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_salesforce_refresh_uses_instance_url_for_sandbox(self, mock_post, mock_reload):+ # Sandbox integrations are stored as kind="salesforce" (the sandbox is a token-exchange+ # fallback in the OAuth callback), so the config's instance_url is the only signal that+ # the refresh must go to test.salesforce.com or the org's own host rather than the+ # hardcoded prod token URL. Salesforce rejects a sandbox refresh_token posted to+ # login.salesforce.com, which shows up to users as "Authentication token could not be+ # refreshed. Please reconnect." within a few hours of connecting.+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "REFRESHED_ACCESS_TOKEN",+ "expires_in": 3600,+ }++ sandbox_instance_url = "https://ryan-co--sandbox.sandbox.my.salesforce.com"+ integration = self.create_integration(+ kind="salesforce",+ config={"instance_url": sandbox_instance_url},+ )++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ assert integration.errors == ""+ assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"++ called_url = mock_post.call_args.args[0]+ assert called_url == f"{sandbox_instance_url}/services/oauth2/token"++ @parameterized.expand(+ [+ ("attacker_https", "https://attacker.example.com"),+ ("attacker_lookalike_suffix", "https://salesforce.com.attacker.example"),+ ("attacker_lookalike_prefix", "https://acmesalesforce.com"),+ ("http_scheme_downgrade", "http://acme.my.salesforce.com"),+ ("with_userinfo", "https://user:[email protected]"),+ ("with_port", "https://acme.my.salesforce.com:8443"),+ ("invalid_port_raises_valueerror", "https://acme.my.salesforce.com:abc"),+ ("garbage_value", "not a url"),+ ("empty_value", ""),+ ]+ )+ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_salesforce_refresh_rejects_untrusted_instance_url(self, _name, bad_instance_url, mock_post, mock_reload):+ # If a future write path (a partial_update action, an admin tool, a data migration)+ # lets an attacker set instance_url, the refresh must not POST client_secret ++ # refresh_token to that origin - the client_secret is fleet-wide and its leak forces+ # rotation and reconnect for every Salesforce integration. Any instance_url that isn't+ # an https .salesforce.com host falls back to the hardcoded prod token URL, and the+ # refresh must not follow redirects that would move the secret to another host.+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "REFRESHED_ACCESS_TOKEN",+ "expires_in": 3600,+ }++ integration = self.create_integration(+ kind="salesforce",+ config={"instance_url": bad_instance_url},+ )++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ called_url = mock_post.call_args.args[0]+ assert called_url == "https://login.salesforce.com/services/oauth2/token"++ called_kwargs = mock_post.call_args.kwargs+ assert called_kwargs["allow_redirects"] is False++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_non_salesforce_refresh_access_token_preserves_none_expires_in(self, mock_post, mock_reload):+ """Test that non-Salesforce integrations preserve None expires_in from refresh response"""+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "REFRESHED_ACCESS_TOKEN",+ # Note: no expires_in field in refresh response+ }++ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})++ with freeze_time("2024-01-01T14:00:00Z"):+ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ # Should preserve None for non-Salesforce+ assert integration.config["expires_in"] is None+ assert integration.config["refreshed_at"] == 1704117600+ assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"++ mock_reload.assert_called_once_with(self.team.id, [integration.id])++ @patch("posthog.models.integration.oauth.requests.post")+ def test_stripe_integration_from_oauth_response_uses_apps_endpoint_and_basic_auth(self, mock_post):+ # Stripe Apps OAuth (api.stripe.com/v1/oauth/token) is a different system from+ # Stripe Connect OAuth (connect.stripe.com/oauth/token): it authenticates the+ # token exchange with HTTP Basic (secret as username, no password) and accepts+ # only `code` + `grant_type` in the body. Codes minted by `marketplace.stripe.com`+ # cannot be redeemed at the Connect endpoint.+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "FAKE_ACCESS",+ "refresh_token": "FAKE_REFRESH",+ "stripe_user_id": "acct_123",+ "account_name": "Test Account",+ "expires_in": 3600,+ }++ with self.settings(+ STRIPE_APP_CLIENT_ID="ca_test_clientid",+ STRIPE_APP_SECRET_KEY="sk_test_secret",+ ):+ OauthIntegration.integration_from_oauth_response(+ "stripe",+ self.team.id,+ self.user,+ {"code": "ac_real_code"},+ )++ call = mock_post.call_args+ assert call.args[0] == "https://api.stripe.com/v1/oauth/token"+ assert call.kwargs["data"] == {"code": "ac_real_code", "grant_type": "authorization_code"}+ assert call.kwargs["auth"].username == "sk_test_secret"+ assert call.kwargs["auth"].password == ""++ def test_stripe_authorize_url_uses_live_client_id_by_default(self):+ with self.settings(+ STRIPE_APP_CLIENT_ID="ca_live_clientid",+ STRIPE_APP_SECRET_KEY="sk_live_secret",+ STRIPE_APP_OVERRIDE_AUTHORIZE_URL="",+ ):+ url = OauthIntegration.authorize_url("stripe", token="state_token", next="/projects/test")+ assert "client_id=ca_live_clientid" in url++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_stripe_refresh_access_token_uses_apps_endpoint_and_basic_auth(self, mock_post, mock_reload):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"access_token": "REFRESHED", "expires_in": 1000}++ integration = self.create_integration(kind="stripe", config={"expires_in": 1000})++ with self.settings(+ STRIPE_APP_CLIENT_ID="ca_test_clientid",+ STRIPE_APP_SECRET_KEY="sk_test_secret",+ ):+ OauthIntegration(integration).refresh_access_token()++ call = mock_post.call_args+ assert call.args[0] == "https://api.stripe.com/v1/oauth/token"+ assert call.kwargs["data"] == {"refresh_token": "REFRESH", "grant_type": "refresh_token"}+ assert call.kwargs["auth"].username == "sk_test_secret"+ assert call.kwargs["auth"].password == ""++ mock_reload.assert_called_once_with(self.team.id, [integration.id])++ @patch("posthog.models.integration.oauth.requests.post")+ def test_stripe_oauth_does_not_persist_is_sandbox(self, mock_post):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "FAKE_ACCESS",+ "refresh_token": "FAKE_REFRESH",+ "stripe_user_id": "acct_live_1",+ "account_name": "Live Account",+ "expires_in": 3600,+ }++ with self.settings(+ STRIPE_APP_CLIENT_ID="ca_live_clientid",+ STRIPE_APP_SECRET_KEY="sk_live_secret",+ ):+ integration = OauthIntegration.integration_from_oauth_response(+ "stripe",+ self.team.id,+ self.user,+ {"code": "ac_live_code"},+ )++ assert "is_sandbox" not in integration.config+++class TestPosthogConnectIntegration(BaseTest):+ connect_settings = {+ "POSTHOG_CONNECT_BASE_URL_US": "https://us.posthog.com",+ "POSTHOG_CONNECT_OAUTH_CLIENT_ID_US": "us-client-id",+ "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_US": "us-secret",+ "POSTHOG_CONNECT_BASE_URL_EU": "https://eu.posthog.com",+ "POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU": "eu-client-id",+ "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU": "eu-secret",+ "POSTHOG_CONNECT_BASE_URL_DEV": "http://localhost:8000",+ "POSTHOG_CONNECT_OAUTH_CLIENT_ID_DEV": "dev-client-id",+ "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_DEV": "dev-secret",+ }++ @parameterized.expand(+ [+ ("US", "https://us.posthog.com/oauth/authorize", "us-client-id"),+ ("EU", "https://eu.posthog.com/oauth/authorize", "eu-client-id"),+ ("DEV", "http://localhost:8000/oauth/authorize", "dev-client-id"),+ ]+ )+ def test_authorize_url_targets_selected_region(self, region, expected_base, expected_client_id):+ with self.settings(**self.connect_settings):+ url = OauthIntegration.authorize_url(+ "posthog", token="tok", next="/projects/test", region=region, scopes=["task:read", "task:write"]+ )+ base, _, query = url.partition("?")+ params = {k: v[0] for k, v in parse_qs(query).items()}+ assert base == expected_base+ assert params["client_id"] == expected_client_id+ # User-selected scopes plus the always-appended identity scopes needed for /oauth/userinfo.+ assert params["scope"] == "task:read task:write openid email"+ # Host comes from SITE_URL, which differs by environment; assert the stable callback suffix.+ assert params["redirect_uri"].endswith("/integrations/posthog/callback")+ # posthog uses PKCE+ assert params["code_challenge_method"] == "S256"+ # Region is carried in state so the callback (on the connecting cell) exchanges the code+ # against the correct target cell.+ state = {k: v[0] for k, v in parse_qs(params["state"]).items()}+ assert state["region"] == region+ assert state["token"] == "tok"++ def test_authorize_url_lowercases_region_input(self):+ with self.settings(**self.connect_settings):+ url = OauthIntegration.authorize_url("posthog", token="tok", region="eu", scopes=["task:read"])+ assert url.startswith("https://eu.posthog.com/oauth/authorize")+ outer = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}+ state = {k: v[0] for k, v in parse_qs(outer["state"]).items()}+ assert state["region"] == "EU"++ def test_authorize_url_defaults_to_task_scopes_when_none_selected(self):+ with self.settings(**self.connect_settings):+ url = OauthIntegration.authorize_url("posthog", token="tok", region="US", scopes=None)+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}+ expected = " ".join([*POSTHOG_CONNECT_DEFAULT_SCOPES, *POSTHOG_CONNECT_IDENTITY_SCOPES])+ assert params["scope"] == expected++ def test_authorize_url_unknown_region_raises(self):+ with self.settings(**self.connect_settings):+ with pytest.raises(NotImplementedError):+ OauthIntegration.authorize_url("posthog", token="tok", region="ASIA", scopes=["task:read"])++ def test_authorize_url_unconfigured_region_raises(self):+ unconfigured = {+ **self.connect_settings,+ "POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU": "",+ "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU": "",+ }+ with self.settings(**unconfigured):+ with pytest.raises(NotImplementedError):+ OauthIntegration.authorize_url("posthog", token="tok", region="EU", scopes=["task:read"])++ @patch("posthog.models.integration.oauth.requests.get")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_integration_from_oauth_response_persists_region_and_namespaces_id(self, mock_post, mock_get):+ with self.settings(**self.connect_settings):+ mock_post.return_value = MagicMock(status_code=200)+ mock_post.return_value.json.return_value = {+ "access_token": "AT",+ "refresh_token": "RT",+ "expires_in": 3600,+ "scope": "task:read task:write openid email",+ }+ mock_get.return_value = MagicMock(status_code=200)+ mock_get.return_value.json.return_value = {"sub": "user-uuid-123", "email": "[email protected]"}++ # posthog is a PKCE flow; the authorize step caches a verifier keyed on the state token.+ cache.set("oauth_pkce_verifier/tok", "the-verifier")+ state = urlencode({"next": "/", "token": "tok", "region": "EU"})+ integration = OauthIntegration.integration_from_oauth_response(+ "posthog", self.team.id, self.user, {"code": "auth-code", "state": state}+ )++ # Token exchange must hit the region carried in state.+ assert mock_post.call_args[0][0] == "https://eu.posthog.com/oauth/token"+ assert integration.kind == "posthog"+ assert integration.config["region"] == "EU"+ # Dedup key is namespaced by region so the same account in two cells doesn't collide.+ assert integration.integration_id == "EU:user-uuid-123"+ assert integration.config["email"] == "[email protected]"+ # Only the resource scopes are persisted (identity scopes dropped), for the caller-scope check.+ assert integration.config["granted_scopes"] == ["task:read", "task:write"]+ assert integration.sensitive_config["access_token"] == "AT"+ assert integration.sensitive_config["refresh_token"] == "RT"++ @patch("posthog.models.integration.oauth.requests.post")+ def test_integration_from_oauth_response_fails_closed_without_pkce_verifier(self, mock_post):+ # No cached verifier (as if the authorize step was skipped / replayed). A first-party posthog+ # flow must fail closed rather than exchange the code without PKCE.+ with self.settings(**self.connect_settings):+ cache.delete("oauth_pkce_verifier/tok")+ state = urlencode({"next": "/", "token": "tok", "region": "EU"})+ with pytest.raises(ValidationError):+ OauthIntegration.integration_from_oauth_response(+ "posthog", self.team.id, self.user, {"code": "auth-code", "state": state}+ )+ mock_post.assert_not_called()++ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_access_token_uses_persisted_region(self, mock_post):+ with self.settings(**self.connect_settings):+ integration = Integration.objects.create(+ team=self.team,+ kind="posthog",+ integration_id="EU:user-uuid-123",+ config={"region": "EU", "refreshed_at": int(time.time()) - 4000, "expires_in": 3600},+ sensitive_config={"refresh_token": "RT", "access_token": "OLD"},+ )+ mock_post.return_value = MagicMock(status_code=200)+ mock_post.return_value.json.return_value = {+ "access_token": "NEW",+ "refresh_token": "RT2",+ "expires_in": 3600,+ }++ OauthIntegration(integration).refresh_access_token()++ # Refresh must target the persisted region's token endpoint, not a static one.+ assert mock_post.call_args[0][0] == "https://eu.posthog.com/oauth/token"+ integration.refresh_from_db()+ assert integration.sensitive_config["access_token"] == "NEW"+++def _make_resend_jwt(payload: dict) -> str:+ body = base64.urlsafe_b64encode(json.dumps(payload).encode()).rstrip(b"=").decode()+ return f"header.{body}.signature"+++@override_settings(RESEND_APP_CLIENT_ID="resend-client-id", RESEND_APP_CLIENT_SECRET="resend-client-secret")+class TestResendIntegrationModel(BaseTest):+ def test_oauth_config(self):+ config = OauthIntegration.oauth_config_for_kind("resend")+ assert config.authorize_url == "https://resend.com/oauth/authorize"+ assert config.token_url == "https://api.resend.com/oauth/token"+ assert config.token_revoke_url == "https://api.resend.com/oauth/revoke"+ assert config.client_id == "resend-client-id"+ assert config.client_secret == "resend-client-secret"+ assert config.scope == "full_access"+ assert config.pkce is True+ assert config.id_path == "resend_account_id"++ @override_settings(RESEND_APP_CLIENT_ID="", RESEND_APP_CLIENT_SECRET="")+ def test_oauth_config_unconfigured_raises(self):+ with pytest.raises(NotImplementedError, match="Resend app not configured"):+ OauthIntegration.oauth_config_for_kind("resend")++ @patch("posthog.models.integration.oauth.requests.post")+ def test_integration_from_oauth_response_extracts_account_from_jwt(self, mock_post):+ access_token = _make_resend_jwt({"sub": "acct_123", "email": "[email protected]"})+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": access_token,+ "refresh_token": "rt_1",+ "expires_in": 900,+ "token_type": "Bearer",+ }++ with freeze_time("2024-01-01T12:00:00Z"):+ integration = OauthIntegration.integration_from_oauth_response(+ "resend",+ self.team.id,+ self.user,+ {"code": "code", "state": "token=state_token"},+ )++ assert integration.kind == "resend"+ assert integration.integration_id == "acct_123"+ assert integration.config["resend_account_id"] == "acct_123"+ assert integration.config["resend_account_name"] == "[email protected]"+ assert integration.config["expires_in"] == 900+ assert integration.sensitive_config["access_token"] == access_token+ assert integration.sensitive_config["refresh_token"] == "rt_1"++ @patch("posthog.models.integration.oauth.requests.post")+ def test_integration_from_oauth_response_name_falls_back_without_email(self, mock_post):+ access_token = _make_resend_jwt({"sub": "acct_xyz"})+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": access_token,+ "refresh_token": "rt",+ "expires_in": 900,+ }++ integration = OauthIntegration.integration_from_oauth_response(+ "resend",+ self.team.id,+ self.user,+ {"code": "code", "state": "token=state_token"},+ )++ assert integration.integration_id == "acct_xyz"+ assert integration.config["resend_account_name"] == "Resend account acct_xyz"++ @patch("posthog.models.integration.oauth.requests.post")+ def test_integration_from_oauth_response_without_sub_raises(self, mock_post):+ access_token = _make_resend_jwt({"email": "[email protected]"})+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": access_token,+ "refresh_token": "rt",+ "expires_in": 900,+ }++ with pytest.raises(Exception, match="failed to extract integration ID"):+ OauthIntegration.integration_from_oauth_response(+ "resend",+ self.team.id,+ self.user,+ {"code": "code", "state": "token=state_token"},+ )++ @patch("posthog.models.integration.oauth.requests.post")+ def test_authorization_code_exchange_does_not_follow_redirects(self, mock_post):+ # A 307/308 from the token endpoint must not forward client_secret + code to its Location.+ access_token = _make_resend_jwt({"sub": "acct_1"})+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": access_token,+ "refresh_token": "rt",+ "expires_in": 900,+ }++ OauthIntegration.integration_from_oauth_response(+ "resend",+ self.team.id,+ self.user,+ {"code": "code", "state": "token=state_token"},+ )++ assert mock_post.call_args.kwargs["allow_redirects"] is False++ @patch("posthog.models.integration.oauth.requests.post")+ def test_revoke_token_authenticates_with_client_credentials(self, mock_post):+ integration = Integration.objects.create(+ team=self.team,+ kind="resend",+ config={"resend_account_id": "acct_1"},+ sensitive_config={"refresh_token": "rt_secret", "access_token": "at_secret"},+ )++ OauthIntegration(integration).revoke_token()++ sent = mock_post.call_args.kwargs["data"]+ assert sent["token"] == "rt_secret"+ assert sent["client_id"] == "resend-client-id"+ assert sent["client_secret"] == "resend-client-secret"+ assert sent["token_type_hint"] == "refresh_token"+++@override_settings(+ SALESFORCE_CONSUMER_KEY="salesforce-client-id", SALESFORCE_CONSUMER_SECRET="salesforce-client-secret"+)+class TestPardotIntegrationModel(BaseTest):+ def test_oauth_config_requests_the_account_engagement_scope(self):+ config = OauthIntegration.oauth_config_for_kind("pardot")++ assert config.authorize_url == "https://login.salesforce.com/services/oauth2/authorize"+ assert config.token_url == "https://login.salesforce.com/services/oauth2/token"+ assert config.token_revoke_url == "https://login.salesforce.com/services/oauth2/revoke"+ assert config.client_id == "salesforce-client-id"+ assert config.client_secret == "salesforce-client-secret"+ assert config.pkce is True+ assert config.id_path == "instance_url"+ # Salesforce's `full` scope does not cover the Account Engagement API, so a token+ # minted for the CRM kind cannot call it. That is why this kind exists at all.+ assert config.scope == "pardot_api refresh_token"+ assert config.scope != OauthIntegration.oauth_config_for_kind("salesforce").scope++ def test_pardot_is_an_oauth_kind(self):+ # Not being listed makes the authorize + callback endpoints reject the kind and drops+ # it out of the scheduled token refresh sweep.+ assert "pardot" in OauthIntegration.supported_kinds++ @override_settings(SALESFORCE_CONSUMER_KEY="", SALESFORCE_CONSUMER_SECRET="")+ def test_oauth_config_unconfigured_raises(self):+ with pytest.raises(NotImplementedError, match="Salesforce app not configured"):+ OauthIntegration.oauth_config_for_kind("pardot")++ @patch("posthog.models.integration.oauth.reload_integrations_on_workers")+ @patch("posthog.models.integration.oauth.requests.post")+ def test_refresh_uses_the_org_instance_host_and_assumes_an_hour(self, mock_post, mock_reload):+ # Account Engagement business units can live on a sandbox org, whose refresh token+ # login.salesforce.com rejects, and Salesforce often omits expires_in — without the+ # assumed hour the token is never treated as expired and syncs fail on a stale one.+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"access_token": "REFRESHED_ACCESS_TOKEN"}++ instance_url = "https://acme--sandbox.sandbox.my.salesforce.com"+ integration = Integration.objects.create(+ team=self.team,+ kind="pardot",+ config={"instance_url": instance_url, "refreshed_at": int(time.time())},+ sensitive_config={"refresh_token": "REFRESH"},+ )++ OauthIntegration(integration).refresh_access_token()++ assert integration.errors == ""+ assert mock_post.call_args.args[0] == f"{instance_url}/services/oauth2/token"+ assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"+ assert integration.config["expires_in"] == 3600++ @patch("posthog.models.integration.oauth.requests.post")+ def test_expiry_is_assumed_when_the_token_response_omits_it(self, mock_post):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "at",+ "refresh_token": "rt",+ "instance_url": "https://acme.my.salesforce.com",+ }++ integration = OauthIntegration.integration_from_oauth_response(+ "pardot",+ self.team.id,+ self.user,+ {"code": "code", "state": "token=state_token"},+ )++ assert integration.integration_id == "https://acme.my.salesforce.com"+ assert integration.config["expires_in"] == 3600+++@override_settings(+ YOUTUBE_ANALYTICS_APP_CLIENT_ID="youtube-client-id",+ YOUTUBE_ANALYTICS_APP_CLIENT_SECRET="youtube-client-secret",+)+class TestYouTubeAnalyticsIntegrationModel(BaseTest):+ def test_oauth_config(self):+ config = OauthIntegration.oauth_config_for_kind("youtube-analytics")++ assert config.authorize_url == "https://accounts.google.com/o/oauth2/v2/auth"+ assert config.token_url == "https://oauth2.googleapis.com/token"+ assert config.client_id == "youtube-client-id"+ assert config.client_secret == "youtube-client-secret"+ assert config.id_path == "sub"+ assert config.name_path == "email"+ # A refresh token only comes back when consent is forced, and the sync depends on one.+ assert config.additional_authorize_params == {"access_type": "offline", "prompt": "consent"}++ def test_oauth_config_requests_analytics_and_channel_read_scopes(self):+ scopes = set(OauthIntegration.oauth_config_for_kind("youtube-analytics").scope.split())++ assert "https://www.googleapis.com/auth/yt-analytics.readonly" in scopes+ assert "https://www.googleapis.com/auth/youtube.readonly" in scopes+ # Channel reports carry no revenue metrics, so the monetary scope is never asked for.+ assert "https://www.googleapis.com/auth/yt-analytics-monetary.readonly" not in scopes++ @override_settings(YOUTUBE_ANALYTICS_APP_CLIENT_ID="", YOUTUBE_ANALYTICS_APP_CLIENT_SECRET="")+ def test_oauth_config_unconfigured_raises(self):+ with pytest.raises(NotImplementedError, match="YouTube Analytics app not configured"):+ OauthIntegration.oauth_config_for_kind("youtube-analytics")diff --git a/posthog/models/test/integration/test_postgres.py b/posthog/models/test/integration/test_postgres.pynew file mode 100644index 000000000000..0294b4b8d144--- /dev/null+++ b/posthog/models/test/integration/test_postgres.py@@ -0,0 +1,125 @@+"""Tests for direct-connection PostgreSQL-protocol integrations."""++from posthog.test.base import BaseTest++from parameterized import parameterized, parameterized_class++from posthog.models.integration import (+ MISSING_CERT_PATH,+ TLS,+ Authority,+ Credentials,+ Integration,+ PostgreSQLIntegration,+ RedshiftIntegration,+)+++@parameterized_class(+ [+ {+ "integration_cls": PostgreSQLIntegration,+ "integration_kind": Integration.IntegrationKind.POSTGRESQL,+ },+ {+ "integration_cls": RedshiftIntegration,+ "integration_kind": Integration.IntegrationKind.AWS_REDSHIFT,+ },+ ]+)+class TestPostgreSQLIntegrationModel(BaseTest):+ integration_kind: Integration.IntegrationKind+ integration_cls: type[RedshiftIntegration] | type[PostgreSQLIntegration]++ @parameterized.expand(+ [+ (+ "require_no_cert",+ {"ssl_mode": "require"},+ {},+ TLS(ssl_mode="require", ssl_root_cert=MISSING_CERT_PATH),+ ),+ (+ "require_system_cert",+ {"ssl_mode": "require", "ssl_root_cert": "system"},+ {},+ TLS(ssl_mode="require", ssl_root_cert="system"),+ ),+ (+ "verify_ca_with_cert",+ {+ "ssl_mode": "verify-ca",+ "ssl_root_cert": "-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----",+ },+ {},+ TLS(+ ssl_mode="verify-ca",+ ssl_root_cert="-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----",+ ),+ ),+ (+ "prefer_no_cert",+ {"ssl_mode": "prefer"},+ {},+ TLS(ssl_mode="prefer", ssl_root_cert=MISSING_CERT_PATH),+ ),+ ]+ )+ def test_tls_with_ssl_configs(self, _name, config_overrides, sensitive_config_overrides, expected_tls):+ config = {"host": "db.example.com", "port": 5432, "user": "exporter"}+ config.update(config_overrides)++ sensitive_config: dict = {"password": "hunter2"}+ sensitive_config.update(sensitive_config_overrides)++ integration = Integration.objects.create(+ team=self.team,+ kind=self.integration_kind,+ integration_id=f"{self.team.pk}-db.example.com-5432-exporter",+ config=config,+ sensitive_config=sensitive_config,+ )++ pq = self.integration_cls(integration)+ assert pq.tls() == expected_tls++ @parameterized.expand(+ [+ (+ "defaults",+ {},+ TLS(ssl_mode="require", ssl_root_cert=MISSING_CERT_PATH),+ ),+ (+ "system_cert",+ {"ssl_root_cert": "system"},+ TLS(ssl_mode="require", ssl_root_cert="system"),+ ),+ (+ "verify_full_with_cert",+ {"ssl_mode": "verify-full", "ssl_root_cert": "cert-data"},+ TLS(ssl_mode="verify-full", ssl_root_cert="cert-data"),+ ),+ ]+ )+ def test_integration_from_config(self, _name, overrides, expected_tls):+ kwargs = {+ "team_id": self.team.pk,+ "host": "localhost",+ "port": 5432,+ "user": "exporter",+ "password": "super-secret",+ }+ kwargs.update(overrides)++ integration = self.integration_cls.integration_from_config(**kwargs) # type: ignore+ pq = self.integration_cls(integration)++ assert pq.authority() == Authority(host="localhost", port=5432)+ assert pq.credentials() == Credentials(user="exporter", password="super-secret")+ assert pq.tls() == expected_tls++ assert "password" not in integration.config++ assert integration.sensitive_config["password"] == "super-secret"+ assert pq.integration_kind == self.integration_kinddiff --git a/posthog/models/test/integration/test_snowflake.py b/posthog/models/test/integration/test_snowflake.pynew file mode 100644index 000000000000..1a3f3da64f31--- /dev/null+++ b/posthog/models/test/integration/test_snowflake.py@@ -0,0 +1,167 @@+"""Tests for the Snowflake integration."""++import pytest+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models.integration import Integration, SnowflakeIntegration, SnowflakeIntegrationError+++class TestSnowflakeIntegrationModel(BaseTest):+ def test_integration_from_config_with_password_auth(self):+ integration = SnowflakeIntegration.integration_from_config(+ team_id=self.team.pk,+ name="prod-snowflake",+ account="myorg-myaccount",+ user="posthog_svc",+ authentication_type="password",+ password="secret",+ created_by=self.user,+ )+ assert integration.kind == Integration.IntegrationKind.SNOWFLAKE+ # The identifier is the user-supplied name, never a credential.+ assert integration.integration_id == "prod-snowflake"+ # account, user and authentication_type are non-sensitive and live in config.+ assert integration.config == {+ "name": "prod-snowflake",+ "account": "myorg-myaccount",+ "user": "posthog_svc",+ "authentication_type": "password",+ }+ assert integration.sensitive_config == {"password": "secret"}+ wrapped = SnowflakeIntegration(integration)+ assert wrapped.password == "secret"+ assert wrapped.private_key is None+ # display_name surfaces auth type and account so users can tell integrations apart.+ assert integration.display_name == "prod-snowflake (account: myorg-myaccount, password auth)"++ def test_integration_from_config_with_keypair_auth(self):+ integration = SnowflakeIntegration.integration_from_config(+ team_id=self.team.pk,+ name="prod-snowflake",+ account="myorg-myaccount",+ user="posthog_svc",+ authentication_type="keypair",+ private_key="-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----",+ private_key_passphrase="phrase",+ created_by=self.user,+ )+ assert integration.config["authentication_type"] == "keypair"+ assert integration.sensitive_config == {+ "private_key": "-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----",+ "private_key_passphrase": "phrase",+ }+ # A password from a switched auth mode must never linger alongside the key-pair material.+ assert "password" not in integration.sensitive_config+ wrapped = SnowflakeIntegration(integration)+ assert wrapped.private_key == "-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----"+ assert wrapped.private_key_passphrase == "phrase"++ def test_integration_from_config_keypair_without_passphrase(self):+ integration = SnowflakeIntegration.integration_from_config(+ team_id=self.team.pk,+ name="prod-snowflake",+ account="myorg-myaccount",+ user="posthog_svc",+ authentication_type="keypair",+ private_key="-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----",+ )+ assert integration.sensitive_config == {+ "private_key": "-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----"+ }++ @parameterized.expand(+ [+ ("missing_name", "", "myorg-myaccount", "posthog_svc"),+ ("missing_account", "prod-snowflake", "", "posthog_svc"),+ ("missing_user", "prod-snowflake", "myorg-myaccount", ""),+ ]+ )+ def test_integration_from_config_requires_name_account_user(self, _name, name, account, user):+ with pytest.raises(SnowflakeIntegrationError, match="Name, account, and user must be provided"):+ SnowflakeIntegration.integration_from_config(+ team_id=self.team.pk,+ name=name,+ account=account,+ user=user,+ authentication_type="password",+ password="secret",+ )++ @parameterized.expand(+ [+ ("password_missing_password", "password", {}, "Password is required"),+ ("keypair_missing_private_key", "keypair", {}, "Private key is required"),+ ("invalid_auth_type", "oauth", {"password": "secret"}, "Invalid authentication type: oauth"),+ ]+ )+ def test_integration_from_config_rejects_invalid_auth(self, _name, authentication_type, credentials, expected):+ with pytest.raises(SnowflakeIntegrationError, match=expected):+ SnowflakeIntegration.integration_from_config(+ team_id=self.team.pk,+ name="prod-snowflake",+ account="myorg-myaccount",+ user="posthog_svc",+ authentication_type=authentication_type,+ **credentials,+ )++ def test_integration_from_config_rejects_duplicate_name(self):+ SnowflakeIntegration.integration_from_config(+ team_id=self.team.pk,+ name="prod-snowflake",+ account="myorg-myaccount",+ user="posthog_svc",+ authentication_type="password",+ password="secret",+ )+ with pytest.raises(SnowflakeIntegrationError, match="An integration named 'prod-snowflake' already exists"):+ SnowflakeIntegration.integration_from_config(+ team_id=self.team.pk,+ name="prod-snowflake",+ account="other-account",+ user="other_user",+ authentication_type="password",+ password="other-secret",+ )+ assert Integration.objects.filter(team=self.team, integration_id="prod-snowflake").count() == 1++ @parameterized.expand(+ [+ ("simple", "myaccount"),+ ("org_account", "myorg-myaccount"),+ ("legacy_locator", "xy12345.us-east-1.aws"),+ ]+ )+ def test_validate_account_accepts_valid_identifiers(self, _name, account):+ SnowflakeIntegration.validate_account(account) # must not raise++ @parameterized.expand(+ [+ ("full_url", "https://myaccount.snowflakecomputing.com"),+ ("with_path", "myaccount/foo"),+ ("with_at", "user@myaccount"),+ ("with_colon", "myaccount:443"),+ ("with_fragment", "myaccount#"),+ ("with_whitespace", "my account"),+ ("empty", ""),+ ]+ )+ def test_validate_account_rejects_malformed_identifiers(self, _name, account):+ with pytest.raises(SnowflakeIntegrationError, match="invalid account identifier"):+ SnowflakeIntegration.validate_account(account)++ def test_wrapping_wrong_kind_raises(self):+ integration = Integration.objects.create(+ team=self.team, kind=Integration.IntegrationKind.AWS_S3, integration_id="x"+ )+ with pytest.raises(SnowflakeIntegrationError, match="is not a Snowflake integration"):+ SnowflakeIntegration(integration)++ def test_wrapping_missing_config_raises(self):+ integration = Integration.objects.create(+ team=self.team, kind=Integration.IntegrationKind.SNOWFLAKE, integration_id="x", config={}+ )+ with pytest.raises(SnowflakeIntegrationError, match="missing"):+ SnowflakeIntegration(integration)diff --git a/posthog/models/test/test_firebase_integration.py b/posthog/models/test/test_firebase_integration.pyindex b21cac5a04c3..6e8bc604cc05 100644--- a/posthog/models/test/test_firebase_integration.py+++ b/posthog/models/test/test_firebase_integration.py@@ -41,8 +41,8 @@ def _mock_credentials(token: str = "access-token-1", expiry_offset: int = 3600):class TestFirebaseIntegration(BaseTest):- @patch("posthog.models.integration.GoogleRequest")- @patch("posthog.models.integration.service_account.Credentials.from_service_account_info")+ @patch("posthog.models.integration.push.GoogleRequest")+ @patch("posthog.models.integration.push.service_account.Credentials.from_service_account_info")def _create_firebase_integration(self, mock_from_sa, mock_google_request, **overrides) -> Integration:mock_from_sa.return_value = _mock_credentials()key_info = overrides.pop("key_info", FAKE_KEY_INFO)@@ -112,16 +112,16 @@ class TestFirebaseIntegration(BaseTest):assert first.id != second.id- @patch("posthog.models.integration.GoogleRequest")- @patch("posthog.models.integration.service_account.Credentials.from_service_account_info")+ @patch("posthog.models.integration.push.GoogleRequest")+ @patch("posthog.models.integration.push.service_account.Credentials.from_service_account_info")def test_validates_service_account_key(self, mock_from_sa, mock_google_request):mock_from_sa.side_effect = Exception("invalid key")with self.assertRaises(ValidationError):FirebaseIntegration.integration_from_key(FAKE_KEY_INFO, self.team.id)- @patch("posthog.models.integration.GoogleRequest")- @patch("posthog.models.integration.service_account.Credentials.from_service_account_info")+ @patch("posthog.models.integration.push.GoogleRequest")+ @patch("posthog.models.integration.push.service_account.Credentials.from_service_account_info")def test_validates_project_id_present(self, mock_from_sa, mock_google_request):mock_from_sa.return_value = _mock_credentials()key_info_no_project = {k: v for k, v in FAKE_KEY_INFO.items() if k != "project_id"}@@ -200,9 +200,9 @@ class TestFirebaseIntegration(BaseTest):# Expired with a generous thresholdassert wrapper.access_token_expired(time_threshold=timedelta(seconds=3500)) is True- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.GoogleRequest")- @patch("posthog.models.integration.service_account.Credentials.from_service_account_info")+ @patch("posthog.models.integration.push.reload_integrations_on_workers")+ @patch("posthog.models.integration.push.GoogleRequest")+ @patch("posthog.models.integration.push.service_account.Credentials.from_service_account_info")def test_refresh_access_token(self, mock_from_sa, mock_google_request, mock_reload):integration = Integration.objects.create(team=self.team,@@ -226,9 +226,9 @@ class TestFirebaseIntegration(BaseTest):assert integration.sensitive_config["access_token"] == "new-token"mock_reload.assert_called_once_with(self.team.id, [integration.id])- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.GoogleRequest")- @patch("posthog.models.integration.service_account.Credentials.from_service_account_info")+ @patch("posthog.models.integration.push.reload_integrations_on_workers")+ @patch("posthog.models.integration.push.GoogleRequest")+ @patch("posthog.models.integration.push.service_account.Credentials.from_service_account_info")def test_get_access_token_refreshes_when_expired(self, mock_from_sa, mock_google_request, mock_reload):integration = Integration.objects.create(team=self.team,diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pydeleted file mode 100644index bce0ad9e7ee0..000000000000--- a/posthog/models/test/test_integration_model.py+++ /dev/null@@ -1,5274 +0,0 @@-import json-import time-import base64-import hashlib-from datetime import UTC, datetime, timedelta-from typing import Optional, cast-from urllib.parse import parse_qs, urlencode--import pytest-from freezegun import freeze_time-from posthog.test.base import BaseTest-from unittest.mock import MagicMock, call, patch--from django.core.cache import cache-from django.db import connection-from django.test import SimpleTestCase, override_settings-from django.utils import timezone--import requests-from disposable_email_domains import blocklist as disposable_email_domains_list-from parameterized import parameterized, parameterized_class-from prometheus_client import REGISTRY-from rest_framework.exceptions import ValidationError--from posthog.egress.github.transport import (- GitHubEgressBudgetExhausted,- GitHubRateLimitError,- raise_if_github_rate_limited,-)-from posthog.egress.limiter.policies import Priority-from posthog.helpers.encrypted_fields import EncryptedJSONField-from posthog.models.github_integration_base import (- GITHUB_BRANCH_CACHE_TTL_SECONDS,- GITHUB_REPOSITORY_CACHE_TTL_SECONDS,- GitHubIntegrationBase,-)-from posthog.models.instance_setting import set_instance_setting-from posthog.models.integration import (- CONFIG_LEGACY_OAUTH_CLIENT,- MISSING_CERT_PATH,- POSTHOG_CONNECT_DEFAULT_SCOPES,- POSTHOG_CONNECT_IDENTITY_SCOPES,- TLS,- Authority,- AWSS3Integration,- Credentials,- DatabricksIntegration,- DatabricksIntegrationError,- DuplicateNameError,- EmailIntegration,- GitHubIntegration,- GitHubIntegrationError,- GoogleAdsIntegration,- GoogleCloudIntegration,- GoogleCloudServiceAccountIntegration,- InstagramIntegration,- Integration,- IntegrationError,- JiraIntegration,- LinearIntegration,- OauthIntegration,- PostgreSQLIntegration,- RedshiftIntegration,- S3CompatibleIntegration,- SlackIntegration,- SnowflakeIntegration,- SnowflakeIntegrationError,- UndecryptedIntegrationSecretError,- invalidate_github_repository_caches_for_installation,- oauth_refresh_failure_reason,- oauth_refresh_terminal_counter,- refresh_backoff_active,- validate_aws_credentials,-)-from posthog.models.organization import Organization-from posthog.models.team.team import Team--from products.workflows.backend.providers import SESProvider---def get_db_field_value(field, model_id):- cursor = connection.cursor()- cursor.execute(f"select {field} from posthog_integration where id='{model_id}';")- return cursor.fetchone()[0]---def update_db_field_value(field, model_id, value):- cursor = connection.cursor()- cursor.execute(f"update posthog_integration set {field}='{value}' where id='{model_id}';")---def test_slack_oauth_requests_the_recently_approved_scopes_on_every_instance():- # These waited on Slack app-directory review and were only requested on DEV/local. They're- # approved now, so every instance asks for them — the features behind them (DM assistant,- # canvas and file artifact delivery, inbox channel creation) are dark without them.- from posthog.models.integration import POSTHOG_SLACK_SCOPE-- requested = set(POSTHOG_SLACK_SCOPE.split(","))-- assert {"assistant:write", "im:history", "canvases:write", "files:write", "channels:manage"} <= requested---class TestIntegrationModel(BaseTest):- def create_integration(- self, kind: str, config: Optional[dict] = None, sensitive_config: Optional[dict] = None- ) -> Integration:- _config = {"refreshed_at": int(time.time()), "expires_in": 3600}- _sensitive_config = {"refresh_token": "REFRESH", "id_token": None}- _config.update(config or {})- _sensitive_config.update(sensitive_config or {})-- return Integration.objects.create(team=self.team, kind=kind, config=_config, sensitive_config=_sensitive_config)-- def test_sensitive_config_encrypted(self):- # Fernet encryption is deterministic, but has a temporal component and utilizes os.urandom() for the IV- with freeze_time("2024-01-01T00:01:00Z"):- with patch("os.urandom", return_value=b"\x00" * 16):- integration = self.create_integration("slack")-- assert integration.sensitive_config == {"refresh_token": "REFRESH", "id_token": None}- assert (- get_db_field_value("sensitive_config", integration.id)- == '{"id_token": null, "refresh_token": "gAAAAABlkgC8AAAAAAAAAAAAAAAAAAAAAJgmFh-MNX9haUNHNfYLvULI6vSRYVd3o8xd4f8xBkWEWAa5RJ2ikOM2dsW5_9F7Mw=="}'- )-- # update the value to non-encrypted and check it still loads-- update_db_field_value(- "sensitive_config", integration.id, '{"id_token": null, "refresh_token": "REFRESH2"}'- )- integration.refresh_from_db()- assert integration.sensitive_config == {"id_token": None, "refresh_token": "REFRESH2"}- assert (- get_db_field_value("sensitive_config", integration.id)- == '{"id_token": null, "refresh_token": "REFRESH2"}'- )-- integration.save()- # The field should now be encrypted- assert integration.sensitive_config == {"id_token": None, "refresh_token": "REFRESH2"}- assert (- get_db_field_value("sensitive_config", integration.id)- == '{"id_token": null, "refresh_token": "gAAAAABlkgC8AAAAAAAAAAAAAAAAAAAAAHlWz9QOMnXDvmix-z5lNG4v0VcO9lGWejmcE_BXHXPZ1wNkb-38JupntWbshBrfFQ=="}'- )-- @parameterized.expand([("access_token",), ("refresh_token",)])- def test_oauth_token_property_raises_if_still_encrypted(self, field_name: str) -> None:- # `sensitive_config` uses `ignore_decrypt_errors=True`, so a value that fails to decrypt- # under every configured key comes back as raw Fernet ciphertext instead of raising. If the- # `access_token`/`refresh_token` properties didn't check for that, this ciphertext would- # get sent straight to the third-party API as the live credential.- integration = Integration(team=self.team, kind="stripe", sensitive_config={field_name: "gAAAAABleftover=="})- with pytest.raises(UndecryptedIntegrationSecretError):- getattr(integration, field_name)-- @parameterized.expand([("access_token",), ("refresh_token",)])- def test_oauth_token_property_passes_through_decrypted_value(self, field_name: str) -> None:- integration = Integration(team=self.team, kind="stripe", sensitive_config={field_name: "a-real-token"})- assert getattr(integration, field_name) == "a-real-token"-- @parameterized.expand([("access_token",), ("refresh_token",)])- def test_oauth_token_property_recovers_an_over_encrypted_value(self, field_name: str) -> None:- # Saving an integration whose secret failed to decrypt re-encrypts the ciphertext, so the- # stored value ends up with an extra layer and one decrypt still leaves ciphertext behind.- # The secret is intact underneath, so the connection must keep working.- integration = self.create_integration("stripe", sensitive_config={field_name: "a-real-token"})- field = cast(EncryptedJSONField, Integration._meta.get_field("sensitive_config")) # type: ignore[misc]- stored = json.loads(get_db_field_value("sensitive_config", integration.id))- update_db_field_value(- "sensitive_config",- integration.id,- json.dumps({**stored, field_name: field.encrypt(stored[field_name])}),- )-- integration.refresh_from_db()-- assert getattr(integration, field_name) == "a-real-token"-- def test_slack_integration_config(self):- set_instance_setting("SLACK_APP_CLIENT_ID", None)- set_instance_setting("SLACK_APP_CLIENT_SECRET", None)- set_instance_setting("SLACK_APP_SIGNING_SECRET", None)-- assert not SlackIntegration.slack_config() == {}-- set_instance_setting("SLACK_APP_CLIENT_ID", "client-id")- set_instance_setting("SLACK_APP_CLIENT_SECRET", "client-secret")- set_instance_setting("SLACK_APP_SIGNING_SECRET", "not-so-secret")-- assert SlackIntegration.slack_config() == {- "SLACK_APP_CLIENT_ID": "client-id",- "SLACK_APP_CLIENT_SECRET": "client-secret",- "SLACK_APP_SIGNING_SECRET": "not-so-secret",- }---class TestLinearIntegrationModel(BaseTest):- def create_integration(self) -> Integration:- return Integration.objects.create(- team=self.team,- kind="linear",- config={"data": {"viewer": {"organization": {"urlKey": "posthog"}}}},- sensitive_config={"access_token": "ACCESS_TOKEN"},- )-- def test_search_issues_raises_on_graphql_errors(self):- # An expired token or GraphQL error must not be reported as a valid empty result.- linear = LinearIntegration(self.create_integration())- with patch.object(linear, "query", return_value={"errors": [{"message": "unauthorized"}]}):- with self.assertRaises(ValidationError):- linear.search_issues("boom")-- @parameterized.expand(- [- ("top_level_errors", {"errors": [{"message": "forbidden"}]}),- ("mutation_failure", {"data": {"attachmentCreate": {"success": False}}}),- ]- )- def test_create_attachment_raises_on_failure(self, _name, response_body):- # Linear reports failures in a 200 body; treating them as success would let callers- # persist references whose promised back-link was never created.- linear = LinearIntegration(self.create_integration())- with patch.object(linear, "query", return_value=response_body):- with self.assertRaises(ValidationError):- linear.create_attachment("LIN-123", "https://us.posthog.com/error_tracking/issue-id")-- def test_create_issue_raises_when_issue_creation_fails(self):- # A failed issueCreate must not fall through to an attachment attempt and a- # persisted {"id": None} reference.- linear = LinearIntegration(self.create_integration())- with patch.object(linear, "query", return_value={"errors": [{"message": "forbidden"}]}) as mock_query:- with self.assertRaises(ValidationError):- linear.create_issue(- "https://us.posthog.com/error_tracking/issue-id",- {"team_id": "team-id", "title": "Title", "description": "Description"},- )- assert mock_query.call_count == 1-- def test_create_issue_succeeds_when_attachment_fails(self):- # The Linear issue already exists when the attachment fires, so a failed back-link- # must not fail the create (retrying would duplicate the issue).- linear = LinearIntegration(self.create_integration())- with patch.object(- linear,- "query",- side_effect=[- {"data": {"issueCreate": {"issue": {"identifier": "LIN-123"}}}},- {"errors": [{"message": "rate limited"}]},- ],- ):- result = linear.create_issue(- "https://us.posthog.com/error_tracking/issue-id",- {"team_id": "team-id", "title": "Title", "description": "Description"},- )-- assert result == {"id": "LIN-123"}-- def test_create_issue_passes_user_fields_as_graphql_variables(self):- linear = LinearIntegration(self.create_integration())- with patch.object(- linear,- "query",- side_effect=[- {"data": {"issueCreate": {"issue": {"identifier": "LIN-123"}}}},- {"data": {"attachmentCreate": {"success": True}}},- ],- ) as mock_query:- attachment_url = f'https://us.posthog.com/project/{self.team.id}/error_tracking/issue-id" }} mutation {{'- result = linear.create_issue(- attachment_url,- {- "team_id": 'team-id" } mutation {',- "title": 'Title "quoted"',- "description": "Description",- },- )-- assert result == {"id": "LIN-123"}- issue_query = mock_query.call_args_list[0].args[0]- issue_variables = mock_query.call_args_list[0].kwargs["variables"]- attachment_query = mock_query.call_args_list[1].args[0]- attachment_variables = mock_query.call_args_list[1].kwargs["variables"]-- assert 'team-id" } mutation {' not in issue_query- assert 'Title "quoted"' not in issue_query- assert issue_variables == {- "title": 'Title "quoted"',- "description": "Description",- "teamId": 'team-id" } mutation {',- }- assert 'issue-id" } mutation {' not in attachment_query- assert attachment_variables["issueId"] == "LIN-123"- assert attachment_variables["title"] == "PostHog issue"- assert attachment_variables["url"].endswith(f'/project/{self.team.id}/error_tracking/issue-id" }} mutation {{')---class TestJiraIntegrationModel:- @staticmethod- def integration() -> MagicMock:- return MagicMock(- id=123,- team_id=456,- kind=Integration.IntegrationKind.JIRA,- config={"cloud_id": "cloud-id"},- sensitive_config={"access_token": "access-token"},- )-- @patch("posthog.models.integration.capture_exception")- @patch("posthog.models.integration.requests.post")- def test_create_issue_captures_structured_error_details(self, mock_post, mock_capture_exception):- mock_post.return_value.status_code = 400- mock_post.return_value.headers = {"Content-Type": "application/json"}- mock_post.return_value.json.return_value = {- "errorMessages": ["Issue type is not available"],- "errors": {"summary": "Summary is required"},- }-- with pytest.raises(ValidationError) as error:- JiraIntegration(self.integration()).create_issue(- {"project_key": "ENG", "title": "Checkout failed", "description": "Details"}- )-- assert error.value.args[0] == (- "Could not create the Jira issue. Check the project's issue settings and try again."- )- captured_error = mock_capture_exception.call_args.args[0]- assert str(captured_error) == "Jira issue creation failed"- assert mock_capture_exception.call_args.kwargs["additional_properties"] == {- "jira_status_code": 400,- "jira_response_content_type": "application/json",- "integration_id": 123,- "team_id": 456,- "jira_error_messages": ["Issue type is not available"],- "jira_field_errors": {"summary": "Summary is required"},- "jira_response_keys": ["errorMessages", "errors"],- }-- @patch("posthog.models.integration.capture_exception")- @patch("posthog.models.integration.requests.post")- def test_create_issue_captures_non_json_response_metadata(self, mock_post, mock_capture_exception):- mock_post.return_value.status_code = 502- mock_post.return_value.headers = {"Content-Type": "text/html"}- mock_post.return_value.json.side_effect = ValueError-- with pytest.raises(ValidationError) as error:- JiraIntegration(self.integration()).create_issue(- {"project_key": "ENG", "title": "Checkout failed", "description": "Details"}- )-- assert error.value.args[0] == (- "Could not create the Jira issue. Check the project's issue settings and try again."- )- assert mock_capture_exception.call_args.kwargs["additional_properties"] == {- "jira_status_code": 502,- "jira_response_content_type": "text/html",- "integration_id": 123,- "team_id": 456,- }---class TestOauthIntegrationModel(BaseTest):- mock_settings = {- "SALESFORCE_CONSUMER_KEY": "salesforce-client-id",- "SALESFORCE_CONSUMER_SECRET": "salesforce-client-secret",- "HUBSPOT_APP_CLIENT_ID": "hubspot-client-id",- "HUBSPOT_APP_CLIENT_SECRET": "hubspot-client-secret",- "GOOGLE_ADS_APP_CLIENT_ID": "google-client-id",- "GOOGLE_ADS_APP_CLIENT_SECRET": "google-client-secret",- "GOOGLE_CALENDAR_APP_CLIENT_ID": "google-calendar-client-id",- "GOOGLE_CALENDAR_APP_CLIENT_SECRET": "google-calendar-client-secret",- "LINKEDIN_APP_CLIENT_ID": "linkedin-client-id",- "LINKEDIN_APP_CLIENT_SECRET": "linkedin-client-secret",- "TIKTOK_ADS_CLIENT_ID": "tiktok-app-id",- "TIKTOK_ADS_CLIENT_SECRET": "tiktok-secret",- }-- def create_integration(- self, kind: str, config: Optional[dict] = None, sensitive_config: Optional[dict] = None- ) -> Integration:- _config = {"refreshed_at": int(time.time()), "expires_in": 3600}- _sensitive_config = {"refresh_token": "REFRESH"}- _config.update(config or {})- _sensitive_config.update(sensitive_config or {})-- return Integration.objects.create(team=self.team, kind=kind, config=_config, sensitive_config=_sensitive_config)-- def test_authorize_url_raises_if_not_configured(self):- with pytest.raises(NotImplementedError):- OauthIntegration.authorize_url("salesforce", token="state_token", next="/projects/test")-- def test_authorize_url(self):- with self.settings(**self.mock_settings):- url = OauthIntegration.authorize_url("salesforce", token="state_token", next="/projects/test")- base, _, query = url.partition("?")- params = {k: v[0] for k, v in parse_qs(query).items()}- assert base == "https://login.salesforce.com/services/oauth2/authorize"- assert params == {- "client_id": "salesforce-client-id",- "scope": "full refresh_token",- "redirect_uri": "https://localhost:8010/integrations/salesforce/callback",- "response_type": "code",- "state": "next=%2Fprojects%2Ftest&token=state_token",- "code_challenge": params["code_challenge"],- "code_challenge_method": "S256",- }-- def test_authorize_url_carries_initiating_team_id_in_state(self):- with self.settings(**self.mock_settings):- url = OauthIntegration.authorize_url(- "salesforce", token="state_token", next="/projects/test", team_id=228502- )- params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}- state = {k: v[0] for k, v in parse_qs(params["state"]).items()}- assert state["team_id"] == "228502"-- def test_authorize_url_omits_team_id_when_not_provided(self):- with self.settings(**self.mock_settings):- url = OauthIntegration.authorize_url("salesforce", token="state_token", next="/projects/test")- params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}- assert "team_id" not in parse_qs(params["state"])-- def test_authorize_url_pkce_challenge_matches_cached_verifier(self):- with self.settings(**self.mock_settings):- url = OauthIntegration.authorize_url("salesforce", token="pkce_state_token", next="/projects/test")- params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}- verifier = cache.get("oauth_pkce_verifier/pkce_state_token")- assert verifier- expected_challenge = (- base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()- )- assert params["code_challenge"] == expected_challenge-- def test_authorize_url_without_pkce_has_no_challenge(self):- with self.settings(**self.mock_settings):- url = OauthIntegration.authorize_url("hubspot", token="no_pkce_state_token", next="/projects/test")- assert "code_challenge" not in url- assert cache.get("oauth_pkce_verifier/no_pkce_state_token") is None-- def test_authorize_url_with_additional_authorize_params(self):- with self.settings(**self.mock_settings):- url = OauthIntegration.authorize_url("google-ads", token="state_token", next="/projects/test")- assert (- url- == "https://accounts.google.com/o/oauth2/v2/auth?client_id=google-client-id&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fadwords+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&redirect_uri=https%3A%2F%2Flocalhost%3A8010%2Fintegrations%2Fgoogle-ads%2Fcallback&response_type=code&state=next%3D%252Fprojects%252Ftest%26token%3Dstate_token&access_type=offline&prompt=consent"- )-- def test_authorize_url_google_calendar(self):- with self.settings(**self.mock_settings):- url = OauthIntegration.authorize_url("google-calendar", token="state_token", next="/projects/test")- assert (- url- == "https://accounts.google.com/o/oauth2/v2/auth?client_id=google-calendar-client-id&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&redirect_uri=https%3A%2F%2Flocalhost%3A8010%2Fintegrations%2Fgoogle-calendar%2Fcallback&response_type=code&state=next%3D%252Fprojects%252Ftest%26token%3Dstate_token&access_type=offline&prompt=consent"- )-- @patch("posthog.models.integration.requests.post")- def test_integration_from_oauth_response(self, mock_post):- with self.settings(**self.mock_settings):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "FAKES_ACCESS_TOKEN",- "refresh_token": "FAKE_REFRESH_TOKEN",- "instance_url": "https://fake.salesforce.com",- "expires_in": 3600,- }-- with freeze_time("2024-01-01T12:00:00Z"):- integration = OauthIntegration.integration_from_oauth_response(- "salesforce",- self.team.id,- self.user,- {- "code": "code",- "state": "next=/projects/test",- },- )-- assert integration.team == self.team- assert integration.created_by == self.user-- assert integration.config == {- "instance_url": "https://fake.salesforce.com",- "refreshed_at": 1704110400,- "expires_in": 3600,- }- assert integration.sensitive_config == {- "access_token": "FAKES_ACCESS_TOKEN",- "refresh_token": "FAKE_REFRESH_TOKEN",- "id_token": None,- }-- @patch("posthog.models.integration.requests.post")- def test_integration_from_oauth_response_sends_pkce_verifier(self, mock_post):- with self.settings(**self.mock_settings):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "FAKES_ACCESS_TOKEN",- "instance_url": "https://fake.salesforce.com",- "expires_in": 3600,- }-- # authorize_url caches the verifier; the exchange must send that exact value and consume it- url = OauthIntegration.authorize_url("salesforce", token="exchange_state_token", next="/projects/test")- challenge = parse_qs(url.partition("?")[2])["code_challenge"][0]- verifier = cache.get("oauth_pkce_verifier/exchange_state_token")-- OauthIntegration.integration_from_oauth_response(- "salesforce",- self.team.id,- self.user,- {"code": "code", "state": "next=%2Fprojects%2Ftest&token=exchange_state_token"},- )-- sent = mock_post.call_args.kwargs["data"]- assert sent["code_verifier"] == verifier- assert (- base64.urlsafe_b64encode(hashlib.sha256(sent["code_verifier"].encode()).digest()).rstrip(b"=").decode()- == challenge- )- assert cache.get("oauth_pkce_verifier/exchange_state_token") is None-- @parameterized.expand(- [- (- "json_error_body",- 400,- {- "error": "invalid_grant",- "error_description": "Authorization code does not exist or has expired.",- },- None,- '{"error":"invalid_grant","error_description":"Authorization code does not exist or has expired."}',- ["invalid_grant", "Authorization code does not exist"],- ),- (- "non_json_error_body",- 502,- None,- ValueError("not json"),- "<html>Bad Gateway</html>",- ["salesforce"],- ),- ]- )- @patch("posthog.models.integration.requests.post")- def test_oauth_token_exchange_failure_raises_validation_error(- self, _name, status_code, json_return, json_side_effect, body_text, expected_in_message, mock_post- ):- """A failed token exchange must surface a ValidationError (→ DRF 400 with `detail`) so the- frontend toast renders something useful. Covers both well-formed JSON error bodies (where- we extract `error_description`) and non-JSON bodies (where the helper falls back to the- raw text or a status-only message)."""- with self.settings(**self.mock_settings):- mock_post.return_value.status_code = status_code- if json_side_effect is not None:- mock_post.return_value.json.side_effect = json_side_effect- else:- mock_post.return_value.json.return_value = json_return- mock_post.return_value.text = body_text-- with pytest.raises(ValidationError) as e:- OauthIntegration.integration_from_oauth_response(- "salesforce",- self.team.id,- self.user,- {"code": "code", "state": "next=/projects/test"},- )-- message = str(e.value).lower()- for fragment in expected_in_message:- assert fragment.lower() in message-- @patch("posthog.models.integration.requests.post")- def test_integration_errors_if_id_cannot_be_generated(self, mock_post):- with self.settings(**self.mock_settings):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "FAKES_ACCESS_TOKEN",- "refresh_token": "FAKE_REFRESH_TOKEN",- "not_instance_url": "https://fake.salesforce.com",- "expires_in": 3600,- }-- with pytest.raises(Exception):- OauthIntegration.integration_from_oauth_response(- "salesforce",- self.team.id,- self.user,- {- "code": "code",- "state": "next=/projects/test",- },- )-- @patch("posthog.models.integration.requests.post")- def test_tiktok_ads_oauth_without_advertiser_accounts_raises_validation_error(self, mock_post):- # TikTok completes OAuth even when the user granted no advertiser account, leaving- # `advertiser_ids` empty. That must surface as a ValidationError (→ 400 with an actionable- # message) rather than the bare Exception (→ 500) the missing-id guard would otherwise raise.- with self.settings(**self.mock_settings):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "code": 0,- "data": {"access_token": "FAKE_ACCESS_TOKEN", "advertiser_ids": []},- }-- with pytest.raises(ValidationError, match="ad accounts"):- OauthIntegration.integration_from_oauth_response(- "tiktok-ads",- self.team.id,- self.user,- {"code": "code", "state": "next=/projects/test"},- )-- @patch("posthog.models.integration.requests.post")- @patch("posthog.models.integration.requests.get")- def test_integration_fetches_info_from_token_info_url(self, mock_get, mock_post):- with self.settings(**self.mock_settings):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "FAKES_ACCESS_TOKEN",- "refresh_token": "FAKE_REFRESH_TOKEN",- "expires_in": 3600,- }-- mock_get.return_value.status_code = 200- mock_get.return_value.json.return_value = {- "hub_id": "hub_id",- "hub_domain": "hub_domain",- "user": "user",- "user_id": "user_id",- "should_not": "be_saved",- "scopes": [- "crm.objects.contacts.read",- "crm.objects.contacts.write",- ],- }-- with freeze_time("2024-01-01T12:00:00Z"):- integration = OauthIntegration.integration_from_oauth_response(- "hubspot",- self.team.id,- self.user,- {- "code": "code",- "state": "next=/projects/test",- },- )-- assert integration.config == {- "expires_in": 3600,- "hub_id": "hub_id",- "hub_domain": "hub_domain",- "user": "user",- "user_id": "user_id",- "refreshed_at": 1704110400,- "scopes": [- "crm.objects.contacts.read",- "crm.objects.contacts.write",- ],- }- assert integration.sensitive_config == {- "access_token": "FAKES_ACCESS_TOKEN",- "refresh_token": "FAKE_REFRESH_TOKEN",- "id_token": None,- }-- @patch("posthog.models.integration.requests.post")- def test_linkedin_integration_extracts_user_info_from_id_token(self, mock_post):- """- LinkedIn's /v2/userinfo endpoint has intermittent REVOKED_ACCESS_TOKEN errors,- so we extract user info from the id_token JWT instead.- """- import json-- # Create a mock JWT id_token with sub and email in the payload- jwt_payload = {"sub": "linkedin_user_123", "email": "[email protected]", "iat": 1704110400}- encoded_payload = base64.urlsafe_b64encode(json.dumps(jwt_payload).encode()).decode().rstrip("=")- mock_id_token = f"eyJhbGciOiJSUzI1NiJ9.{encoded_payload}.fake_signature"-- with self.settings(**self.mock_settings):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "FAKE_ACCESS_TOKEN",- "refresh_token": "FAKE_REFRESH_TOKEN",- "id_token": mock_id_token,- "expires_in": 3600,- }-- with freeze_time("2024-01-01T12:00:00Z"):- integration = OauthIntegration.integration_from_oauth_response(- "linkedin-ads",- self.team.id,- self.user,- {- "code": "code",- "state": "next=/projects/test",- },- )-- assert integration.team == self.team- assert integration.created_by == self.user- # Verify sub and email were extracted from JWT- assert integration.config["sub"] == "linkedin_user_123"- assert integration.config["email"] == "[email protected]"- assert integration.config["refreshed_at"] == 1704110400- assert integration.config["expires_in"] == 3600-- assert integration.sensitive_config == {- "access_token": "FAKE_ACCESS_TOKEN",- "refresh_token": "FAKE_REFRESH_TOKEN",- "id_token": mock_id_token,- }-- def test_integration_access_token_expired(self):- now = datetime.now()- with freeze_time(now):- integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})-- with freeze_time(now):- # Access token is not expired- assert not OauthIntegration(integration).access_token_expired()-- with freeze_time(now + timedelta(seconds=1000) - timedelta(seconds=501)):- # After the expiry but before the threshold it is not expired- assert not OauthIntegration(integration).access_token_expired()-- with freeze_time(now + timedelta(seconds=1000) - timedelta(seconds=499)):- # After the threshold it is expired- assert OauthIntegration(integration).access_token_expired()-- with freeze_time(now + timedelta(seconds=1000)):- # After the threshold it is expired- assert OauthIntegration(integration).access_token_expired()-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_access_token(self, mock_post, mock_reload):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "REFRESHED_ACCESS_TOKEN",- "expires_in": 1000,- }-- integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})-- with freeze_time("2024-01-01T14:00:00Z"):- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- mock_post.assert_called_with(- "https://api.hubapi.com/oauth/v1/token",- data={- "grant_type": "refresh_token",- "client_id": "hubspot-client-id",- "client_secret": "hubspot-client-secret",- "refresh_token": "REFRESH",- },- timeout=10,- allow_redirects=False,- )-- assert integration.config["expires_in"] == 1000- assert integration.config["refreshed_at"] == 1704117600- assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"-- mock_reload.assert_called_once_with(self.team.id, [integration.id])-- @parameterized.expand(- [- (- "rotated",- {- "access_token": "REFRESHED_ACCESS_TOKEN",- "refresh_token": "ROTATED_REFRESH_TOKEN",- "expires_in": 1000,- },- "ROTATED_REFRESH_TOKEN",- ),- ("not_rotated", {"access_token": "REFRESHED_ACCESS_TOKEN", "expires_in": 1000}, "REFRESH"),- ]- )- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_access_token_refresh_token_handling(- self, _name, token_response, expected_refresh_token, mock_post, mock_reload- ):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = token_response-- integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})-- with freeze_time("2024-01-01T14:00:00Z"):- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"- assert integration.sensitive_config["refresh_token"] == expected_refresh_token-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_tiktok_ads_refresh_uses_business_api_and_unwraps_data(self, mock_post, mock_reload):- # TikTok Business API refreshes against its own endpoint with app_id/secret (JSON) and nests- # the refreshed tokens under `data` — not the Login Kit client_key/open.tiktokapis.com flow.- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "code": 0,- "data": {"access_token": "REFRESHED_ACCESS_TOKEN", "refresh_token": "ROTATED_REFRESH_TOKEN"},- }-- integration = self.create_integration(kind="tiktok-ads", config={"expires_in": 1000})-- with freeze_time("2024-01-01T14:00:00Z"):- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- mock_post.assert_called_with(- "https://business-api.tiktok.com/open_api/v1.3/oauth2/refresh_token/",- json={- "app_id": "tiktok-app-id",- "secret": "tiktok-secret",- "refresh_token": "REFRESH",- "grant_type": "refresh_token",- },- headers={"Content-Type": "application/json"},- timeout=10,- )- assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"- assert integration.sensitive_config["refresh_token"] == "ROTATED_REFRESH_TOKEN"-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_access_token_handles_errors(self, mock_post, mock_reload):- mock_post.return_value.status_code = 401- mock_post.return_value.json.return_value = {"error": "BROKEN"}-- integration = self.create_integration(kind="hubspot", config={"expires_in": 1000, "refreshed_at": 1700000000})-- with freeze_time("2024-01-01T14:00:00Z"):- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- assert integration.config["expires_in"] == 1000- assert integration.config["refreshed_at"] == 1700000000- assert integration.errors == "TOKEN_REFRESH_FAILED"-- mock_reload.assert_not_called()-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_failed_refresh_leaves_stored_secrets_byte_identical(self, mock_post, mock_reload):- # A failed refresh has no new secrets to store, and rewriting the ones already there is how- # a secret that couldn't be decrypted (handed back as raw ciphertext by- # `ignore_decrypt_errors`) gains a permanent extra encryption layer.- mock_post.return_value.status_code = 401- mock_post.return_value.json.return_value = {"error": "BROKEN"}-- integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})- stored_before = get_db_field_value("sensitive_config", integration.id)-- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- assert get_db_field_value("sensitive_config", integration.id) == stored_before- assert integration.errors == "TOKEN_REFRESH_FAILED"-- @patch("posthog.models.integration.requests.post")- def test_refresh_with_unreadable_secret_goes_terminal_without_calling_the_provider(self, mock_post):- # Posting ciphertext as the refresh token just earns an invalid_grant every minute forever.- # Nothing about the stored secret can change, so the sweep must stop and the reconnect- # prompt must show instead.- integration = self.create_integration(kind="hubspot", sensitive_config={"refresh_token": "gAAAAAleftover=="})-- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- mock_post.assert_not_called()- assert integration.errors == "TOKEN_REFRESH_FAILED"- assert refresh_backoff_active(integration) is True-- integration.refresh_from_db()- assert integration.config["refresh_terminal"] is True-- def _mock_token_response(self, status_code: int, token: Optional[str]) -> MagicMock:- response = MagicMock()- response.status_code = status_code- response.json.return_value = {"access_token": token, "expires_in": 1000} if token else {}- response.text = "error"- return response-- @parameterized.expand(- [- # Primary works: the fallback must not fire, even when configured, and the grant is no- # longer tied to the legacy app - so the reconnect prompt must stop showing.- ("primary_ok", True, [(200, "primary-token")], "primary-token", "", 1, True, False),- # A token issued by the previous app only refreshes with the fallback pair. Flagging it- # is what identifies the connections that break when the legacy app is retired.- ("fallback_rescues", True, [(401, None), (200, "fallback-token")], "fallback-token", "", 2, False, True),- # Both credentials failing still marks the integration errored so the reconnect banner shows.- ("both_fail", True, [(401, None), (401, None)], None, "TOKEN_REFRESH_FAILED", 2, True, True),- # Without a fallback configured, behavior is identical to before: a single attempt, no retry.- ("no_fallback_no_retry", False, [(401, None)], None, "TOKEN_REFRESH_FAILED", 1, False, False),- ]- )- def test_refresh_falls_back_to_previous_credentials(- self,- _name,- has_fallback,- responses,- expected_token,- expected_errors,- expected_calls,- initial_legacy_flag,- expected_legacy_flag,- ):- fallbacks = {"bing-ads": {"client_id": "old-app-id", "client_secret": "old-app-secret"}} if has_fallback else {}- config = {"expires_in": 1000}- if initial_legacy_flag:- config[CONFIG_LEGACY_OAUTH_CLIENT] = True- integration = self.create_integration(kind="bing-ads", config=config)-- with (- self.settings(- BING_ADS_CLIENT_ID="new-app-id",- BING_ADS_CLIENT_SECRET="new-app-secret",- OAUTH_CLIENT_FALLBACKS=fallbacks,- ),- patch("posthog.models.integration.reload_integrations_on_workers"),- patch(- "posthog.models.integration.requests.post",- side_effect=[self._mock_token_response(status, token) for status, token in responses],- ) as mock_post,- ):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert mock_post.call_count == expected_calls- assert integration.errors == expected_errors- assert integration.config.get(CONFIG_LEGACY_OAUTH_CLIENT, False) == expected_legacy_flag- if expected_token is not None:- assert integration.sensitive_config["access_token"] == expected_token-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_network_error_marks_failed_without_raising(self, mock_post, mock_reload):- # A timeout must not escape refresh_access_token: the Celery sweep would error out before- # recording the failure, leaving the integration without a backoff or the reconnect state.- mock_post.side_effect = requests.Timeout("timed out")- integration = self.create_integration(kind="bing-ads", config={"expires_in": 1000})-- with self.settings(BING_ADS_CLIENT_ID="new-app-id", BING_ADS_CLIENT_SECRET="new-app-secret"):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert integration.errors == "TOKEN_REFRESH_FAILED"- assert integration.config.get("refresh_failure_count") == 1- assert integration.config.get("refresh_next_attempt_at")-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_primary_network_error_still_tries_fallback(self, mock_post, mock_reload):- # A network error on the primary credentials must not skip the fallback attempt.- mock_post.side_effect = [requests.Timeout("timed out"), self._mock_token_response(200, "fallback-token")]- integration = self.create_integration(kind="bing-ads", config={"expires_in": 1000})-- with self.settings(- BING_ADS_CLIENT_ID="new-app-id",- BING_ADS_CLIENT_SECRET="new-app-secret",- OAUTH_CLIENT_FALLBACKS={"bing-ads": {"client_id": "old-app-id", "client_secret": "old-app-secret"}},- ):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert mock_post.call_count == 2- assert integration.errors == ""- assert integration.sensitive_config["access_token"] == "fallback-token"-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_access_token_resets_errors(self, mock_post, mock_reload):- """Test that errors field is reset to empty string after successful refresh_access_token"""- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "REFRESHED_ACCESS_TOKEN",- "expires_in": 1000,- }-- integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})- integration.errors = "TOKEN_REFRESH_FAILED"- integration.save()-- with freeze_time("2024-01-01T14:00:00Z"):- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert integration.errors == ""-- @parameterized.expand(- [- ("first_failure", 0, 120),- ("second_failure", 1, 240),- ("capped", 10, 3600),- ]- )- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_failure_schedules_backoff(self, _name, prior_failures, expected_delay, mock_post, mock_reload):- mock_post.return_value.status_code = 401- mock_post.return_value.json.return_value = {"error": "BROKEN"}-- config: dict = {"expires_in": 1000}- if prior_failures:- config["refresh_failure_count"] = prior_failures- integration = self.create_integration(kind="hubspot", config=config)-- with freeze_time("2024-01-01T14:00:00Z"):- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert integration.config["refresh_failure_count"] == prior_failures + 1- assert integration.config["refresh_next_attempt_at"] == 1704117600 + expected_delay- assert "refresh_terminal" not in integration.config-- @parameterized.expand(- [- # (error, prior total failures, prior invalid_grant streak, expect terminal)- ("invalid_grant_below_threshold", "invalid_grant", 3, 3, False),- ("invalid_grant_at_threshold", "invalid_grant", 4, 4, True),- ("invalid_client_never_terminal", "invalid_client", 10, 0, False),- # A single invalid_grant after a run of other failures must not go terminal - the- # streak has to be invalid_grant all the way through- ("mixed_failures_not_terminal", "invalid_grant", 4, 0, False),- ]- )- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_failure_terminal_state(- self, _name, error, prior_failures, prior_grant_streak, expected_terminal, mock_post, mock_reload- ):- mock_post.return_value.status_code = 400- mock_post.return_value.json.return_value = {"error": error}-- config: dict = {"expires_in": 1000, "refresh_failure_count": prior_failures}- if prior_grant_streak:- config["refresh_invalid_grant_count"] = prior_grant_streak- integration = self.create_integration(kind="hubspot", config=config)-- terminal_counter = oauth_refresh_terminal_counter.labels(kind="hubspot")- counter_before = terminal_counter._value.get()-- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert bool(integration.config.get("refresh_terminal")) is expected_terminal- # The transition is the fleet die-off signal: exactly one increment when a row goes- # terminal, none otherwise- assert terminal_counter._value.get() - counter_before == (1 if expected_terminal else 0)-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_already_terminal_row_does_not_recount_on_bypassing_refresh(self, mock_post, mock_reload):- mock_post.return_value.status_code = 400- mock_post.return_value.json.return_value = {"error": "invalid_grant"}-- # On-demand refreshes bypass the backoff, so a dead row can keep failing after the- # transition - it must not inflate the die-off counter again- integration = self.create_integration(- kind="hubspot",- config={- "expires_in": 1000,- "refresh_failure_count": 6,- "refresh_invalid_grant_count": 6,- "refresh_terminal": True,- },- )-- terminal_counter = oauth_refresh_terminal_counter.labels(kind="hubspot")- counter_before = terminal_counter._value.get()-- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert integration.config.get("refresh_terminal") is True- assert terminal_counter._value.get() == counter_before-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_non_invalid_grant_failure_resets_grant_streak(self, mock_post, mock_reload):- mock_post.return_value.status_code = 503- mock_post.return_value.json.return_value = {"error": "server_error"}-- integration = self.create_integration(- kind="hubspot",- config={"expires_in": 1000, "refresh_failure_count": 4, "refresh_invalid_grant_count": 4},- )-- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert "refresh_invalid_grant_count" not in integration.config- assert "refresh_terminal" not in integration.config-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_success_clears_backoff_state(self, mock_post, mock_reload):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {"access_token": "REFRESHED_ACCESS_TOKEN", "expires_in": 1000}-- integration = self.create_integration(- kind="hubspot",- config={- "expires_in": 1000,- "refresh_failure_count": 5,- "refresh_invalid_grant_count": 5,- "refresh_next_attempt_at": 1704117600,- "refresh_terminal": True,- },- )-- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert "refresh_failure_count" not in integration.config- assert "refresh_invalid_grant_count" not in integration.config- assert "refresh_next_attempt_at" not in integration.config- assert "refresh_terminal" not in integration.config-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_failure_with_non_json_body_still_backs_off(self, mock_post, mock_reload):- mock_post.return_value.status_code = 502- mock_post.return_value.json.side_effect = ValueError("not json")- mock_post.return_value.text = "<html>Bad Gateway</html>"-- integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})-- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert integration.errors == "TOKEN_REFRESH_FAILED"- assert integration.config["refresh_failure_count"] == 1-- @parameterized.expand(- [- ("invalid_grant", 400, {"error": "invalid_grant"}, None, "invalid_grant"),- ("invalid_client", 401, {"error": "invalid_client"}, None, "invalid_client"),- ("server_error", 502, {}, None, "http_5xx"),- ("other_4xx", 400, {"error": "temporarily_unavailable"}, None, "other"),- ("non_string_error", 400, {"error": {"code": 1}}, None, "other"),- ("reddit_dead_grant_shape", 400, {"message": "Bad Request", "error": 400}, "reddit-ads", "invalid_grant"),- ("reddit_shape_on_other_kind", 400, {"message": "Bad Request", "error": 400}, "hubspot", "other"),- ("reddit_5xx", 502, {"message": "Bad Gateway", "error": 502}, "reddit-ads", "http_5xx"),- ("reddit_oauth_error_code", 400, {"error": "invalid_grant"}, "reddit-ads", "invalid_grant"),- (- "hubspot_dead_hub_shape",- 400,- {"status": "BAD_HUB", "message": "missing or unknown hub id", "error": "access_denied"},- "hubspot",- "invalid_grant",- ),- (- "hubspot_shape_on_other_kind",- 400,- {"status": "BAD_HUB", "error": "access_denied"},- "salesforce",- "other",- ),- ("hubspot_bad_hub_5xx_is_outage", 502, {"status": "BAD_HUB"}, "hubspot", "http_5xx"),- (- "hubspot_bad_refresh_token_still_oauth_code",- 400,- {"status": "BAD_REFRESH_TOKEN", "error": "invalid_grant"},- "hubspot",- "invalid_grant",- ),- ("rate_limited", 429, {"status": "error", "errorType": "RATE_LIMIT"}, "hubspot", "rate_limited"),- ("rate_limited_any_kind", 429, {}, None, "rate_limited"),- (- "meta_dead_token",- 400,- {- "error": {- "message": "Error validating access token: The session has been invalidated because the user changed their password.",- "type": "OAuthException",- "code": 190,- "error_subcode": 460,- }- },- "meta-ads",- "invalid_grant",- ),- (- "instagram_dead_token",- 400,- {"error": {"type": "OAuthException", "code": 190}},- "instagram",- "invalid_grant",- ),- ("meta_shape_on_other_kind", 400, {"error": {"code": 190}}, "hubspot", "other"),- ("meta_non_grant_error_code", 400, {"error": {"type": "OAuthException", "code": 10}}, "meta-ads", "other"),- ("meta_190_5xx_is_outage", 502, {"error": {"code": 190}}, "meta-ads", "http_5xx"),- ]- )- def test_oauth_refresh_failure_reason(self, _name, status_code, body, kind, expected):- assert oauth_refresh_failure_reason(status_code, body, kind=kind) == expected-- @patch("posthog.models.integration.requests.post")- def test_reconnect_clears_backoff_state(self, mock_post):- # A customer re-authing must un-brick a terminal integration, or "please reconnect"- # comms leave them permanently dead.- with self.settings(**self.mock_settings):- mock_post.return_value.status_code = 200- # integration_from_oauth_response pops fields out of the response dict, so each call- # needs a fresh one- mock_post.return_value.json.side_effect = lambda: {- "access_token": "FAKES_ACCESS_TOKEN",- "refresh_token": "FAKE_REFRESH_TOKEN",- "instance_url": "https://fake.salesforce.com",- "expires_in": 3600,- }- oauth_payload = {"code": "code", "state": "next=/projects/test"}-- integration = OauthIntegration.integration_from_oauth_response(- "salesforce", self.team.id, self.user, oauth_payload- )- integration.config.update(- {"refresh_failure_count": 5, "refresh_next_attempt_at": 1704117600, "refresh_terminal": True}- )- integration.save()-- reconnected = OauthIntegration.integration_from_oauth_response(- "salesforce", self.team.id, self.user, oauth_payload- )-- assert reconnected.id == integration.id- assert "refresh_failure_count" not in reconnected.config- assert "refresh_next_attempt_at" not in reconnected.config- assert "refresh_terminal" not in reconnected.config-- @patch("posthog.models.integration.requests.post")- def test_salesforce_integration_without_expires_in_initial_response(self, mock_post):- """Test that Salesforce integrations without expires_in get default 1 hour expiry"""- with self.settings(**self.mock_settings):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "FAKES_ACCESS_TOKEN",- "refresh_token": "FAKE_REFRESH_TOKEN",- "instance_url": "https://fake.salesforce.com",- # Note: no expires_in field- }-- with freeze_time("2024-01-01T12:00:00Z"):- integration = OauthIntegration.integration_from_oauth_response(- "salesforce",- self.team.id,- self.user,- {- "code": "code",- "state": "next=/projects/test",- },- )-- # Should have default 1 hour (3600 seconds) expiry- assert integration.config["expires_in"] == 3600- assert integration.config["refreshed_at"] == 1704110400-- def test_salesforce_access_token_expired_without_expires_in(self):- """Test that Salesforce tokens without expires_in info use 1 hour default"""- now = datetime.now()- with freeze_time(now):- # Create integration without expires_in- integration = self.create_integration(- kind="salesforce",- config={"refreshed_at": int(time.time())}, # No expires_in- sensitive_config={"refresh_token": "REFRESH"},- )-- oauth_integration = OauthIntegration(integration)-- with freeze_time(now):- # Token should not be expired initially- assert not oauth_integration.access_token_expired()-- with freeze_time(now + timedelta(minutes=29)):- # Should not be expired before 30 minutes (half of 1 hour default)- assert not oauth_integration.access_token_expired()-- with freeze_time(now + timedelta(minutes=31)):- # Should be expired after 30 minutes (halfway point of 1 hour)- assert oauth_integration.access_token_expired()-- def test_non_salesforce_access_token_expired_without_expires_in(self):- """Test that non-Salesforce integrations without expires_in return False"""- now = datetime.now()- with freeze_time(now):- # Create non-Salesforce integration without expires_in - override the default- integration = Integration.objects.create(- team=self.team,- kind="hubspot",- config={"refreshed_at": int(time.time())}, # No expires_in- sensitive_config={"refresh_token": "REFRESH"},- )-- oauth_integration = OauthIntegration(integration)-- with freeze_time(now + timedelta(hours=5)):- # Should never expire without expires_in for non-Salesforce- assert not oauth_integration.access_token_expired()-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_salesforce_refresh_access_token_without_expires_in_response(self, mock_post, mock_reload):- """Test that Salesforce refresh without expires_in in response gets 1 hour default"""- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "REFRESHED_ACCESS_TOKEN",- # Note: no expires_in field in refresh response- }-- integration = self.create_integration(kind="salesforce", config={"expires_in": 1000})-- with freeze_time("2024-01-01T14:00:00Z"):- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- # Should have default 1 hour (3600 seconds) expiry- assert integration.config["expires_in"] == 3600- assert integration.config["refreshed_at"] == 1704117600- assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"-- mock_reload.assert_called_once_with(self.team.id, [integration.id])-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_salesforce_refresh_uses_instance_url_for_sandbox(self, mock_post, mock_reload):- # Sandbox integrations are stored as kind="salesforce" (the sandbox is a token-exchange- # fallback in the OAuth callback), so the config's instance_url is the only signal that- # the refresh must go to test.salesforce.com or the org's own host rather than the- # hardcoded prod token URL. Salesforce rejects a sandbox refresh_token posted to- # login.salesforce.com, which shows up to users as "Authentication token could not be- # refreshed. Please reconnect." within a few hours of connecting.- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "REFRESHED_ACCESS_TOKEN",- "expires_in": 3600,- }-- sandbox_instance_url = "https://ryan-co--sandbox.sandbox.my.salesforce.com"- integration = self.create_integration(- kind="salesforce",- config={"instance_url": sandbox_instance_url},- )-- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- assert integration.errors == ""- assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"-- called_url = mock_post.call_args.args[0]- assert called_url == f"{sandbox_instance_url}/services/oauth2/token"-- @parameterized.expand(- [- ("attacker_https", "https://attacker.example.com"),- ("attacker_lookalike_suffix", "https://salesforce.com.attacker.example"),- ("attacker_lookalike_prefix", "https://acmesalesforce.com"),- ("http_scheme_downgrade", "http://acme.my.salesforce.com"),- ("with_userinfo", "https://user:[email protected]"),- ("with_port", "https://acme.my.salesforce.com:8443"),- ("invalid_port_raises_valueerror", "https://acme.my.salesforce.com:abc"),- ("garbage_value", "not a url"),- ("empty_value", ""),- ]- )- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_salesforce_refresh_rejects_untrusted_instance_url(self, _name, bad_instance_url, mock_post, mock_reload):- # If a future write path (a partial_update action, an admin tool, a data migration)- # lets an attacker set instance_url, the refresh must not POST client_secret +- # refresh_token to that origin - the client_secret is fleet-wide and its leak forces- # rotation and reconnect for every Salesforce integration. Any instance_url that isn't- # an https .salesforce.com host falls back to the hardcoded prod token URL, and the- # refresh must not follow redirects that would move the secret to another host.- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "REFRESHED_ACCESS_TOKEN",- "expires_in": 3600,- }-- integration = self.create_integration(- kind="salesforce",- config={"instance_url": bad_instance_url},- )-- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- called_url = mock_post.call_args.args[0]- assert called_url == "https://login.salesforce.com/services/oauth2/token"-- called_kwargs = mock_post.call_args.kwargs- assert called_kwargs["allow_redirects"] is False-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_non_salesforce_refresh_access_token_preserves_none_expires_in(self, mock_post, mock_reload):- """Test that non-Salesforce integrations preserve None expires_in from refresh response"""- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "REFRESHED_ACCESS_TOKEN",- # Note: no expires_in field in refresh response- }-- integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})-- with freeze_time("2024-01-01T14:00:00Z"):- with self.settings(**self.mock_settings):- OauthIntegration(integration).refresh_access_token()-- # Should preserve None for non-Salesforce- assert integration.config["expires_in"] is None- assert integration.config["refreshed_at"] == 1704117600- assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"-- mock_reload.assert_called_once_with(self.team.id, [integration.id])-- @patch("posthog.models.integration.requests.post")- def test_stripe_integration_from_oauth_response_uses_apps_endpoint_and_basic_auth(self, mock_post):- # Stripe Apps OAuth (api.stripe.com/v1/oauth/token) is a different system from- # Stripe Connect OAuth (connect.stripe.com/oauth/token): it authenticates the- # token exchange with HTTP Basic (secret as username, no password) and accepts- # only `code` + `grant_type` in the body. Codes minted by `marketplace.stripe.com`- # cannot be redeemed at the Connect endpoint.- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "FAKE_ACCESS",- "refresh_token": "FAKE_REFRESH",- "stripe_user_id": "acct_123",- "account_name": "Test Account",- "expires_in": 3600,- }-- with self.settings(- STRIPE_APP_CLIENT_ID="ca_test_clientid",- STRIPE_APP_SECRET_KEY="sk_test_secret",- ):- OauthIntegration.integration_from_oauth_response(- "stripe",- self.team.id,- self.user,- {"code": "ac_real_code"},- )-- call = mock_post.call_args- assert call.args[0] == "https://api.stripe.com/v1/oauth/token"- assert call.kwargs["data"] == {"code": "ac_real_code", "grant_type": "authorization_code"}- assert call.kwargs["auth"].username == "sk_test_secret"- assert call.kwargs["auth"].password == ""-- def test_stripe_authorize_url_uses_live_client_id_by_default(self):- with self.settings(- STRIPE_APP_CLIENT_ID="ca_live_clientid",- STRIPE_APP_SECRET_KEY="sk_live_secret",- STRIPE_APP_OVERRIDE_AUTHORIZE_URL="",- ):- url = OauthIntegration.authorize_url("stripe", token="state_token", next="/projects/test")- assert "client_id=ca_live_clientid" in url-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_stripe_refresh_access_token_uses_apps_endpoint_and_basic_auth(self, mock_post, mock_reload):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {"access_token": "REFRESHED", "expires_in": 1000}-- integration = self.create_integration(kind="stripe", config={"expires_in": 1000})-- with self.settings(- STRIPE_APP_CLIENT_ID="ca_test_clientid",- STRIPE_APP_SECRET_KEY="sk_test_secret",- ):- OauthIntegration(integration).refresh_access_token()-- call = mock_post.call_args- assert call.args[0] == "https://api.stripe.com/v1/oauth/token"- assert call.kwargs["data"] == {"refresh_token": "REFRESH", "grant_type": "refresh_token"}- assert call.kwargs["auth"].username == "sk_test_secret"- assert call.kwargs["auth"].password == ""-- mock_reload.assert_called_once_with(self.team.id, [integration.id])-- @patch("posthog.models.integration.requests.post")- def test_stripe_oauth_does_not_persist_is_sandbox(self, mock_post):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "FAKE_ACCESS",- "refresh_token": "FAKE_REFRESH",- "stripe_user_id": "acct_live_1",- "account_name": "Live Account",- "expires_in": 3600,- }-- with self.settings(- STRIPE_APP_CLIENT_ID="ca_live_clientid",- STRIPE_APP_SECRET_KEY="sk_live_secret",- ):- integration = OauthIntegration.integration_from_oauth_response(- "stripe",- self.team.id,- self.user,- {"code": "ac_live_code"},- )-- assert "is_sandbox" not in integration.config---class TestPosthogConnectIntegration(BaseTest):- connect_settings = {- "POSTHOG_CONNECT_BASE_URL_US": "https://us.posthog.com",- "POSTHOG_CONNECT_OAUTH_CLIENT_ID_US": "us-client-id",- "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_US": "us-secret",- "POSTHOG_CONNECT_BASE_URL_EU": "https://eu.posthog.com",- "POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU": "eu-client-id",- "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU": "eu-secret",- "POSTHOG_CONNECT_BASE_URL_DEV": "http://localhost:8000",- "POSTHOG_CONNECT_OAUTH_CLIENT_ID_DEV": "dev-client-id",- "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_DEV": "dev-secret",- }-- @parameterized.expand(- [- ("US", "https://us.posthog.com/oauth/authorize", "us-client-id"),- ("EU", "https://eu.posthog.com/oauth/authorize", "eu-client-id"),- ("DEV", "http://localhost:8000/oauth/authorize", "dev-client-id"),- ]- )- def test_authorize_url_targets_selected_region(self, region, expected_base, expected_client_id):- with self.settings(**self.connect_settings):- url = OauthIntegration.authorize_url(- "posthog", token="tok", next="/projects/test", region=region, scopes=["task:read", "task:write"]- )- base, _, query = url.partition("?")- params = {k: v[0] for k, v in parse_qs(query).items()}- assert base == expected_base- assert params["client_id"] == expected_client_id- # User-selected scopes plus the always-appended identity scopes needed for /oauth/userinfo.- assert params["scope"] == "task:read task:write openid email"- # Host comes from SITE_URL, which differs by environment; assert the stable callback suffix.- assert params["redirect_uri"].endswith("/integrations/posthog/callback")- # posthog uses PKCE- assert params["code_challenge_method"] == "S256"- # Region is carried in state so the callback (on the connecting cell) exchanges the code- # against the correct target cell.- state = {k: v[0] for k, v in parse_qs(params["state"]).items()}- assert state["region"] == region- assert state["token"] == "tok"-- def test_authorize_url_lowercases_region_input(self):- with self.settings(**self.connect_settings):- url = OauthIntegration.authorize_url("posthog", token="tok", region="eu", scopes=["task:read"])- assert url.startswith("https://eu.posthog.com/oauth/authorize")- outer = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}- state = {k: v[0] for k, v in parse_qs(outer["state"]).items()}- assert state["region"] == "EU"-- def test_authorize_url_defaults_to_task_scopes_when_none_selected(self):- with self.settings(**self.connect_settings):- url = OauthIntegration.authorize_url("posthog", token="tok", region="US", scopes=None)- params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}- expected = " ".join([*POSTHOG_CONNECT_DEFAULT_SCOPES, *POSTHOG_CONNECT_IDENTITY_SCOPES])- assert params["scope"] == expected-- def test_authorize_url_unknown_region_raises(self):- with self.settings(**self.connect_settings):- with pytest.raises(NotImplementedError):- OauthIntegration.authorize_url("posthog", token="tok", region="ASIA", scopes=["task:read"])-- def test_authorize_url_unconfigured_region_raises(self):- unconfigured = {- **self.connect_settings,- "POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU": "",- "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU": "",- }- with self.settings(**unconfigured):- with pytest.raises(NotImplementedError):- OauthIntegration.authorize_url("posthog", token="tok", region="EU", scopes=["task:read"])-- @patch("posthog.models.integration.requests.get")- @patch("posthog.models.integration.requests.post")- def test_integration_from_oauth_response_persists_region_and_namespaces_id(self, mock_post, mock_get):- with self.settings(**self.connect_settings):- mock_post.return_value = MagicMock(status_code=200)- mock_post.return_value.json.return_value = {- "access_token": "AT",- "refresh_token": "RT",- "expires_in": 3600,- "scope": "task:read task:write openid email",- }- mock_get.return_value = MagicMock(status_code=200)- mock_get.return_value.json.return_value = {"sub": "user-uuid-123", "email": "[email protected]"}-- # posthog is a PKCE flow; the authorize step caches a verifier keyed on the state token.- cache.set("oauth_pkce_verifier/tok", "the-verifier")- state = urlencode({"next": "/", "token": "tok", "region": "EU"})- integration = OauthIntegration.integration_from_oauth_response(- "posthog", self.team.id, self.user, {"code": "auth-code", "state": state}- )-- # Token exchange must hit the region carried in state.- assert mock_post.call_args[0][0] == "https://eu.posthog.com/oauth/token"- assert integration.kind == "posthog"- assert integration.config["region"] == "EU"- # Dedup key is namespaced by region so the same account in two cells doesn't collide.- assert integration.integration_id == "EU:user-uuid-123"- assert integration.config["email"] == "[email protected]"- # Only the resource scopes are persisted (identity scopes dropped), for the caller-scope check.- assert integration.config["granted_scopes"] == ["task:read", "task:write"]- assert integration.sensitive_config["access_token"] == "AT"- assert integration.sensitive_config["refresh_token"] == "RT"-- @patch("posthog.models.integration.requests.post")- def test_integration_from_oauth_response_fails_closed_without_pkce_verifier(self, mock_post):- # No cached verifier (as if the authorize step was skipped / replayed). A first-party posthog- # flow must fail closed rather than exchange the code without PKCE.- with self.settings(**self.connect_settings):- cache.delete("oauth_pkce_verifier/tok")- state = urlencode({"next": "/", "token": "tok", "region": "EU"})- with pytest.raises(ValidationError):- OauthIntegration.integration_from_oauth_response(- "posthog", self.team.id, self.user, {"code": "auth-code", "state": state}- )- mock_post.assert_not_called()-- @patch("posthog.models.integration.requests.post")- def test_refresh_access_token_uses_persisted_region(self, mock_post):- with self.settings(**self.connect_settings):- integration = Integration.objects.create(- team=self.team,- kind="posthog",- integration_id="EU:user-uuid-123",- config={"region": "EU", "refreshed_at": int(time.time()) - 4000, "expires_in": 3600},- sensitive_config={"refresh_token": "RT", "access_token": "OLD"},- )- mock_post.return_value = MagicMock(status_code=200)- mock_post.return_value.json.return_value = {- "access_token": "NEW",- "refresh_token": "RT2",- "expires_in": 3600,- }-- OauthIntegration(integration).refresh_access_token()-- # Refresh must target the persisted region's token endpoint, not a static one.- assert mock_post.call_args[0][0] == "https://eu.posthog.com/oauth/token"- integration.refresh_from_db()- assert integration.sensitive_config["access_token"] == "NEW"---class TestGoogleCloudIntegrationModel(BaseTest):- mock_keyfile = {- "type": "service_account",- "project_id": "posthog-616",- "private_key_id": "df3e129a722a865cc3539b4e69507bad",- "private_key": "-----BEGIN PRIVATE KEY-----\nTHISISTHEKEY==\n-----END PRIVATE KEY-----\n",- "client_email": "[email protected]",- "client_id": "11223344556677889900",- "auth_uri": "https://accounts.google.com/o/oauth2/auth",- "token_uri": "https://oauth2.googleapis.com/token",- "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",- "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/not-a-topic%40posthog-616.iam.gserviceaccount.com",- "universe_domain": "googleapis.com",- }-- def create_integration(- self, kind: str, config: Optional[dict] = None, sensitive_config: Optional[dict] = None- ) -> Integration:- _config = {"refreshed_at": int(time.time()), "expires_in": 3600}- _sensitive_config = self.mock_keyfile- _config.update(config or {})- _sensitive_config.update(sensitive_config or {})-- return Integration.objects.create(team=self.team, kind=kind, config=_config, sensitive_config=_sensitive_config)-- @patch("google.oauth2.service_account.Credentials.from_service_account_info")- def test_integration_from_key(self, mock_credentials):- mock_credentials.return_value.project_id = "posthog-616"- mock_credentials.return_value.service_account_email = "posthog@"- mock_credentials.return_value.token = "ACCESS_TOKEN"- mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)- mock_credentials.return_value.refresh = lambda _: None-- with freeze_time("2024-01-01T12:00:00Z"):- integration = GoogleCloudIntegration.integration_from_key(- "google-pubsub",- self.mock_keyfile,- self.team.id,- self.user,- )-- assert integration.team == self.team- assert integration.created_by == self.user-- assert integration.config == {- "refreshed_at": 1704110400,- "expires_in": 3600,- }- assert integration.sensitive_config == {- "key_info": self.mock_keyfile,- "access_token": "ACCESS_TOKEN",- }-- @patch("google.oauth2.service_account.Credentials.from_service_account_info")- def test_integration_refresh_token(self, mock_credentials):- mock_credentials.return_value.project_id = "posthog-616"- mock_credentials.return_value.service_account_email = "posthog@"- mock_credentials.return_value.token = "ACCESS_TOKEN"- mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)- mock_credentials.return_value.refresh = lambda _: None-- with freeze_time("2024-01-01T12:00:00Z"):- integration = GoogleCloudIntegration.integration_from_key(- "google-pubsub",- self.mock_keyfile,- self.team.id,- self.user,- )-- with freeze_time("2024-01-01T12:00:00Z"):- assert GoogleCloudIntegration(integration).access_token_expired() is False-- with freeze_time("2024-01-01T14:00:00Z"):- assert GoogleCloudIntegration(integration).access_token_expired() is True-- mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600 * 3)-- GoogleCloudIntegration(integration).refresh_access_token()- assert GoogleCloudIntegration(integration).access_token_expired() is False-- assert integration.config == {- "refreshed_at": 1704110400 + 3600 * 2,- "expires_in": 3600,- }- assert integration.sensitive_config["access_token"] == "ACCESS_TOKEN"-- # Verify refresh used the nested key_info, not the whole sensitive_config- refresh_call = mock_credentials.call_args_list[-1]- assert refresh_call[0][0] == self.mock_keyfile-- @patch("google.oauth2.service_account.Credentials.from_service_account_info")- def test_refresh_token_fallback_pre_migration_sensitive_config(self, mock_credentials):- """Pre-migration integrations store key_info directly in sensitive_config (not nested under 'key_info').- The refresh logic should fall back to using the entire sensitive_config as key_info."""- mock_credentials.return_value.project_id = "posthog-616"- mock_credentials.return_value.service_account_email = "posthog@"- mock_credentials.return_value.token = "REFRESHED_TOKEN"- mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)- mock_credentials.return_value.refresh = lambda _: None-- # Simulate pre-migration state: key_info stored directly as sensitive_config,- # access_token in config- integration = Integration.objects.create(- team=self.team,- kind="google-pubsub",- integration_id="posthog@",- config={- "refreshed_at": 1704110400,- "expires_in": 1,- "access_token": "OLD_TOKEN",- },- sensitive_config=self.mock_keyfile,- )-- with freeze_time("2024-01-01T14:00:00Z"):- GoogleCloudIntegration(integration).refresh_access_token()-- # After refresh, sensitive_config should be migrated to the nested structure- assert integration.sensitive_config == {- "key_info": self.mock_keyfile,- "access_token": "REFRESHED_TOKEN",- }- assert "access_token" not in integration.config-- # Verify refresh used the whole sensitive_config as key_info (pre-migration fallback)- assert mock_credentials.call_args[0][0] == self.mock_keyfile-- @patch("google.oauth2.service_account.Credentials.from_service_account_info")- def test_get_access_token_reads_from_sensitive_config(self, mock_credentials):- mock_credentials.return_value.project_id = "posthog-616"- mock_credentials.return_value.service_account_email = "posthog@"- mock_credentials.return_value.token = "ACCESS_TOKEN"- mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)- mock_credentials.return_value.refresh = lambda _: None-- with freeze_time("2024-01-01T12:00:00Z"):- integration = GoogleCloudIntegration.integration_from_key(- "google-pubsub",- self.mock_keyfile,- self.team.id,- self.user,- )-- with freeze_time("2024-01-01T12:00:00Z"):- token = GoogleCloudIntegration(integration).get_access_token()-- assert token == "ACCESS_TOKEN"- assert "access_token" not in integration.config---class TestExtractFailingChecks(SimpleTestCase):- @parameterized.expand(- [- ("failure", "FAILURE", True),- ("timed_out", "TIMED_OUT", True),- ("action_required", "ACTION_REQUIRED", True),- ("startup_failure", "STARTUP_FAILURE", True),- ("cancelled", "CANCELLED", True),- ("stale", "STALE", True),- ("success", "SUCCESS", False),- ("neutral", "NEUTRAL", False),- ("skipped", "SKIPPED", False),- ]- )- def test_check_run_is_reported_only_when_its_conclusion_blocks_merge(self, _name, conclusion, expected_reported):- rollup = {- "contexts": {- "nodes": [- {- "__typename": "CheckRun",- "conclusion": conclusion,- "name": "unit tests",- "checkSuite": {"workflowRun": {"workflow": {"name": "CI"}}},- "detailsUrl": "https://ci/1",- }- ]- }- }-- failing = GitHubIntegrationBase._extract_failing_checks(rollup)-- assert (failing == [{"key": "CI/unit tests", "details_url": "https://ci/1"}]) is expected_reported---class TestGitHubIntegrationModel(BaseTest):- def setUp(self):- super().setUp()- cache.clear()-- def create_integration(self, config: Optional[dict] = None, sensitive_config: Optional[dict] = None) -> Integration:- _config = {"expires_at": 3600}- _sensitive_config = {"token": "REFRESH"}- _config.update(config or {})- _sensitive_config.update(sensitive_config or {})-- # Mirror production (integration_from_installation_id): the model integration_id field holds the- # GitHub App installation id, which is what egress telemetry keys its gauges on.- return Integration.objects.create(- team=self.team,- kind="github",- integration_id=(config or {}).get("installation_id"),- config=_config,- sensitive_config=_sensitive_config,- )-- def mock_github_client_request(- self,- status_code=201,- token="ACCESS_TOKEN",- repository_selection="all",- expires_in_hours=1,- error_text=None,- permissions=None,- ):- def _client_request(endpoint, method="GET"):- mock_response = MagicMock()- if method == "POST":- mock_response.status_code = status_code- dt = datetime.now(UTC) + timedelta(hours=expires_in_hours)- iso_time = dt.replace(tzinfo=None).isoformat(timespec="seconds") + "Z"-- if status_code == 201:- mock_response.json.return_value = {- "token": token,- "repository_selection": repository_selection,- "expires_at": iso_time,- **({"permissions": permissions} if permissions is not None else {}),- }- else:- mock_response.text = error_text or "error"- mock_response.json.return_value = {}- else:- mock_response.status_code = 200- mock_response.json.return_value = {- "account": {"type": "Organization", "login": "PostHog"},- **({"permissions": permissions} if permissions is not None else {}),- }- return mock_response-- return _client_request-- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_mint_scoped_installation_token_marks_uninstalled_installation(self, mock_client_request):- integration = self.create_integration(- {"installation_id": "INSTALL", "expires_in": 3600, "refreshed_at": 1704110400},- {"access_token": "FULL_TOKEN"},- )- mock_response = MagicMock(status_code=404, text="Not Found")- mock_response.json.return_value = {"message": "Not Found"}- mock_client_request.return_value = mock_response-- github = GitHubIntegration(integration)- with pytest.raises(GitHubIntegrationError):- github.mint_scoped_installation_token({"contents": "read"})-- # Without the permanently-gone marker, every scheduled run re-mints a dead installation- # forever — the marker is what lets callers skip it until the customer reconnects.- integration.refresh_from_db()- assert GitHubIntegration(integration).installation_unavailable() is True- assert "expires_in" not in integration.config-- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_mint_scoped_installation_token_downscopes_without_persisting(self, mock_client_request):- integration = self.create_integration({"installation_id": "INSTALL"}, {"access_token": "FULL_TOKEN"})- mock_response = MagicMock(status_code=201)- mock_response.json.return_value = {"token": "SCOPED_TOKEN", "expires_at": "2024-01-01T13:00:00Z"}- mock_client_request.return_value = mock_response-- token = GitHubIntegration(integration).mint_scoped_installation_token({"contents": "read"})-- assert token == "SCOPED_TOKEN"- # Without the permissions body the mint returns a FULL-permission token — a silent- # privilege escalation for every read-only sandbox.- assert mock_client_request.call_args.kwargs["json_body"] == {"permissions": {"contents": "read"}}- # The scoped token must never clobber the shared full-permission credential other flows read.- integration.refresh_from_db()- assert integration.sensitive_config == {"token": "REFRESH", "access_token": "FULL_TOKEN"}-- def test_get_diff_compares_branch_tips(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=200, text="diff --git a b")- with patch.object(github, "api_request", return_value=mock_response) as mock_get:- result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")- assert result == {- "success": True,- "diff": "diff --git a b",- "truncated": False,- }- mock_get.assert_called_once()- assert "/compare/master...feature/foo" in mock_get.call_args.args[1]-- def test_get_diff_pins_to_shas_when_given(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=200, text="diff --git a b")- with patch.object(github, "api_request", return_value=mock_response) as mock_get:- result = github.get_diff(- "PostHog/posthog",- target_branch="feature/foo",- base_branch="master",- target_sha="abc123f",- base_sha="def456a",- )- assert result["success"] is True- assert "/compare/def456a...abc123f" in mock_get.call_args.args[1]-- def test_get_diff_maps_upstream_error(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=404, text="Not Found")- with patch.object(github, "api_request", return_value=mock_response):- result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")- assert result == {"success": False, "error": "Not Found", "status_code": 404}-- def test_get_diff_handles_request_exception(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- with patch.object(github, "api_request", side_effect=GitHubIntegrationError("network error")):- result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")- assert result["success"] is False- assert result["status_code"] == 502-- def _github_for_org(self) -> GitHubIntegration:- integration = self.create_integration(- config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}- )- return GitHubIntegration(integration)-- @staticmethod- def _git_data_api_request(*, ref_status: int = 201):- calls: list[tuple[str, str, Optional[dict]]] = []-- def _request(method, path, **kwargs):- calls.append((method, path, kwargs.get("json_body")))- if "/git/ref/heads/" in path and method == "GET":- return MagicMock(status_code=200, **{"json.return_value": {"object": {"sha": "base-sha"}}})- if "/git/commits/" in path:- return MagicMock(status_code=200, **{"json.return_value": {"tree": {"sha": "base-tree"}}})- if path.endswith("/git/trees"):- return MagicMock(status_code=201, **{"json.return_value": {"sha": "new-tree"}})- if path.endswith("/git/commits"):- return MagicMock(status_code=201, **{"json.return_value": {"sha": "new-commit"}})- if path.endswith("/git/refs"):- return MagicMock(status_code=ref_status, text="Reference already exists")- if "/git/refs/heads/" in path and method == "PATCH":- return MagicMock(status_code=200)- raise AssertionError(f"unexpected request {method} {path}")-- return _request, calls-- def test_commit_files_to_branch_writes_every_file_in_one_commit(self):- github = self._github_for_org()- request, calls = self._git_data_api_request()-- with patch.object(github, "api_request", side_effect=request):- result = github.commit_files_to_branch(- "community-skills", "community-skill/x", "main", {"a.md": "A", "b/c.md": "C"}, "msg"- )-- assert result["success"] is True- assert result["commit_sha"] == "new-commit"- tree_body = next(body for _, path, body in calls if path.endswith("/git/trees"))- assert {entry["path"] for entry in tree_body["tree"]} == {"a.md", "b/c.md"}- assert tree_body["base_tree"] == "base-tree"- # The branch reference is written last, so a failure earlier leaves no branch in the repo.- assert calls[-1][1].endswith("/git/refs")-- def test_commit_files_to_branch_replaces_a_directory_rather_than_merging_into_it(self):- github = self._github_for_org()- request, calls = self._git_data_api_request()-- with patch.object(github, "api_request", side_effect=request):- result = github.commit_files_to_branch(- "community-skills",- "community-skill/x",- "main",- {"skills/x/SKILL.md": "S", "skills/x/refs/g.md": "G", "README.md": "R"},- "msg",- replace_directory="skills/x",- )-- assert result["success"] is True- subtree_body, tree_body = (body for _, path, body in calls if path.endswith("/git/trees"))- # No base_tree on the subtree, so it holds these files and nothing else. That is what makes a- # path the caller dropped disappear instead of surviving from the base.- assert "base_tree" not in subtree_body- assert {entry["path"] for entry in subtree_body["tree"]} == {"SKILL.md", "refs/g.md"}- assert tree_body["base_tree"] == "base-tree"- assert {(entry["path"], entry["type"]) for entry in tree_body["tree"]} == {- ("skills/x", "tree"),- ("README.md", "blob"),- }-- def test_commit_files_to_branch_force_updates_an_existing_branch(self):- github = self._github_for_org()- request, calls = self._git_data_api_request(ref_status=422)-- with patch.object(github, "api_request", side_effect=request):- result = github.commit_files_to_branch(- "community-skills", "community-skill/x", "main", {"a.md": "A"}, "msg"- )-- assert result["success"] is True- assert result["created_branch"] is False- method, path, body = calls[-1]- assert (method, path) == ("PATCH", "/repos/PostHog/community-skills/git/refs/heads/community-skill/x")- assert body == {"sha": "new-commit", "force": True}-- @parameterized.expand([("deleted", 204), ("already gone", 404)])- def test_delete_branch_treats_a_missing_branch_as_deleted(self, _name: str, status_code: int):- github = self._github_for_org()- with patch.object(github, "api_request", return_value=MagicMock(status_code=status_code)):- assert github.delete_branch("community-skills", "community-skill/x")["success"] is True-- @parameterized.expand([("the ref is gone", 404, True), ("the ref is still there", 200, False)])- def test_delete_branch_reads_the_ref_back_after_an_ambiguous_422(self, _name: str, recheck: int, deleted: bool):- github = self._github_for_org()-- def _request(method, path, **kwargs):- if method == "DELETE":- return MagicMock(status_code=422, text="Validation failed")- return MagicMock(status_code=recheck, **{"json.return_value": {"object": {"sha": "abc"}}})-- with patch.object(github, "api_request", side_effect=_request):- result = github.delete_branch("community-skills", "community-skill/x")-- # A 422 the caller reads as success is a branch left on a public repo with nobody warned.- assert result["success"] is deleted-- @parameterized.expand([("the expected commit", "mine", True), ("someone else's commit", "theirs", False)])- def test_delete_branch_with_an_expected_sha_only_deletes_its_own_commit(- self, _name: str, head_sha: str, deleted: bool- ):- github = self._github_for_org()- methods: list[str] = []-- def _request(method, path, **kwargs):- methods.append(method)- if method == "GET":- return MagicMock(status_code=200, **{"json.return_value": {"object": {"sha": head_sha}}})- return MagicMock(status_code=204)-- with patch.object(github, "api_request", side_effect=_request):- result = github.delete_branch("community-skills", "community-skill/x", expected_sha="mine")-- assert result["success"] is True- assert ("DELETE" in methods) is deleted-- def test_get_open_pull_request_for_head_returns_number_and_url(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=200)- mock_response.json.return_value = [- {- "number": 7,- "html_url": "https://github.com/PostHog/posthog/pull/7",- "base": {"ref": "master"},- }- ]- with patch.object(github, "_installation_authenticated_get", return_value=mock_response):- assert github.get_open_pull_request_for_head("PostHog/posthog", "posthog-code/fix") == {- "number": 7,- "url": "https://github.com/PostHog/posthog/pull/7",- "base": "master",- }-- def test_get_open_pr_base_for_head_returns_base_ref_of_open_pr(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=200)- mock_response.json.return_value = [- {- "number": 7,- "html_url": "https://github.com/PostHog/posthog/pull/7",- "base": {"ref": "master"},- "head": {"ref": "posthog-code/fix"},- }- ]- with patch.object(github, "_installation_authenticated_get", return_value=mock_response) as mock_get:- result = github.get_open_pr_base_for_head("PostHog/posthog", "posthog-code/fix")- assert result == "master"- # Query is scoped to open PRs whose head is the branch, in the repo owner's namespace.- assert mock_get.call_args.kwargs["params"] == {- "head": "PostHog:posthog-code/fix",- "state": "open",- "per_page": 1,- }-- def test_get_open_pr_base_for_head_returns_none_when_no_open_pr(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=200)- mock_response.json.return_value = []- with patch.object(github, "_installation_authenticated_get", return_value=mock_response):- assert github.get_open_pr_base_for_head("PostHog/posthog", "master") is None-- def test_get_open_pr_base_for_head_returns_none_on_error(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- with patch.object(github, "_installation_authenticated_get", return_value=None):- assert github.get_open_pr_base_for_head("PostHog/posthog", "posthog-code/fix") is None-- def test_get_pull_request_comments_merges_conversation_and_review_sorted(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)-- def fake_get(url, **kwargs):- response = MagicMock(status_code=200)- if "/issues/" in url:- response.json.return_value = [- {- "id": 2,- "user": {"login": "bob", "avatar_url": "https://a/bob.png"},- "body": "second",- "created_at": "2026-07-06T10:00:00Z",- "html_url": "https://github.com/PostHog/posthog/pull/1#issuecomment-2",- }- ]- else: # /pulls/{n}/comments — review comments- response.json.return_value = [- {- "id": 1,- "user": {"login": "alice", "avatar_url": "https://a/alice.png"},- "body": "first",- "created_at": "2026-07-06T09:00:00Z",- "html_url": "https://github.com/PostHog/posthog/pull/1#discussion_r1",- "path": "posthog/models.py",- }- ]- return response-- with patch.object(github, "_installation_authenticated_get", side_effect=fake_get):- result = github.get_pull_request_comments("PostHog/posthog", 1)-- assert result["success"] is True- # Merged and sorted oldest-first across both sources; review comment carries its file path,- # conversation comment does not.- assert [(c["author"], c["comment_type"], c["path"]) for c in result["comments"]] == [- ("alice", "review", "posthog/models.py"),- ("bob", "conversation", None),- ]-- def test_get_pull_request_comments_best_effort_when_one_source_fails(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)-- def fake_get(url, **kwargs):- if "/issues/" in url:- return None # conversation fetch fails- response = MagicMock(status_code=200)- response.json.return_value = [- {"id": 1, "user": {"login": "alice"}, "body": "x", "created_at": "2026-07-06T09:00:00Z"}- ]- return response-- with patch.object(github, "_installation_authenticated_get", side_effect=fake_get):- result = github.get_pull_request_comments("PostHog/posthog", 1)-- assert result["success"] is True- assert [c["author"] for c in result["comments"]] == ["alice"]-- @parameterized.expand(- [- ("success", "success", ("completed", "success")),- ("failure", "failure", ("completed", "failure")),- ("error", "error", ("completed", "failure")),- ("pending", "pending", ("in_progress", None)),- ("unknown", None, ("in_progress", None)),- ]- )- def test_map_commit_status_state(self, _name, state, expected):- assert GitHubIntegration._map_commit_status_state(state) == expected-- def test_get_pull_request_checks_merges_check_runs_and_statuses(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)-- def fake_get(url, **kwargs):- response = MagicMock(status_code=200)- if "/check-runs" in url:- response.json.return_value = {- "check_runs": [- {- "name": "unit",- "status": "completed",- "conclusion": "failure",- "html_url": "https://github.com/checks/1",- }- ]- }- else: # /status — legacy commit statuses- response.json.return_value = {- "statuses": [{"context": "buildkite", "state": "success", "target_url": "https://bk/1"}]- }- return response-- with (- patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}),- patch.object(github, "_installation_authenticated_get", side_effect=fake_get),- ):- result = github.get_pull_request_checks("PostHog/posthog", 1)-- assert result["success"] is True- assert result["checks"] == [- {"name": "unit", "status": "completed", "conclusion": "failure", "url": "https://github.com/checks/1"},- {"name": "buildkite", "status": "completed", "conclusion": "success", "url": "https://bk/1"},- ]-- def test_get_pull_request_checks_follows_pagination(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)-- def fake_get(url, **kwargs):- response = MagicMock(status_code=200)- response.links = {}- if "/check-runs" not in url:- response.json.return_value = {"statuses": []}- elif "page=2" in url:- response.json.return_value = {- "check_runs": [- {- "name": "second page",- "status": "completed",- "conclusion": "success",- }- ]- }- else:- response.json.return_value = {- "check_runs": [- {- "name": "first page",- "status": "completed",- "conclusion": "success",- }- ]- }- response.links = {- "next": {"url": "https://api.github.com/repos/PostHog/posthog/commits/abc123f/check-runs?page=2"}- }- return response-- with (- patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}),- patch.object(github, "_installation_authenticated_get", side_effect=fake_get),- ):- result = github.get_pull_request_checks("PostHog/posthog", 1)-- assert [check["name"] for check in result["checks"]] == ["first page", "second page"]-- @parameterized.expand([("check_runs",), ("statuses",)])- def test_get_pull_request_checks_fails_when_later_page_is_unavailable(self, failing_source):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)-- def fake_get(url, **kwargs):- source = "check_runs" if "/check-runs" in url else "statuses"- if source == failing_source and "page=2" in url:- return None-- response = MagicMock(status_code=200)- response.links = {}- response.json.return_value = {"check_runs": []} if source == "check_runs" else {"statuses": []}- if source == failing_source:- next_path = "check-runs" if source == "check_runs" else "status"- response.links = {- "next": {"url": f"https://api.github.com/repos/PostHog/posthog/commits/abc123f/{next_path}?page=2"}- }- return response-- with (- patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}),- patch.object(github, "_installation_authenticated_get", side_effect=fake_get),- ):- result = github.get_pull_request_checks("PostHog/posthog", 1)-- expected_noun = "check run" if failing_source == "check_runs" else "commit status"- assert result == {"success": False, "error": f"GitHub could not return every {expected_noun}"}-- def test_get_pull_request_checks_fails_when_pr_unavailable(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- with patch.object(github, "get_pull_request", return_value={"success": False, "error": "nope"}):- result = github.get_pull_request_checks("PostHog/posthog", 1)- assert result["success"] is False-- def test_get_diff_truncates_oversized_diff(self):- from posthog.models.integration import _MAX_DIFF_CHARS-- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- oversized = "x" * (_MAX_DIFF_CHARS + 100)- mock_response = MagicMock(status_code=200, text=oversized)- with patch.object(github, "api_request", return_value=mock_response):- result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")- assert result["success"] is True- assert result["truncated"] is True- assert len(result["diff"]) < len(oversized)- assert result["diff"].startswith("x" * 100)- assert "truncated" in result["diff"]-- @parameterized.expand(- [- ("repo_traversal", {"repository": "../../other/repo"}),- ("repo_extra_path", {"repository": "owner/repo/contents/x"}),- ("target_branch_traversal", {"target_branch": "../../../etc"}),- ("target_branch_query", {"target_branch": "main?ref=x"}),- ("base_branch_traversal", {"base_branch": "..%2f"}),- ("target_sha_not_hex", {"target_sha": "main?ref=x"}),- ("base_sha_not_hex", {"base_sha": "../../x"}),- ]- )- def test_get_diff_rejects_unsafe_values(self, _name, overrides):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- kwargs: dict = {"repository": "PostHog/posthog", "target_branch": "feature/foo", "base_branch": "master"}- kwargs.update(overrides)- with patch.object(github, "api_request") as mock_get:- result = github.get_diff(**kwargs)- assert result["success"] is False- assert result["status_code"] == 400- mock_get.assert_not_called()-- def test_get_diff_allows_nested_branch_names(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=200, text="diff --git a b")- with patch.object(github, "api_request", return_value=mock_response) as mock_get:- result = github.get_diff(- "PostHog/posthog", target_branch="feature/nested/branch", base_branch="release/v1.2"- )- assert result["success"] is True- mock_get.assert_called_once()-- @parameterized.expand(- [- ("traversal", "../../other/repo"),- ("extra_path_segment", "owner/repo/contents/secret"),- ("query_injection", "owner/repo?ref=x"),- ("fragment", "owner/repo#"),- ("bare_name", "repo"),- ]- )- def test_first_for_team_repository_rejects_unsafe_path_without_probing(self, _name, repository):- # The access check interpolates `repository` into an authenticated GET /repos/{repository};- # an unsafe path must be rejected before any request fires, so it can't probe other endpoints.- self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- with patch.object(GitHubIntegration, "installation_can_access_repository") as mock_access:- result = GitHubIntegration.first_for_team_repository(self.team.id, repository)- assert result is None- mock_access.assert_not_called()-- def test_first_for_team_repository_allows_owner_repo(self):- self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- with patch.object(GitHubIntegration, "installation_can_access_repository", return_value=True) as mock_access:- result = GitHubIntegration.first_for_team_repository(self.team.id, "PostHog/posthog")- assert result is not None- mock_access.assert_called_once_with("PostHog/posthog")-- @parameterized.expand(- [- ("owner_repo", "PostHog/posthog", "https://api.github.com/repos/PostHog/posthog/pulls/123"),- ("bare_repo", "posthog", "https://api.github.com/repos/PostHog/posthog/pulls/123"),- ]- )- def test_close_pull_request_patches_state_closed(self, _name, repository, expected_url):- # account.name lets a bare repo name resolve to {org}/{repo} via organization().- integration = self.create_integration(- config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}- )- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=200)- mock_response.json.return_value = {"number": 123, "state": "closed"}- with patch.object(github, "_installation_authenticated_patch", return_value=mock_response) as mock_patch:- result = github.close_pull_request(repository, 123)- assert result == {"success": True, "number": 123, "state": "closed"}- assert mock_patch.call_args.args[0] == expected_url- assert mock_patch.call_args.kwargs["json_body"] == {"state": "closed"}-- def test_close_pull_request_maps_upstream_error(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=404, text="Not Found")- with patch.object(github, "_installation_authenticated_patch", return_value=mock_response):- result = github.close_pull_request("PostHog/posthog", 123)- assert result == {"success": False, "error": "Failed to close pull request: Not Found", "status_code": 404}-- def test_close_pull_request_from_url_parses_and_closes(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=200)- mock_response.json.return_value = {"number": 42, "state": "closed"}- with patch.object(github, "_installation_authenticated_patch", return_value=mock_response) as mock_patch:- result = github.close_pull_request_from_url("https://github.com/PostHog/posthog/pull/42")- assert result["success"] is True- assert mock_patch.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/pulls/42"-- def test_close_pull_request_from_url_rejects_non_pr_url(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- with patch.object(github, "_installation_authenticated_patch") as mock_patch:- result = github.close_pull_request_from_url("https://github.com/PostHog/posthog/issues/42")- assert result["success"] is False- mock_patch.assert_not_called()-- def test_search_issues_drops_results_from_other_repositories(self):- # Search-syntax operators in the query (e.g. "foo OR bar") can escape the repo:- # qualifier, so results must be filtered by the repository they actually belong to.- integration = self.create_integration(- config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}- )- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=200)- mock_response.json.return_value = {- "items": [- {- "number": 1,- "title": "In repo",- "html_url": "https://github.com/PostHog/posthog/issues/1",- "repository_url": "https://api.github.com/repos/PostHog/posthog",- },- {- "number": 2,- "title": "Other repo",- "html_url": "https://github.com/PostHog/other/issues/2",- "repository_url": "https://api.github.com/repos/PostHog/other",- },- {- "number": 3,- "title": "A pull request",- "html_url": "https://github.com/PostHog/posthog/pull/3",- "repository_url": "https://api.github.com/repos/PostHog/posthog",- "pull_request": {"url": "https://api.github.com/repos/PostHog/posthog/pulls/3"},- },- ]- }- with patch.object(github, "api_request", return_value=mock_response) as mock_request:- results = github.search_issues("posthog", 'crash" repo:microsoft/vscode "')- assert [result["id"] for result in results] == ["1"]- assert results[0]["external_context"] == {"repository": "posthog", "number": 1}- # The user's text is quoted so its qualifiers and operators match literally instead of- # rewriting the query and filling the result page with foreign matches.- sent_query = mock_request.call_args.kwargs["params"]["q"]- assert sent_query == 'repo:PostHog/posthog "crash repo:microsoft/vscode" in:title type:issue'-- def test_comment_on_pull_request_posts_to_issues_endpoint(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=201)- with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:- result = github.comment_on_pull_request("PostHog/posthog", 123, "hello")- assert result == {"success": True}- # PR comments go through the issues endpoint, not /pulls.- assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/123/comments"- assert mock_post.call_args.kwargs["json_body"] == {"body": "hello"}-- def test_comment_on_pull_request_from_url_parses_and_posts(self):- integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})- github = GitHubIntegration(integration)- mock_response = MagicMock(status_code=201)- with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:- result = github.comment_on_pull_request_from_url("https://github.com/PostHog/posthog/pull/42", "note")- assert result["success"] is True- assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/42/comments"-- @parameterized.expand(- [- (- "complete_headers",- {- "X-RateLimit-Resource": "core",- "X-RateLimit-Remaining": "4998",- "X-RateLimit-Limit": "5000",- "X-RateLimit-Reset": "1704117600",- },- "core",- 4998,- 5000,- 1704117600,- ),- ("no_headers", {}, "unknown", None, None, None),- (- "no_resource_header",- {- "X-RateLimit-Remaining": "4997",- "X-RateLimit-Limit": "5000",- "X-RateLimit-Reset": "1704117601",- },- "unknown",- 4997,- 5000,- 1704117601,- ),- ]- )- @patch("posthog.egress.transport.transport.requests.request")- def test_github_api_request_metrics_include_integration_and_rate_limit_headers(- self,- _name: str,- response_headers: dict[str, str],- expected_resource: str,- expected_remaining: int | None,- expected_limit: int | None,- expected_reset: int | None,- mock_get,- ):- # Distinct installation id per case: the gauges are keyed by installation_id on a process-global- # registry that isn't reset between methods, so a shared id would make the no_headers "== None"- # assertion depend on parametrize ordering (another case sets the same (id, "unknown") series).- integration = self.create_integration(- {"installation_id": f"INSTALL-{_name}", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- response = MagicMock()- response.status_code = 200- response.headers = response_headers- mock_get.return_value = response-- labels = {- "installation_id": integration.integration_id,- "method": "GET",- "endpoint": "/repos/{owner}/{repo}",- "status_code": "200",- "source": "integration",- }- previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0-- with patch.object(GitHubIntegration, "access_token_expired", return_value=False):- GitHubIntegration(integration).api_request(- "GET",- "/repos/PostHog/posthog",- endpoint="/repos/{owner}/{repo}",- )-- assert REGISTRY.get_sample_value("github_integration_api_requests_total", labels) == previous_count + 1- assert (- REGISTRY.get_sample_value(- "github_integration_api_rate_limit_remaining",- {"installation_id": integration.integration_id, "resource": expected_resource},- )- == expected_remaining- )- assert (- REGISTRY.get_sample_value(- "github_integration_api_rate_limit_limit",- {"installation_id": integration.integration_id, "resource": expected_resource},- )- == expected_limit- )- assert (- REGISTRY.get_sample_value(- "github_integration_api_rate_limit_reset_timestamp_seconds",- {"installation_id": integration.integration_id, "resource": expected_resource},- )- == expected_reset- )-- @patch("posthog.egress.transport.transport.requests.request")- def test_github_api_request_metrics_include_request_exceptions(self, mock_get):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- mock_get.side_effect = requests.RequestException("network failure")-- labels = {- "installation_id": integration.integration_id,- "method": "GET",- "endpoint": "/repos/{owner}/{repo}",- "status_code": "exception",- "source": "integration",- }- previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0-- with (- patch.object(GitHubIntegration, "access_token_expired", return_value=False),- pytest.raises(GitHubIntegrationError),- ):- GitHubIntegration(integration).api_request(- "GET",- "/repos/PostHog/posthog",- endpoint="/repos/{owner}/{repo}",- )-- # GET retries the network error once; both attempts record an exception sample.- assert REGISTRY.get_sample_value("github_integration_api_requests_total", labels) == previous_count + 2-- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_github_integration_refresh_token(self, mock_client_request):- mock_client_request.side_effect = self.mock_github_client_request(status_code=201)-- with freeze_time("2024-01-01T12:00:00Z"):- integration = GitHubIntegration.integration_from_installation_id(- "INSTALLATION_ID",- self.team.id,- self.user,- )-- assert GitHubIntegration(integration).access_token_expired() is False-- with freeze_time("2024-01-01T14:00:00Z"):- assert GitHubIntegration(integration).access_token_expired() is True-- GitHubIntegration(integration).refresh_access_token()- assert GitHubIntegration(integration).access_token_expired() is False-- assert integration.config == {- "installation_id": "INSTALLATION_ID",- "account": {- "name": "PostHog",- "type": "Organization",- },- "repository_selection": "all",- "refreshed_at": 1704117600,- "expires_in": 3600,- }-- assert integration.sensitive_config == {- "access_token": "ACCESS_TOKEN",- }-- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_github_integration_persists_installation_permissions(self, mock_client_request):- # The warehouse schema picker reads config["permissions"] to mark tables the installation- # can't sync. Dropping this on connect or refresh silently returns the picker to offering- # tables whose every sync 403s.- mock_client_request.side_effect = self.mock_github_client_request(- permissions={"contents": "read", "metadata": "read"}- )- integration = GitHubIntegration.integration_from_installation_id("INSTALLATION_ID", self.team.id, self.user)- assert integration.config["permissions"] == {"contents": "read", "metadata": "read"}-- # A permission update to the App shows up on the next hourly token refresh, including for- # integrations connected before this key was persisted at all.- mock_client_request.side_effect = self.mock_github_client_request(- permissions={"contents": "read", "metadata": "read", "deployments": "read"}- )- GitHubIntegration(integration).refresh_access_token()- assert integration.config["permissions"] == {"contents": "read", "metadata": "read", "deployments": "read"}-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_github_refresh_access_token_handles_errors(self, mock_client_request, mock_reload):- """Test that errors field is set if refresh_access_token fails"""- integration = self.create_integration({"expires_at": 3600}, {"token": "REFRESH"})- mock_client_request.side_effect = self.mock_github_client_request(status_code=400, error_text="error")-- with freeze_time("2024-01-01T12:00:00Z"):- integration.errors = ""- integration.save()-- with pytest.raises(Exception):- GitHubIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert integration.errors == "TOKEN_REFRESH_FAILED"- assert integration.config["refresh_failure_count"] == 1-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_github_refresh_access_token_resets_errors(self, mock_client_request, mock_reload):- """Test that errors field is reset to empty string after successful refresh_access_token"""- mock_client_request.side_effect = self.mock_github_client_request(status_code=201)-- with freeze_time("2024-01-01T12:00:00Z"):- integration = GitHubIntegration.integration_from_installation_id(- "INSTALLATION_ID",- self.team.id,- self.user,- )- integration.errors = "TOKEN_REFRESH_FAILED"- integration.save()-- GitHubIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert integration.errors == ""-- @parameterized.expand(- [- ("uninstalled_404", 404, "Not Found", {}, True),- ("suspended_403", 403, "This installation has been suspended.", {}, True),- ("rate_limited_403", 403, "You have exceeded a secondary rate limit", {"retry-after": "60"}, False),- ("transient_500", 500, "Server Error", {}, False),- ]- )- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_github_refresh_disarms_proactive_refresh_only_for_dead_installation(- self, _name, status_code, text, headers, expected_disarmed, mock_client_request, _mock_reload- ):- response = MagicMock(spec=requests.Response)- response.status_code = status_code- response.text = text- response.headers = headers- response.json.return_value = {}- mock_client_request.return_value = response-- integration = self.create_integration(- config={"installation_id": "INSTALL", "expires_in": 3600, "refreshed_at": int(time.time()) - 3600},- sensitive_config={"access_token": "ACCESS_TOKEN"},- )-- with pytest.raises(GitHubIntegrationError):- GitHubIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- if expected_disarmed:- assert "expires_in" not in integration.config- assert "refreshed_at" not in integration.config- assert GitHubIntegration(integration).access_token_expired() is False- assert integration.config["installation_unavailable_since"]- assert GitHubIntegration(integration).installation_unavailable() is True- else:- assert integration.config["expires_in"] == 3600- assert "refreshed_at" in integration.config- assert "installation_unavailable_since" not in integration.config- assert GitHubIntegration(integration).installation_unavailable() is False-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_github_refresh_success_clears_installation_unavailable_marker(self, mock_client_request, _mock_reload):- mock_client_request.side_effect = self.mock_github_client_request(status_code=201)- integration = self.create_integration(- config={"installation_id": "INSTALL", "installation_unavailable_since": 1700000000},- sensitive_config={"access_token": "STALE_TOKEN"},- )-- GitHubIntegration(integration).refresh_access_token()-- integration.refresh_from_db()- assert "installation_unavailable_since" not in integration.config- assert GitHubIntegration(integration).installation_unavailable() is False- assert integration.sensitive_config["access_token"] == "ACCESS_TOKEN"- assert "expires_in" in integration.config-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_list_repositories_retries_transient_non_json_response(self, _mock_expired, mock_get):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )-- transient = MagicMock()- transient.status_code = 502- transient.json.side_effect = ValueError("not json")-- success = MagicMock()- success.status_code = 200- success.json.return_value = {- "repositories": [- {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},- {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},- ]- }-- mock_get.side_effect = [transient, success]-- repos, has_more = GitHubIntegration(integration).list_repositories()-- assert repos == [- {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},- {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},- ]- assert has_more is False- assert mock_get.call_count == 2-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_list_repositories_raises_after_repeated_transient_non_json(self, _mock_expired, mock_get):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )-- transient_1 = MagicMock()- transient_1.status_code = 502- transient_1.json.side_effect = ValueError("not json")-- transient_2 = MagicMock()- transient_2.status_code = 502- transient_2.json.side_effect = ValueError("not json")-- mock_get.side_effect = [transient_1, transient_2]-- with pytest.raises(GitHubIntegrationError, match="list_repositories non-JSON response"):- GitHubIntegration(integration).list_repositories()-- assert mock_get.call_count == 2-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_list_all_repositories_raises_when_later_page_fails(self, _mock_expired, mock_get):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )-- first_page = MagicMock()- first_page.status_code = 200- first_page.json.return_value = {- "repositories": [{"id": i, "name": f"repo-{i}", "full_name": f"PostHog/repo-{i}"} for i in range(100)]- }-- second_page = MagicMock()- second_page.status_code = 502- second_page.json.return_value = {"message": "bad gateway"}-- # Page-1 succeeds. Page-2 fetch is retried once after transient 502.- mock_get.side_effect = [first_page, second_page, second_page]-- with pytest.raises(GitHubIntegrationError, match="failed to list repositories"):- GitHubIntegration(integration).list_all_repositories()-- assert mock_get.call_count == 3-- @patch("posthog.models.integration.GitHubIntegration.list_repositories")- def test_list_all_repositories_fetches_all_pages(self, mock_list):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )-- first_page = [{"id": i, "name": f"repo-{i}", "full_name": f"PostHog/repo-{i}"} for i in range(100)]- second_page = [{"id": i, "name": f"repo-{i}", "full_name": f"PostHog/repo-{i}"} for i in range(100, 130)]- mock_list.side_effect = [- (first_page, True),- (second_page, False),- ]-- repos = GitHubIntegration(integration).list_all_repositories()-- assert len(repos) == 130- assert repos == first_page + second_page- assert mock_list.call_args_list == [- call(page=1, per_page=100),- call(page=2, per_page=100),- ]-- @patch("posthog.models.integration.GitHubIntegration.list_all_repositories")- def test_list_cached_repositories_uses_cached_data_when_fresh(self, mock_list_all):- cached_repositories = [- {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},- {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},- ]- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- integration.repository_cache = cached_repositories- integration.repository_cache_updated_at = timezone.now()- integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])-- labels = {- "integration_id": str(integration.id),- "cache": "repositories",- "repository": "__all__",- "result": "hit",- }- previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0-- repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=1, offset=1)-- assert repos == [{"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"}]- assert has_more is False- mock_list_all.assert_not_called()- assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1-- @patch("posthog.models.integration.GitHubIntegration.list_all_repositories")- def test_list_cached_repositories_surfaces_optional_fields_when_present(self, mock_list_all):- cached_repositories = [- {- "id": 1,- "name": "posthog",- "full_name": "PostHog/posthog",- "private": True,- "default_branch": "master",- "language": "Python",- "pushed_at": "2026-06-01T00:00:00Z",- "archived": False,- "can_push": True,- },- {"id": 2, "name": "legacy", "full_name": "PostHog/legacy"},- ]- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- integration.repository_cache = cached_repositories- integration.repository_cache_updated_at = timezone.now()- integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])-- repos, _ = GitHubIntegration(integration).list_cached_repositories()-- assert repos[0] == {- "id": 1,- "name": "posthog",- "full_name": "PostHog/posthog",- "private": True,- "default_branch": "master",- "language": "Python",- "pushed_at": "2026-06-01T00:00:00Z",- "archived": False,- "can_push": True,- }- # Repos cached before these fields existed keep their original shape — optional keys are omitted, not nulled.- assert repos[1] == {"id": 2, "name": "legacy", "full_name": "PostHog/legacy"}- mock_list_all.assert_not_called()-- @patch("posthog.models.integration.GitHubIntegration.list_all_repositories")- def test_sync_repository_cache_respects_refresh_cooldown(self, mock_list_all):- cached_repositories = [- {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},- {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},- ]- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- integration.repository_cache = cached_repositories- integration.repository_cache_updated_at = timezone.now()- integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])-- repos = GitHubIntegration(integration).sync_repository_cache(min_refresh_interval_seconds=60)-- assert repos == cached_repositories- mock_list_all.assert_not_called()-- @patch("posthog.models.integration.GitHubIntegration.list_all_repositories")- def test_sync_repository_cache_only_updates_timestamp_when_snapshot_unchanged(self, mock_list_all):- cached_repositories = [- {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},- {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},- ]- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- original_updated_at = timezone.now() - timedelta(minutes=5)- integration.repository_cache = cached_repositories- integration.repository_cache_updated_at = original_updated_at- integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])- mock_list_all.return_value = cached_repositories-- with patch.object(integration, "save", wraps=integration.save) as mock_save:- repos = GitHubIntegration(integration).sync_repository_cache()-- assert repos == cached_repositories- mock_save.assert_called_once_with(update_fields=["repository_cache_updated_at"])- integration.refresh_from_db()- assert integration.repository_cache == cached_repositories- assert integration.repository_cache_updated_at is not None- assert integration.repository_cache_updated_at > original_updated_at-- @patch("posthog.models.integration.GitHubIntegration.list_all_repositories")- def test_list_cached_repositories_populates_cache_on_miss(self, mock_list_all):- fetched_repositories = [- {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},- {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},- ]- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- mock_list_all.return_value = fetched_repositories-- labels = {- "integration_id": str(integration.id),- "cache": "repositories",- "repository": "__all__",- "result": "miss",- }- previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0-- repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=1, offset=0)-- integration.refresh_from_db()- assert repos == [{"id": 1, "name": "posthog", "full_name": "PostHog/posthog"}]- assert has_more is True- assert integration.repository_cache == fetched_repositories- assert integration.repository_cache_updated_at is not None- mock_list_all.assert_called_once_with()- assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1-- @patch("posthog.models.integration.GitHubIntegration.list_all_repositories")- def test_list_cached_repositories_returns_stale_cache_on_refresh_error(self, mock_list_all):- stale_repositories = [- {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},- {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},- ]- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- integration.repository_cache = stale_repositories- integration.repository_cache_updated_at = timezone.now() - timedelta(- seconds=GITHUB_REPOSITORY_CACHE_TTL_SECONDS + 1- )- integration.save(update_fields=["repository_cache", "repository_cache_updated_at"])- mock_list_all.side_effect = Exception("GitHub is slow")-- repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=10, offset=0)-- integration.refresh_from_db()- assert repos == stale_repositories- assert has_more is False- assert integration.repository_cache == stale_repositories- mock_list_all.assert_called_once_with()-- @patch("posthog.models.integration.GitHubIntegration.list_all_repositories")- def test_list_cached_repositories_raises_on_refresh_error_without_cache(self, mock_list_all):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- mock_list_all.side_effect = Exception("GitHub is slow")-- with pytest.raises(Exception, match="GitHub is slow"):- GitHubIntegration(integration).list_cached_repositories(limit=10, offset=0)-- integration.refresh_from_db()- assert integration.repository_cache == []- assert integration.repository_cache_updated_at is None- mock_list_all.assert_called_once_with()-- def test_invalidate_github_repository_caches_for_installation_clears_team_and_personal_rows(self):- from posthog.models.user_integration import UserIntegration-- team_integration = self.create_integration(- {"installation_id": "12345", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- team_integration.integration_id = "12345"- team_integration.repository_cache = [{"id": 1, "name": "a", "full_name": "org/a"}]- team_integration.repository_cache_updated_at = timezone.now()- team_integration.save(update_fields=["integration_id", "repository_cache", "repository_cache_updated_at"])-- user_integration = UserIntegration.objects.create(- user=self.user,- kind=UserIntegration.IntegrationKind.GITHUB,- integration_id="12345",- config={"installation_id": "12345"},- sensitive_config={"access_token": "ACCESS_TOKEN"},- repository_cache=[{"id": 2, "name": "b", "full_name": "org/b"}],- repository_cache_updated_at=timezone.now(),- )-- invalidate_github_repository_caches_for_installation("12345")-- team_integration = Integration.objects.get(pk=team_integration.pk)- user_integration = UserIntegration.objects.get(pk=user_integration.pk)- assert team_integration.repository_cache_updated_at is None- assert user_integration.repository_cache_updated_at is None- assert team_integration.repository_cache == [{"id": 1, "name": "a", "full_name": "org/a"}]-- @patch("posthog.models.integration.GitHubIntegration.list_all_repositories")- def test_list_cached_repositories_pages_with_full_cached_snapshot(self, mock_list_all):- fetched_repositories = [{"id": i, "name": f"repo-{i}", "full_name": f"PostHog/repo-{i}"} for i in range(650)]- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- mock_list_all.return_value = fetched_repositories-- repos, has_more = GitHubIntegration(integration).list_cached_repositories(limit=25, offset=600)-- assert repos == fetched_repositories[600:625]- assert has_more is True- mock_list_all.assert_called_once_with()-- @parameterized.expand(- [- ("blank_search_returns_all", " ", 10, 0, [1, 2, 3, 4], False),- ("no_match_returns_empty", "missing", 10, 0, [], False),- ("casefold_matches_owner_prefix", "POSTHOG", 10, 0, [1, 2, 3, 4], False),- ("pagination_applies_after_filter", "posthog", 1, 1, [2], True),- ]- )- @patch("posthog.models.integration.GitHubIntegration.list_all_repositories")- def test_list_cached_repositories_filters_search_before_pagination(- self,- _name,- search,- limit,- offset,- expected_ids,- expected_has_more,- mock_list_all,- ):- fetched_repositories = [- {"id": 1, "name": "posthog", "full_name": "PostHog/posthog"},- {"id": 2, "name": "posthog-js", "full_name": "PostHog/posthog-js"},- {"id": 3, "name": "code", "full_name": "PostHog/code"},- {"id": 4, "name": "posthog-python", "full_name": "PostHog/posthog-python"},- ]- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- mock_list_all.return_value = fetched_repositories-- repos, has_more = GitHubIntegration(integration).list_cached_repositories(- search=search, limit=limit, offset=offset- )-- assert [repo["id"] for repo in repos] == expected_ids- assert has_more is expected_has_more- mock_list_all.assert_called_once_with()-- @patch("posthog.models.integration.GitHubIntegration.list_branches")- @patch("posthog.models.integration.GitHubIntegration.get_default_branch")- def test_list_cached_branches_uses_cached_data_when_fresh(self, mock_default_branch, mock_list_branches):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- repo = "posthog/posthog"- cache.set(- GitHubIntegration(integration)._get_branch_cache_key(repo),- {- "branches": ["main", "develop", "feature/test"],- "default_branch": "main",- "updated_at": time.time(),- },- )-- labels = {- "integration_id": str(integration.id),- "cache": "branches",- "repository": repo,- "result": "hit",- }- previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0-- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(- repo, limit=2, offset=1- )-- assert branches == ["develop", "feature/test"]- assert default_branch == "main"- assert has_more is False- mock_list_branches.assert_not_called()- mock_default_branch.assert_not_called()- assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1-- @patch("posthog.models.integration.GitHubIntegration.list_branches")- @patch("posthog.models.integration.GitHubIntegration.get_default_branch")- def test_list_cached_branches_filters_search_before_pagination(self, mock_default_branch, mock_list_branches):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- repo = "posthog/posthog"- cache.set(- GitHubIntegration(integration)._get_branch_cache_key(repo),- {- "branches": [- "main",- "feature/agent-cache",- "feature/agent-branch-search",- "fix/refresh-button",- ],- "default_branch": "main",- "updated_at": time.time(),- },- )-- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(- repo, search="feature/agent", limit=1, offset=1- )-- assert branches == ["feature/agent-branch-search"]- assert default_branch == "main"- assert has_more is False- mock_list_branches.assert_not_called()- mock_default_branch.assert_not_called()-- @patch("posthog.models.integration.GitHubIntegration.list_branches")- @patch("posthog.models.integration.GitHubIntegration.get_default_branch")- def test_list_cached_branches_populates_cache_on_miss(self, mock_default_branch, mock_list_branches):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- repo = "posthog/posthog"- mock_list_branches.return_value = (["develop", "feature/test"], False)- mock_default_branch.return_value = "main"-- labels = {- "integration_id": str(integration.id),- "cache": "branches",- "repository": repo,- "result": "miss",- }- previous_count = REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) or 0-- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(- repo, limit=2, offset=0- )-- cached = cache.get(GitHubIntegration(integration)._get_branch_cache_key(repo))- assert branches == ["develop", "feature/test"]- assert default_branch == "main"- assert has_more is False- assert cached["branches"] == ["develop", "feature/test"]- assert cached["default_branch"] == "main"- mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)- mock_default_branch.assert_called_once_with(repo)- assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1-- @patch("posthog.models.integration.GitHubIntegration.list_branches")- @patch("posthog.models.integration.GitHubIntegration.get_default_branch")- def test_list_cached_branches_returns_stale_cache_on_refresh_error(self, mock_default_branch, mock_list_branches):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- repo = "posthog/posthog"- cache.set(- GitHubIntegration(integration)._get_branch_cache_key(repo),- {- "branches": ["main", "develop"],- "default_branch": "main",- "updated_at": time.time() - (GITHUB_BRANCH_CACHE_TTL_SECONDS + 1),- },- )- mock_list_branches.side_effect = Exception("GitHub is slow")-- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(- repo, limit=10, offset=0- )-- assert branches == ["main", "develop"]- assert default_branch == "main"- assert has_more is False- mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)- mock_default_branch.assert_not_called()-- @patch("posthog.models.integration.GitHubIntegration.list_branches")- @patch("posthog.models.integration.GitHubIntegration.get_default_branch")- def test_list_cached_branches_keeps_cached_default_branch_on_refresh_failure(- self, mock_default_branch, mock_list_branches- ):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- repo = "posthog/posthog"- cache.set(- GitHubIntegration(integration)._get_branch_cache_key(repo),- {- "branches": ["main", "develop"],- "default_branch": "main",- "updated_at": time.time() - (GITHUB_BRANCH_CACHE_TTL_SECONDS + 1),- },- )- mock_list_branches.return_value = (["main", "develop", "feature/test"], False)- mock_default_branch.side_effect = Exception("GitHub is slow")-- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(- repo, limit=10, offset=0- )-- cached = cache.get(GitHubIntegration(integration)._get_branch_cache_key(repo))- assert branches == ["main", "develop", "feature/test"]- assert default_branch == "main"- assert has_more is False- assert cached["branches"] == ["main", "develop", "feature/test"]- assert cached["default_branch"] == "main"- mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)- mock_default_branch.assert_called_once_with(repo)-- @patch("posthog.models.integration.GitHubIntegration.list_branches")- def test_list_cached_branches_raises_on_refresh_error_without_cache(self, mock_list_branches):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- repo = "posthog/posthog"- mock_list_branches.side_effect = Exception("GitHub is slow")-- with pytest.raises(Exception, match="GitHub is slow"):- GitHubIntegration(integration).list_cached_branches(repo, limit=10, offset=0)-- mock_list_branches.assert_called_once_with(repo, limit=100, offset=0)-- @patch("posthog.models.integration.GitHubIntegration.list_branches")- def test_list_all_branches_fetches_all_pages(self, mock_list_branches):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- repo = "posthog/posthog"- first_page = [f"branch-{i}" for i in range(100)]- second_page = [f"branch-{i}" for i in range(100, 230)]- mock_list_branches.side_effect = [- (first_page, True),- (second_page, False),- ]-- branches = GitHubIntegration(integration).list_all_branches(repo)-- assert branches == first_page + second_page- assert mock_list_branches.call_args_list == [- call(repo, limit=100, offset=0),- call(repo, limit=100, offset=100),- ]-- @patch("posthog.models.integration.GitHubIntegration.list_branches")- @patch("posthog.models.integration.GitHubIntegration.get_default_branch")- def test_list_cached_branches_pages_with_full_cached_snapshot(self, mock_default_branch, mock_list_branches):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- repo = "posthog/posthog"- first_page = [f"branch-{i}" for i in range(100)]- second_page = [f"branch-{i}" for i in range(100, 200)]- remaining_branches = [f"branch-{i}" for i in range(200, 1500)]- mock_list_branches.side_effect = [- (first_page, True),- (second_page, True),- (remaining_branches, False),- ]- mock_default_branch.return_value = "branch-1200"-- branches, default_branch, has_more = GitHubIntegration(integration).list_cached_branches(- repo, limit=25, offset=1200- )-- expected_branches = ["branch-1199"] + [f"branch-{i}" for i in range(1201, 1225)]- assert branches == expected_branches- assert default_branch == "branch-1200"- assert has_more is True- assert mock_list_branches.call_args_list == [- call(repo, limit=100, offset=0),- call(repo, limit=100, offset=100),- call(repo, limit=100, offset=200),- ]-- # --- raise_if_github_rate_limited ----- @parameterized.expand(- [- ("429_no_body", 429, "", True),- ("403_rate_limit_body", 403, "API rate limit exceeded for installation", True),- ("403_other_body", 403, "Forbidden", False),- ("200_ok", 200, "", False),- ("404_not_found", 404, "", False),- ]- )- def test_raise_if_github_rate_limited_detection(self, _name, status_code, body, should_raise):- response = MagicMock()- response.status_code = status_code- response.text = body- response.headers = {}-- if should_raise:- with pytest.raises(GitHubRateLimitError):- raise_if_github_rate_limited(response)- else:- raise_if_github_rate_limited(response) # must not raise-- @freeze_time("2024-01-01 12:00:00")- def test_raise_if_github_rate_limited_populates_fields(self):- reset_timestamp = int(time.time()) + 60- response = MagicMock()- response.status_code = 429- response.text = ""- response.headers = {- "x-ratelimit-reset": str(reset_timestamp),- "retry-after": "30",- }-- with pytest.raises(GitHubRateLimitError) as exc_info:- raise_if_github_rate_limited(response)-- assert exc_info.value.reset_at == reset_timestamp- assert exc_info.value.retry_after == 30-- @freeze_time("2024-01-01 12:00:00")- def test_raise_if_github_rate_limited_derives_retry_after_from_reset_at(self):- reset_timestamp = int(time.time()) + 45- response = MagicMock()- response.status_code = 429- response.text = ""- response.headers = {"x-ratelimit-reset": str(reset_timestamp)}-- with pytest.raises(GitHubRateLimitError) as exc_info:- raise_if_github_rate_limited(response)-- assert exc_info.value.retry_after == 45-- # --- exception hierarchy ----- def test_github_rate_limit_error_is_egress_error_not_fatal_integration_error(self):- # Deliberately NOT a GitHubIntegrationError: a transient rate limit is retryable, not a fatal- # integration failure, and it lives in the egress layer. Backoff filters key off these fields.- err = GitHubRateLimitError("test", retry_after=45)- assert not isinstance(err, GitHubIntegrationError)- assert err.retry_after == 45-- # --- get_access_token ----- def test_get_access_token_returns_token_when_not_expired(self):- integration = self.create_integration(- config={"expires_in": 3600, "refreshed_at": int(time.time())},- sensitive_config={"access_token": "valid-token"},- )- github = GitHubIntegration(integration)- assert github.get_access_token() == "valid-token"-- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- @patch("posthog.models.integration.reload_integrations_on_workers")- def test_get_access_token_refreshes_when_expired(self, mock_reload, mock_client_request):- integration = self.create_integration(- config={"expires_in": 3600, "refreshed_at": int(time.time()) - 7200}, # expired: refreshed 2h ago- sensitive_config={"access_token": "old-token"},- )- mock_response = MagicMock()- mock_response.status_code = 201- dt = datetime.now(UTC) + timedelta(hours=1)- mock_response.json.return_value = {- "token": "new-token",- "expires_at": dt.replace(tzinfo=None).isoformat(timespec="seconds") + "Z",- }- mock_client_request.return_value = mock_response-- github = GitHubIntegration(integration)- token = github.get_access_token()-- assert token == "new-token"- mock_client_request.assert_called_once()-- def test_get_access_token_raises_when_token_missing_after_refresh(self):- integration = self.create_integration(- config={"expires_in": 3600, "refreshed_at": int(time.time())},- sensitive_config={}, # no access_token key- )- github = GitHubIntegration(integration)-- with pytest.raises(GitHubIntegrationError, match="Access token unavailable"):- github.get_access_token()---def _create_github_integration(team) -> Integration:- # integration_id mirrors production (set from config on install) — the egress gate and- # tier store key on it; without it every call is identity-blind and skips both.- return Integration.objects.create(- team=team,- kind="github",- integration_id="INSTALL",- config={"installation_id": "INSTALL", "account": {"name": "PostHog"}},- sensitive_config={"access_token": "ACCESS_TOKEN"},- )---class TestGitHubIntegrationGhApiGet(BaseTest):- def _create_integration(self) -> Integration:- return _create_github_integration(self.team)-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_returns_parsed_json_body(self, _mock_expired, mock_get):- ok = MagicMock()- ok.status_code = 200- ok.json.return_value = {"default_branch": "main"}- mock_get.return_value = ok-- integration = self._create_integration()- body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")- assert body == {"default_branch": "main"}-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.egress.github.transport.consume_github_installation_sync", return_value=False)- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_batch_instance_is_shed_when_budget_denied(self, _mock_expired, _mock_consume, mock_request):- # Guards the lane plumbing: if the instance priority stops reaching the transport, BATCH- # callers silently ride the never-shed CRITICAL lane again and denials stop deferring work.- integration = self._create_integration()- github = GitHubIntegration(integration, priority=Priority.BATCH)- with pytest.raises(GitHubEgressBudgetExhausted):- github.api_request("GET", "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")- mock_request.assert_not_called()-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.egress.github.transport.consume_github_installation_sync", return_value=False)- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_critical_default_proceeds_when_budget_denied(self, _mock_expired, _mock_consume, mock_request):- ok = MagicMock()- ok.status_code = 200- mock_request.return_value = ok-- integration = self._create_integration()- response = GitHubIntegration(integration).api_request(- "GET", "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"- )- assert response.status_code == 200- mock_request.assert_called_once()-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_retries_once_on_transient_5xx(self, _mock_expired, mock_get):- transient = MagicMock()- transient.status_code = 503- transient.json.return_value = {}- ok = MagicMock()- ok.status_code = 200- ok.json.return_value = {"ok": True}- mock_get.side_effect = [transient, ok]-- integration = self._create_integration()- body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")- assert body == {"ok": True}- assert mock_get.call_count == 2-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_raises_rate_limit_error_on_secondary_limit(self, _mock_expired, mock_get):- resp = MagicMock()- resp.status_code = 403- resp.headers = {"retry-after": "5"}- resp.json.return_value = {"message": "secondary rate limit"}- mock_get.return_value = resp-- integration = self._create_integration()- with pytest.raises(GitHubRateLimitError) as excinfo:- GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")- assert excinfo.value.retry_after == 5-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_detects_secondary_limit_from_body_when_headers_missing(self, _mock_expired, mock_get):- resp = MagicMock()- resp.status_code = 403- resp.headers = {}- resp.text = '{"message": "You have exceeded a secondary rate limit."}'- resp.json.return_value = {"message": "You have exceeded a secondary rate limit."}- mock_get.return_value = resp-- integration = self._create_integration()- with pytest.raises(GitHubRateLimitError) as excinfo:- GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")- assert excinfo.value.retry_after == 60-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.refresh_access_token")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_refreshes_token_on_401(self, _mock_expired, mock_refresh, mock_get):- unauth = MagicMock()- unauth.status_code = 401- unauth.json.return_value = {}- ok = MagicMock()- ok.status_code = 200- ok.json.return_value = {"after_refresh": True}- mock_get.side_effect = [unauth, ok]-- integration = self._create_integration()- body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")- assert body == {"after_refresh": True}- assert mock_refresh.called-- def test_rejects_path_without_leading_slash(self):- integration = self._create_integration()- with pytest.raises(ValueError, match="must start with"):- GitHubIntegration(integration)._gh_api_get("repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")---class TestGitHubIntegrationGraphQL(BaseTest):- def _create_integration(self) -> Integration:- return _create_github_integration(self.team)-- @staticmethod- def _graphql_response(body: dict) -> MagicMock:- # GitHub returns transient GraphQL server errors as an HTTP 200 with an ``errors`` body,- # so the retry decision hinges on the body, not the status code.- resp = MagicMock()- resp.status_code = 200- resp.json.return_value = body- return resp-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_retries_transient_server_error_and_returns_data(self, _mock_expired, mock_request):- # A 200-with-`errors` "Something went wrong" server error must be retried, not raised —- # otherwise a transient GitHub blip permanently kills the in-flight follow-up run.- transient = self._graphql_response(- {"data": None, "errors": [{"message": "Something went wrong while executing your query. (abc123)"}]}- )- ok = self._graphql_response({"data": {"repository": {"name": "posthog"}}})- mock_request.side_effect = [transient, ok]-- github = GitHubIntegration(self._create_integration())- data = github._gh_graphql("query {}", {}, endpoint="/graphql:test")- assert data == {"repository": {"name": "posthog"}}- assert mock_request.call_count == 2-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_gives_up_after_exhausting_transient_retries(self, _mock_expired, mock_request):- # Guards against both a run-killing single attempt and an unbounded retry loop.- transient = self._graphql_response(- {"data": None, "errors": [{"type": "SERVICE_UNAVAILABLE", "message": "unavailable"}]}- )- mock_request.return_value = transient-- github = GitHubIntegration(self._create_integration())- with pytest.raises(GitHubIntegrationError):- github._gh_graphql("query {}", {}, endpoint="/graphql:test")- assert mock_request.call_count == GitHubIntegration._GRAPHQL_TRANSIENT_ATTEMPTS-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_does_not_retry_deterministic_error(self, _mock_expired, mock_request):- # A deterministic error (bad query, missing field, permission) will never succeed on- # retry, so it must raise on the first attempt rather than burn the retry budget.- mock_request.return_value = self._graphql_response(- {"data": None, "errors": [{"type": "FORBIDDEN", "message": "Resource not accessible by integration"}]}- )-- github = GitHubIntegration(self._create_integration())- with pytest.raises(GitHubIntegrationError):- github._gh_graphql("query {}", {}, endpoint="/graphql:test")- assert mock_request.call_count == 1-- @patch("posthog.egress.transport.transport.requests.request")- @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)- def test_returns_partial_data_with_field_errors(self, _mock_expired, mock_request):- # When GitHub returns usable data alongside field-level errors, keep the data rather- # than treating the response as a failure.- mock_request.return_value = self._graphql_response(- {"data": {"repository": {"name": "posthog"}}, "errors": [{"message": "field-level error"}]}- )-- github = GitHubIntegration(self._create_integration())- data = github._gh_graphql("query {}", {}, endpoint="/graphql:test")- assert data == {"repository": {"name": "posthog"}}- assert mock_request.call_count == 1---BABYSIT_PR_URL = "https://github.com/acme/widgets/pull/7"---def _babysit_thread(thread_id: str, *, is_resolved: bool = False, author: str = "reviewer", body: str = "fix this"):- return {- "id": thread_id,- "isResolved": is_resolved,- "path": "posthog/api.py",- "comments": {- "nodes": [- {- "id": f"{thread_id}-C1",- "url": f"{BABYSIT_PR_URL}#discussion_{thread_id}",- "body": body,- "author": {"login": author},- "authorAssociation": "MEMBER",- }- ]- },- }---def _babysit_feedback(node_id: str, *, author: str = "reviewer", body: str = "please rename"):- return {- "id": node_id,- "url": f"{BABYSIT_PR_URL}#issuecomment-{node_id}",- "body": body,- "author": {"login": author},- "authorAssociation": "MEMBER",- }---class TestGitHubIntegrationPullRequestBabysitSnapshot(BaseTest):- def _github(self) -> GitHubIntegration:- return GitHubIntegration(_create_github_integration(self.team))-- @staticmethod- def _payload(**overrides) -> dict:- pull_request: dict = {- "url": BABYSIT_PR_URL,- "state": "OPEN",- "isDraft": False,- "mergeable": "MERGEABLE",- "headRefOid": "head1",- "author": {"login": "posthog-bot"},- "reviewThreads": {"nodes": []},- "comments": {"nodes": []},- "reviews": {"nodes": []},- "commits": {"nodes": [{"commit": {"statusCheckRollup": None}}]},- }- pull_request.update(overrides)- return {"repository": {"pullRequest": pull_request}}-- _FAILING_CONTEXT = {- "__typename": "CheckRun",- "name": "backend",- "conclusion": "FAILURE",- "detailsUrl": "https://ci.example.com/1",- "checkSuite": None,- }-- def test_resolved_threads_and_self_or_empty_feedback_are_dropped(self):- payload = self._payload(- reviewThreads={"nodes": [_babysit_thread("T1", is_resolved=True), _babysit_thread("T2")]},- comments={- "nodes": [- _babysit_feedback("M1", author="posthog-bot"),- _babysit_feedback("M2", body=" "),- _babysit_feedback("M3"),- ]- },- reviews={"nodes": [_babysit_feedback("R1", author="posthog-bot"), _babysit_feedback("R2")]},- )-- with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):- result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)-- assert [thread["id"] for thread in result["unresolved_threads"]] == ["T2"]- assert [comment["id"] for comment in result["comments"]] == ["M3", "R2"]-- @parameterized.expand(- [- ("MERGED", False, "merged"),- ("CLOSED", False, "closed"),- ("OPEN", True, "draft"),- ("OPEN", False, "open"),- ]- )- def test_pr_state_mapping(self, gql_state, is_draft, expected):- payload = self._payload(state=gql_state, isDraft=is_draft)-- with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):- result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)-- assert result["state"] == expected-- @parameterized.expand(- [- ("CONFLICTING", True),- ("MERGEABLE", False),- ("UNKNOWN", False),- ]- )- def test_only_a_conflicting_merge_state_flags_a_conflict(self, gql_mergeable, expected):- payload = self._payload(mergeable=gql_mergeable)-- with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):- result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)-- assert result["has_conflict"] is expected-- def test_extracts_only_failing_checks_with_workflow_scoped_keys(self):- rollup = {- "contexts": {- "nodes": [- {- "__typename": "CheckRun",- "name": "backend",- "conclusion": "FAILURE",- "detailsUrl": "https://ci.example.com/1",- "checkSuite": {"workflowRun": {"workflow": {"name": "CI"}}},- },- {"__typename": "CheckRun", "name": "frontend", "conclusion": "SUCCESS", "checkSuite": None},- {"__typename": "CheckRun", "name": "flaky", "conclusion": "TIMED_OUT", "checkSuite": None},- {- "__typename": "StatusContext",- "context": "vercel",- "state": "ERROR",- "targetUrl": "https://vercel.example.com/1",- },- {"__typename": "StatusContext", "context": "netlify", "state": "SUCCESS"},- ]- },- }- payload = self._payload(commits={"nodes": [{"commit": {"statusCheckRollup": rollup}}]})-- with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):- result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)-- assert [check["key"] for check in result["failing_checks"]] == ["CI/backend", "flaky", "vercel"]- assert result["failing_checks"][0]["details_url"] == "https://ci.example.com/1"-- @parameterized.expand(- [- ("FAILURE", [], [("ci-rollup-failing", f"{BABYSIT_PR_URL}/checks")]),- ("ERROR", [], [("ci-rollup-failing", f"{BABYSIT_PR_URL}/checks")]),- ("FAILURE", [_FAILING_CONTEXT], [("backend", "https://ci.example.com/1")]),- ("SUCCESS", [], []),- ("PENDING", [], []),- ]- )- def test_rollup_state_backstops_checks_missing_from_the_context_page(self, rollup_state, context_nodes, expected):- rollup = {"state": rollup_state, "contexts": {"nodes": context_nodes}}- payload = self._payload(commits={"nodes": [{"commit": {"statusCheckRollup": rollup}}]})-- with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload):- result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)-- assert [(check["key"], check["details_url"]) for check in result["failing_checks"]] == expected-- def test_invalid_pull_request_url_is_reported_as_failure_without_calling_github(self):- with patch.object(GitHubIntegration, "_gh_graphql") as mock_graphql:- result = self._github().get_pull_request_babysit_snapshot("https://example.com/not/a/pull-request")-- assert result["success"] is False- mock_graphql.assert_not_called()-- def test_missing_pull_request_is_reported_as_failure(self):- with patch.object(GitHubIntegration, "_gh_graphql", return_value={"repository": {"pullRequest": None}}):- result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)-- assert result["success"] is False---class TestDatabricksIntegrationModel(BaseTest):- @patch("posthog.models.integration.is_url_allowed", return_value=(True, None))- def test_integration_from_config_with_valid_config(self, mock_is_url_allowed):- integration = DatabricksIntegration.integration_from_config(- team_id=self.team.pk,- server_hostname="databricks.com",- client_id="client_id",- client_secret="client_secret",- created_by=self.user,- )- assert integration.team == self.team- assert integration.created_by == self.user- assert integration.config == {"server_hostname": "databricks.com"}- assert integration.sensitive_config == {"client_id": "client_id", "client_secret": "client_secret"}-- @patch("posthog.models.integration.is_url_allowed", return_value=(False, "Could not resolve host"))- def test_integration_from_config_with_invalid_server_hostname(self, mock_is_url_allowed):- with pytest.raises(- DatabricksIntegrationError, match="Databricks integration error: could not validate hostname 'invalid'"- ):- DatabricksIntegration.integration_from_config(- team_id=self.team.pk,- server_hostname="invalid",- client_id="client_id",- client_secret="client_secret",- created_by=self.user,- )---class TestAWSS3IntegrationModel(BaseTest):- @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")- def test_integration_from_config_with_valid_config(self, mock_validate):- integration = AWSS3Integration.integration_from_config(- team_id=self.team.pk,- name="prod-aws",- aws_access_key_id="AKIAEXAMPLE",- aws_secret_access_key="secret",- created_by=self.user,- )- assert integration.team == self.team- assert integration.created_by == self.user- assert integration.kind == Integration.IntegrationKind.AWS_S3- # The identifier is the user-supplied name, never a credential.- assert integration.integration_id == "prod-aws"- # The account id resolved from STS is stored in non-sensitive config.- assert integration.config == {"name": "prod-aws", "aws_account_id": "123456789012"}- assert integration.sensitive_config == {- "aws_access_key_id": "AKIAEXAMPLE",- "aws_secret_access_key": "secret",- }- # display_name surfaces AWS account so users can tell integrations apart.- assert integration.display_name == "prod-aws (AWS account 123456789012)"- assert AWSS3Integration(integration).aws_account_id == "123456789012"-- def test_integration_from_config_requires_name(self):- with pytest.raises(IntegrationError, match="A name is required"):- AWSS3Integration.integration_from_config(- team_id=self.team.pk,- name="",- aws_access_key_id="AKIAEXAMPLE",- aws_secret_access_key="secret",- )-- @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")- def test_integration_from_config_rejects_duplicate_name(self, mock_validate):- AWSS3Integration.integration_from_config(- team_id=self.team.pk,- name="prod-aws",- aws_access_key_id="AKIAEXAMPLE",- aws_secret_access_key="secret",- )- with pytest.raises(DuplicateNameError, match="An integration named 'prod-aws' already exists"):- AWSS3Integration.integration_from_config(- team_id=self.team.pk,- name="prod-aws",- aws_access_key_id="AKIAOTHER",- aws_secret_access_key="other-secret",- )- assert Integration.objects.filter(team=self.team, integration_id="prod-aws").count() == 1-- @patch("boto3.client")- def test_validate_aws_credentials_returns_account_id(self, mock_boto_client):- mock_boto_client.return_value.get_caller_identity.return_value = {"Account": "123456789012"}- assert validate_aws_credentials("key", "secret") == "123456789012"-- @patch("boto3.client")- def test_validate_aws_credentials_raises_on_invalid_credentials(self, mock_boto_client):- from botocore.exceptions import ClientError-- mock_boto_client.return_value.get_caller_identity.side_effect = ClientError(- {"Error": {"Code": "InvalidClientTokenId", "Message": "The security token is invalid."}},- "GetCallerIdentity",- )- with pytest.raises(IntegrationError, match="AWS credentials are not valid: The security token is invalid."):- validate_aws_credentials("key", "secret")-- def test_wrapping_wrong_kind_raises(self):- integration = Integration.objects.create(- team=self.team, kind=Integration.IntegrationKind.S3_COMPATIBLE, integration_id="x"- )- with pytest.raises(IntegrationError, match="is not the expected AWS integration"):- AWSS3Integration(integration)-- def test_wrapping_missing_credentials_raises(self):- integration = Integration.objects.create(- team=self.team, kind=Integration.IntegrationKind.AWS_S3, integration_id="x", sensitive_config={}- )- with pytest.raises(IntegrationError, match="missing"):- AWSS3Integration(integration)---class TestS3CompatibleIntegrationModel(BaseTest):- def test_integration_from_config_with_valid_config(self):- integration = S3CompatibleIntegration.integration_from_config(- team_id=self.team.pk,- name="my-r2",- endpoint_url="https://account.r2.cloudflarestorage.com",- aws_access_key_id="key",- aws_secret_access_key="secret",- created_by=self.user,- )- assert integration.kind == Integration.IntegrationKind.S3_COMPATIBLE- assert integration.integration_id == "my-r2"- # endpoint_url is non-sensitive and lives in config.- assert integration.config == {"name": "my-r2", "endpoint_url": "https://account.r2.cloudflarestorage.com"}- assert integration.sensitive_config == {"aws_access_key_id": "key", "aws_secret_access_key": "secret"}- wrapped = S3CompatibleIntegration(integration)- assert wrapped.endpoint_url == "https://account.r2.cloudflarestorage.com"- # display_name surfaces auth type and endpoint so users can tell integrations apart.- assert integration.display_name == "my-r2 (access key, https://account.r2.cloudflarestorage.com)"-- def test_integration_from_config_requires_endpoint_url(self):- with pytest.raises(IntegrationError, match="Endpoint URL is required"):- S3CompatibleIntegration.integration_from_config(- team_id=self.team.pk,- name="my-r2",- endpoint_url="",- aws_access_key_id="key",- aws_secret_access_key="secret",- )-- def test_integration_from_config_rejects_duplicate_name(self):- S3CompatibleIntegration.integration_from_config(- team_id=self.team.pk,- name="my-r2",- endpoint_url="https://account.r2.cloudflarestorage.com",- aws_access_key_id="key",- aws_secret_access_key="secret",- )- with pytest.raises(DuplicateNameError, match="An integration named 'my-r2' already exists"):- S3CompatibleIntegration.integration_from_config(- team_id=self.team.pk,- name="my-r2",- endpoint_url="https://other.r2.cloudflarestorage.com",- aws_access_key_id="key2",- aws_secret_access_key="secret2",- )- assert Integration.objects.filter(team=self.team, integration_id="my-r2").count() == 1-- # is_url_allowed bypasses validation in DEBUG/test mode, so force the production path to exercise rejection.- @override_settings(FORCE_URL_VALIDATION=True)- def test_integration_from_config_rejects_internal_endpoint(self):- with pytest.raises(IntegrationError, match="Invalid endpoint URL"):- S3CompatibleIntegration.integration_from_config(- team_id=self.team.pk,- name="my-r2",- endpoint_url="https://169.254.169.254",- aws_access_key_id="key",- aws_secret_access_key="secret",- )-- def test_wrapping_missing_endpoint_url_raises(self):- integration = Integration.objects.create(- team=self.team,- kind=Integration.IntegrationKind.S3_COMPATIBLE,- integration_id="x",- config={"name": "x"},- sensitive_config={"aws_access_key_id": "key", "aws_secret_access_key": "secret"},- )- with pytest.raises(IntegrationError, match="missing required field: 'endpoint_url'"):- S3CompatibleIntegration(integration)---class TestGoogleAdsIntegrationModel(BaseTest):- def _integration(self) -> Integration:- return Integration.objects.create(- team=self.team,- kind="google-ads",- config={},- sensitive_config={"access_token": "token"},- integration_id="google_ads_test",- )-- @staticmethod- def _customer_client(- customer_id: str, name: str, level: Optional[str] = None, manager: bool = False, status: str = "ENABLED"- ) -> dict:- client: dict = {"clientCustomer": f"customers/{customer_id}", "descriptiveName": name, "status": status}- # Google's REST responses omit proto3 defaults, so level 0 and manager=false are absent.- if level is not None:- client["level"] = level- if manager:- client["manager"] = True- return {"customerClient": client}-- @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")- @patch("posthog.models.integration.requests.request")- def test_accessible_accounts_reads_every_search_stream_chunk(self, mock_request):- accessible = MagicMock(status_code=200)- accessible.json.return_value = {"resourceNames": ["customers/6501924158"]}- # searchStream's REST body is an array of batches; a large hierarchy spans several.- stream = MagicMock(status_code=200)- stream.json.return_value = [- {"results": [self._customer_client("6501924158", "Acme Corp", manager=True)]},- {"results": [self._customer_client("1234567890", "Client One", level="1")]},- ]- mock_request.side_effect = [accessible, stream]-- accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()-- assert [account["id"] for account in accounts] == ["6501924158", "1234567890"]- assert accounts[0]["manager"] is True- assert accounts[1]["parent_id"] == "6501924158"-- @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")- @patch("posthog.models.integration.requests.request")- def test_accessible_accounts_dedupes_an_account_reachable_from_two_roots(self, mock_request):- # A user with direct access to both a manager and one of its clients gets both in- # `resourceNames`, so the client is walked twice: once as a root (level absent, i.e. 0) and once- # under the manager (level "1"). Those two levels must be compared as numbers — comparing the raw- # values raises TypeError (None vs "1") and 500s the picker.- accessible = MagicMock(status_code=200)- accessible.json.return_value = {"resourceNames": ["customers/1234567890", "customers/6501924158"]}- client_walk = MagicMock(status_code=200)- client_walk.json.return_value = [{"results": [self._customer_client("1234567890", "Client One")]}]- manager_walk = MagicMock(status_code=200)- manager_walk.json.return_value = [- {- "results": [- self._customer_client("6501924158", "Acme Corp", manager=True),- self._customer_client("1234567890", "Client One", level="1"),- ]- }- ]- mock_request.side_effect = [accessible, client_walk, manager_walk]-- accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()-- # The client is kept once, at its shallowest sighting: reachable directly, so it needs no manager- # to log in as.- assert [account["id"] for account in accounts] == ["1234567890", "6501924158"]- assert accounts[0]["level"] is None- assert accounts[0]["parent_id"] == "1234567890"-- @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")- @patch("posthog.models.integration.requests.request")- def test_accessible_accounts_keeps_enabled_sighting_when_shallower_root_is_disabled(self, mock_request):- # The same client is reachable enabled under a manager (level "1") and directly as a disabled root- # (level 0). The enabled path is walked first and kept; the disabled shallower root must not evict- # it — otherwise the account vanishes from the picker even though Google returned an enabled path.- accessible = MagicMock(status_code=200)- accessible.json.return_value = {"resourceNames": ["customers/6501924158", "customers/1234567890"]}- manager_walk = MagicMock(status_code=200)- manager_walk.json.return_value = [- {- "results": [- self._customer_client("6501924158", "Acme Corp", manager=True),- self._customer_client("1234567890", "Client One", level="1"),- ]- }- ]- disabled_root_walk = MagicMock(status_code=200)- disabled_root_walk.json.return_value = [- {"results": [self._customer_client("1234567890", "Client One", status="DISABLED")]}- ]- mock_request.side_effect = [accessible, manager_walk, disabled_root_walk]-- accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()-- client = next(account for account in accounts if account["id"] == "1234567890")- assert client["level"] == "1"- assert client["parent_id"] == "6501924158"-- @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")- @patch("posthog.models.integration.requests.request")- def test_accessible_accounts_empty_when_login_has_no_accessible_customers(self, mock_request):- # A Google login with no accessible Ads accounts gets a 200 with an empty body, so `resourceNames`- # is absent rather than an empty list — this must yield no accounts, not raise KeyError.- accessible = MagicMock(status_code=200)- accessible.json.return_value = {}- mock_request.return_value = accessible-- accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()-- assert accounts == []-- @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")- @patch("tenacity.nap.time.sleep")- @patch("posthog.models.integration.requests.request")- def test_accessible_accounts_rides_out_one_transient_read_timeout(self, mock_request, mock_sleep):- # The walk is a chain of sequential requests; a single timed-out request used to fail the whole- # walk. It must instead be retried once and succeed.- accessible = MagicMock(status_code=200)- accessible.json.return_value = {"resourceNames": ["customers/6501924158"]}- stream = MagicMock(status_code=200)- stream.json.return_value = [{"results": [self._customer_client("1234567890", "Client One", level="1")]}]- mock_request.side_effect = [accessible, requests.exceptions.ReadTimeout("read timed out"), stream]-- accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()-- assert [account["id"] for account in accounts] == ["1234567890"]-- @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")- @patch("tenacity.nap.time.sleep")- @patch("posthog.models.integration.requests.request")- def test_accessible_accounts_raises_after_repeated_read_timeouts(self, mock_request, mock_sleep):- # Retries must be bounded: a persistently unreachable endpoint should still fail rather than- # retry forever or get silently swallowed.- mock_request.side_effect = requests.exceptions.ReadTimeout("read timed out")-- with pytest.raises(requests.exceptions.ReadTimeout):- GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()-- assert mock_request.call_count == 3---class TestPinterestAdsIntegrationDisplayName(BaseTest):- @parameterized.expand(- [- (- "business",- {"id": "1", "username": "13x6ppss87fecv1q790xh1orhyp9th", "business_name": "Posthog Inc"},- "Posthog Inc",- ),- ("personal", {"id": "1", "username": "javierposthog", "business_name": ""}, "javierposthog"),- # Older connections predate business_name being stored.- ("legacy", {"id": "1", "username": "javierposthog"}, "javierposthog"),- ]- )- def test_display_name_prefers_business_name(self, _name: str, config: dict, expected: str) -> None:- integration = Integration.objects.create(- team=self.team,- kind="pinterest-ads",- config=config,- integration_id=config["id"],- )- assert integration.display_name == expected---class TestTikTokAdsIntegrationDisplayName(BaseTest):- @parameterized.expand(- [- (- "email_wins_over_display_name",- {- "advertiser_ids": ["7554133187111469074"],- "user_email": "e***[email protected]",- "user_display_name": "user1140434302514",- },- "e***[email protected]",- ),- ("neither_fetched_falls_back_to_id", {"advertiser_ids": ["7554133187111469074"]}, "7554133187111469074"),- ]- )- def test_display_name_prefers_user_email(self, _name: str, config: dict, expected: str) -> None:- integration = Integration.objects.create(- team=self.team,- kind="tiktok-ads",- config=config,- integration_id=",".join(config["advertiser_ids"]),- )- assert integration.display_name == expected---@override_settings(REDDIT_ADS_CLIENT_ID="reddit-client-id", REDDIT_ADS_CLIENT_SECRET="reddit-client-secret")-class TestRedditAdsIntegrationDisplayName(BaseTest):- @parameterized.expand(- [- (- "username",- {"reddit_user_id": "t2_1tqubocxl4", "data.reddit_username": "javierposthog"},- "javierposthog",- ),- ("legacy", {"reddit_user_id": "t2_1tqubocxl4"}, "t2_1tqubocxl4"),- ]- )- def test_display_name_prefers_username(self, _name: str, config: dict, expected: str) -> None:- integration = Integration.objects.create(- team=self.team,- kind="reddit-ads",- config=config,- integration_id=config["reddit_user_id"],- )- assert integration.display_name == expected---class TestSnowflakeIntegrationModel(BaseTest):- def test_integration_from_config_with_password_auth(self):- integration = SnowflakeIntegration.integration_from_config(- team_id=self.team.pk,- name="prod-snowflake",- account="myorg-myaccount",- user="posthog_svc",- authentication_type="password",- password="secret",- created_by=self.user,- )- assert integration.kind == Integration.IntegrationKind.SNOWFLAKE- # The identifier is the user-supplied name, never a credential.- assert integration.integration_id == "prod-snowflake"- # account, user and authentication_type are non-sensitive and live in config.- assert integration.config == {- "name": "prod-snowflake",- "account": "myorg-myaccount",- "user": "posthog_svc",- "authentication_type": "password",- }- assert integration.sensitive_config == {"password": "secret"}- wrapped = SnowflakeIntegration(integration)- assert wrapped.password == "secret"- assert wrapped.private_key is None- # display_name surfaces auth type and account so users can tell integrations apart.- assert integration.display_name == "prod-snowflake (account: myorg-myaccount, password auth)"-- def test_integration_from_config_with_keypair_auth(self):- integration = SnowflakeIntegration.integration_from_config(- team_id=self.team.pk,- name="prod-snowflake",- account="myorg-myaccount",- user="posthog_svc",- authentication_type="keypair",- private_key="-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----",- private_key_passphrase="phrase",- created_by=self.user,- )- assert integration.config["authentication_type"] == "keypair"- assert integration.sensitive_config == {- "private_key": "-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----",- "private_key_passphrase": "phrase",- }- # A password from a switched auth mode must never linger alongside the key-pair material.- assert "password" not in integration.sensitive_config- wrapped = SnowflakeIntegration(integration)- assert wrapped.private_key == "-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----"- assert wrapped.private_key_passphrase == "phrase"-- def test_integration_from_config_keypair_without_passphrase(self):- integration = SnowflakeIntegration.integration_from_config(- team_id=self.team.pk,- name="prod-snowflake",- account="myorg-myaccount",- user="posthog_svc",- authentication_type="keypair",- private_key="-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----",- )- assert integration.sensitive_config == {- "private_key": "-----BEGIN PRIVATE KEY-----\nxxx\n-----END PRIVATE KEY-----"- }-- @parameterized.expand(- [- ("missing_name", "", "myorg-myaccount", "posthog_svc"),- ("missing_account", "prod-snowflake", "", "posthog_svc"),- ("missing_user", "prod-snowflake", "myorg-myaccount", ""),- ]- )- def test_integration_from_config_requires_name_account_user(self, _name, name, account, user):- with pytest.raises(SnowflakeIntegrationError, match="Name, account, and user must be provided"):- SnowflakeIntegration.integration_from_config(- team_id=self.team.pk,- name=name,- account=account,- user=user,- authentication_type="password",- password="secret",- )-- @parameterized.expand(- [- ("password_missing_password", "password", {}, "Password is required"),- ("keypair_missing_private_key", "keypair", {}, "Private key is required"),- ("invalid_auth_type", "oauth", {"password": "secret"}, "Invalid authentication type: oauth"),- ]- )- def test_integration_from_config_rejects_invalid_auth(self, _name, authentication_type, credentials, expected):- with pytest.raises(SnowflakeIntegrationError, match=expected):- SnowflakeIntegration.integration_from_config(- team_id=self.team.pk,- name="prod-snowflake",- account="myorg-myaccount",- user="posthog_svc",- authentication_type=authentication_type,- **credentials,- )-- def test_integration_from_config_rejects_duplicate_name(self):- SnowflakeIntegration.integration_from_config(- team_id=self.team.pk,- name="prod-snowflake",- account="myorg-myaccount",- user="posthog_svc",- authentication_type="password",- password="secret",- )- with pytest.raises(SnowflakeIntegrationError, match="An integration named 'prod-snowflake' already exists"):- SnowflakeIntegration.integration_from_config(- team_id=self.team.pk,- name="prod-snowflake",- account="other-account",- user="other_user",- authentication_type="password",- password="other-secret",- )- assert Integration.objects.filter(team=self.team, integration_id="prod-snowflake").count() == 1-- @parameterized.expand(- [- ("simple", "myaccount"),- ("org_account", "myorg-myaccount"),- ("legacy_locator", "xy12345.us-east-1.aws"),- ]- )- def test_validate_account_accepts_valid_identifiers(self, _name, account):- SnowflakeIntegration.validate_account(account) # must not raise-- @parameterized.expand(- [- ("full_url", "https://myaccount.snowflakecomputing.com"),- ("with_path", "myaccount/foo"),- ("with_at", "user@myaccount"),- ("with_colon", "myaccount:443"),- ("with_fragment", "myaccount#"),- ("with_whitespace", "my account"),- ("empty", ""),- ]- )- def test_validate_account_rejects_malformed_identifiers(self, _name, account):- with pytest.raises(SnowflakeIntegrationError, match="invalid account identifier"):- SnowflakeIntegration.validate_account(account)-- def test_wrapping_wrong_kind_raises(self):- integration = Integration.objects.create(- team=self.team, kind=Integration.IntegrationKind.AWS_S3, integration_id="x"- )- with pytest.raises(SnowflakeIntegrationError, match="is not a Snowflake integration"):- SnowflakeIntegration(integration)-- def test_wrapping_missing_config_raises(self):- integration = Integration.objects.create(- team=self.team, kind=Integration.IntegrationKind.SNOWFLAKE, integration_id="x", config={}- )- with pytest.raises(SnowflakeIntegrationError, match="missing"):- SnowflakeIntegration(integration)---class TestGoogleCloudServiceAccountIntegration(BaseTest):- def test_raises_on_duplicate_service_account_email(self):- _ = GoogleCloudServiceAccountIntegration.integration_from_service_account(- team_id=self.team.pk,- organization_id=str(self.team.organization.id),- service_account_email="[email protected]",- project_id="test",- )- with pytest.raises(ValidationError):- _ = GoogleCloudServiceAccountIntegration.integration_from_service_account(- team_id=self.team.pk + 1,- organization_id="a-different-org",- service_account_email="[email protected]",- project_id="test",- )-- def test_allows_duplicate_service_account_email_when_using_key(self):- key_file_integration = GoogleCloudServiceAccountIntegration.integration_from_service_account(- team_id=self.team.pk,- organization_id=str(self.team.organization.id),- service_account_email="[email protected]",- project_id="test",- private_key="something",- private_key_id="something",- token_uri="something",- )-- other_org = Organization.objects.create(name="other org")- other_team = Team.objects.create(organization=other_org, name="other team")- new_impersonated_integration = GoogleCloudServiceAccountIntegration.integration_from_service_account(- team_id=other_team.id,- organization_id=other_org.id,- service_account_email="[email protected]",- project_id="test",- )-- new_key_file_integration = GoogleCloudServiceAccountIntegration.integration_from_service_account(- team_id=other_team.pk,- organization_id=other_org.id,- service_account_email="[email protected]",- project_id="test",- private_key="something",- private_key_id="something",- token_uri="something",- )-- assert (- GoogleCloudServiceAccountIntegration(key_file_integration).service_account_email- == GoogleCloudServiceAccountIntegration(new_impersonated_integration).service_account_email- == GoogleCloudServiceAccountIntegration(new_key_file_integration).service_account_email- )---class TestEmailIntegrationDomainValidation(BaseTest):- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_successful_domain_creation_ses(self, mock_create_email_domain):- mock_create_email_domain.return_value = {"status": "success", "domain": "successdomain.com"}- config = {"email": "[email protected]", "name": "Test User", "provider": "ses"}- integration = EmailIntegration.create_native_integration(- config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user- )- assert integration.team == self.team- assert integration.config["email"] == "[email protected]"- assert integration.config["provider"] == "ses"- assert integration.config["domain"] == "successdomain.com"- assert integration.config["name"] == "Test User"- assert integration.config["verified"] is False-- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- @patch("products.workflows.backend.providers.SESProvider.verify_email_domain")- def test_duplicate_domain_in_another_organization(self, mock_create_email_domain, mock_verify_email_domain):- mock_create_email_domain.return_value = {"status": "success", "domain": "successdomain.com"}- mock_verify_email_domain.return_value = {"status": "verified", "domain": "example.com"}- # Create an integration with a domain in another organization- other_org = Organization.objects.create(name="other org")- other_team = Team.objects.create(organization=other_org, name="other team")- config = {"email": "[email protected]", "name": "Test User"}- EmailIntegration.create_native_integration(- config, team_id=other_team.id, organization_id=str(other_org.id), created_by=self.user- )-- # Attempt to create the same domain in a different organization should raise ValidationError- with pytest.raises(ValidationError) as exc:- EmailIntegration.create_native_integration(- config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user- )- assert "already exists in another organization" in str(exc.value)-- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_duplicate_domain_in_same_organization_allowed(self, mock_create_email_domain):- mock_create_email_domain.return_value = {"status": "success", "domain": "example.com"}- # Create an integration with a domain in one team- other_team = Team.objects.create(organization=self.organization, name="other team")- config = {"email": "[email protected]", "name": "Test User"}- integration1 = EmailIntegration.create_native_integration(- config, team_id=other_team.id, organization_id=str(self.organization.id), created_by=self.user- )-- # Creating the same domain in a different team in the same organization should succeed- integration2 = EmailIntegration.create_native_integration(- config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user- )-- assert integration1.config["domain"] == "example.com"- assert integration2.config["domain"] == "example.com"- assert integration1.team_id == other_team.id- assert integration2.team_id == self.team.id-- def test_unsupported_email_domain(self):- # Test with a free email domain- config = {"email": "[email protected]", "name": "Test User"}-- with pytest.raises(ValidationError) as exc:- EmailIntegration.create_native_integration(- config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user- )- assert "not supported" in str(exc.value)-- # Test with a disposable email domain- disposable_domain = next(iter(disposable_email_domains_list))- config = {"email": f"user@{disposable_domain}", "name": "Test User"}-- with pytest.raises(ValidationError) as exc:- EmailIntegration.create_native_integration(- config, team_id=self.team.id, organization_id=str(self.organization.id), created_by=self.user- )- assert disposable_domain in str(exc.value)- assert "not supported" in str(exc.value)-- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_cross_org_guard_blocks_mixed_case_domain(self, mock_create_email_domain):- mock_create_email_domain.return_value = {"status": "success", "domain": "example.com"}- other_org = Organization.objects.create(name="other org")- other_team = Team.objects.create(organization=other_org, name="other team")- EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Owner"},- team_id=other_team.id,- organization_id=str(other_org.id),- created_by=self.user,- )-- with pytest.raises(ValidationError) as exc:- EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Attacker"},- team_id=self.team.id,- organization_id=str(self.organization.id),- created_by=self.user,- )- assert "already exists in another organization" in str(exc.value)-- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_stored_domain_is_lowercased(self, mock_create_email_domain):- mock_create_email_domain.return_value = {"status": "success", "domain": "successdomain.com"}- integration = EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Test User", "provider": "ses"},- team_id=self.team.id,- organization_id=str(self.organization.id),- created_by=self.user,- )- assert integration.config["domain"] == "successdomain.com"-- @parameterized.expand(- [- ("gmail_titlecase", "[email protected]"),- ("gmail_uppercase", "[email protected]"),- ("gmail_mixed", "[email protected]"),- ("yahoo_titlecase", "[email protected]"),- ("hotmail_uppercase", "[email protected]"),- ]- )- def test_free_email_block_is_case_insensitive(self, _name, email):- config = {"email": email, "name": "Test User"}- with pytest.raises(ValidationError) as exc:- EmailIntegration.create_native_integration(- config,- team_id=self.team.id,- organization_id=str(self.organization.id),- created_by=self.user,- )- assert "not supported" in str(exc.value)---class TestEmailIntegrationCrossTenantStaleVerification(BaseTest):- def _build_ses_provider(self, tenants_for_domain: dict[str, list[str]] | None = None) -> SESProvider:- patcher = patch("products.workflows.backend.providers.ses.boto3.client")- patcher.start()- self.addCleanup(patcher.stop)-- provider = SESProvider()- provider.ses_client = MagicMock()- provider.ses_v2_client = MagicMock()- provider.sts_client = MagicMock()- provider.sts_client.get_caller_identity.return_value = {"Account": "123456789012"}-- provider.ses_client.verify_domain_identity.return_value = {"VerificationToken": "tok"}- provider.ses_client.verify_domain_dkim.return_value = {"DkimTokens": ["t1", "t2", "t3"]}- provider.ses_client.set_identity_mail_from_domain.return_value = {}-- def _list_resource_tenants(ResourceArn: str) -> dict:- domain = ResourceArn.split("/")[-1]- return {"ResourceTenants": [{"TenantName": t} for t in (tenants_for_domain or {}).get(domain, [])]}-- provider.ses_v2_client.list_resource_tenants.side_effect = _list_resource_tenants- return provider-- def _set_global_ses_success(self, provider, domain: str) -> None:- provider.ses_client.get_identity_verification_attributes.return_value = {- "VerificationAttributes": {domain: {"VerificationStatus": "Success"}}- }- provider.ses_client.get_identity_dkim_attributes.return_value = {- "DkimAttributes": {domain: {"DkimVerificationStatus": "Success"}}- }- provider.ses_client.get_identity_mail_from_domain_attributes.return_value = {- "MailFromDomainAttributes": {domain: {"MailFromDomainStatus": "Success"}}- }-- @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")- def test_verify_email_domain_requires_team_tenant_association(self, mock_resolver_cls):- provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})- self._set_global_ses_success(provider, "partner.com")- dmarc_answer = MagicMock()- dmarc_answer.strings = [b"v=DMARC1; p=none;"]- mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]-- result_team_a = provider.verify_email_domain("partner.com", "feedback", team_id=1)- result_team_b = provider.verify_email_domain("partner.com", "feedback", team_id=999)-- assert result_team_a["status"] == "success"- assert result_team_b["status"] == "pending"-- @patch("products.workflows.backend.providers.SESProvider.delete_identity")- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_destroy_email_integration_deletes_ses_identity(self, mock_create_email_domain, mock_delete_identity):- from posthog.api.integration import IntegrationViewSet-- mock_create_email_domain.return_value = {"status": "success"}- integration = EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Owner"},- team_id=self.team.id,- organization_id=str(self.organization.id),- created_by=self.user,- )-- with self.captureOnCommitCallbacks(execute=True):- IntegrationViewSet().perform_destroy(integration)-- mock_delete_identity.assert_called_once_with("partner.com")- assert not Integration.objects.filter(pk=integration.pk).exists()-- @patch("products.workflows.backend.providers.SESProvider.delete_identity")- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_destroy_email_integration_skips_ses_delete_when_sibling_exists(- self, mock_create_email_domain, mock_delete_identity- ):- from posthog.api.integration import IntegrationViewSet-- mock_create_email_domain.return_value = {"status": "success"}- sibling_team = Team.objects.create(organization=self.organization, name="sibling team")- EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Sibling"},- team_id=sibling_team.id,- organization_id=str(self.organization.id),- created_by=self.user,- )- integration = EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Owner"},- team_id=self.team.id,- organization_id=str(self.organization.id),- created_by=self.user,- )-- with self.captureOnCommitCallbacks(execute=True):- IntegrationViewSet().perform_destroy(integration)-- assert mock_delete_identity.call_count == 0-- def test_create_email_domain_rejects_foreign_tenant_owner(self):- provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})-- with pytest.raises(Exception) as exc:- provider.create_email_domain("partner.com", "feedback", team_id=999, org_team_ids=[999])- assert "already associated with another organization" in str(exc.value)-- def test_create_email_domain_allows_sibling_team_in_same_org(self):- provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})-- provider.create_email_domain(- "partner.com",- "feedback",- team_id=2,- org_team_ids=[1, 2, 3, 4, 5],- )-- @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")- @patch("products.workflows.backend.providers.SESProvider.create_email_domain")- def test_takeover_after_owner_deletes_integration_is_blocked(self, mock_create_email_domain, mock_resolver_cls):- from posthog.api.integration import IntegrationViewSet-- mock_create_email_domain.return_value = {"status": "success"}- dmarc_answer = MagicMock()- dmarc_answer.strings = [b"v=DMARC1; p=none;"]- mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]-- org_a = Organization.objects.create(name="org a")- team_a = Team.objects.create(organization=org_a, name="team a")- org_b = Organization.objects.create(name="org b")- team_b = Team.objects.create(organization=org_b, name="team b")-- integration_a = EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Owner A"},- team_id=team_a.id,- organization_id=str(org_a.id),- created_by=self.user,- )- with patch("products.workflows.backend.providers.SESProvider.delete_identity") as mock_delete:- with self.captureOnCommitCallbacks(execute=True):- IntegrationViewSet().perform_destroy(integration_a)- mock_delete.assert_called_once_with("partner.com")-- integration_b = EmailIntegration.create_native_integration(- {"email": "[email protected]", "name": "Attacker B"},- team_id=team_b.id,- organization_id=str(org_b.id),- created_by=self.user,- )-- provider = self._build_ses_provider(tenants_for_domain={"partner.com": []})- self._set_global_ses_success(provider, "partner.com")-- email_b = EmailIntegration(integration_b)- with patch.object(type(email_b), "ses_provider", new=provider):- result = email_b.verify()-- assert result["status"] == "pending"- integration_b.refresh_from_db()- assert integration_b.config.get("verified") is False-- def test_aws_account_id_is_cached_per_provider(self):- provider = self._build_ses_provider()- provider.sts_client.get_caller_identity.reset_mock()-- for _ in range(5):- provider._identity_arn("partner.com")- provider._identity_arn("other.com")-- assert provider.sts_client.get_caller_identity.call_count == 1---class TestEmailIntegrationSESCleanupOnDelete(BaseTest):- def _create_email_integration(self, email: str, team_id: int, organization_id: str) -> Integration:- with patch("products.workflows.backend.providers.SESProvider.create_email_domain"):- return EmailIntegration.create_native_integration(- {"email": email, "name": "Test"},- team_id=team_id,- organization_id=organization_id,- created_by=self.user,- )-- @patch("products.workflows.backend.providers.SESProvider.delete_identity")- def test_team_cascade_delete_cleans_up_ses_identity(self, mock_delete_identity):- team = Team.objects.create(organization=self.organization, name="doomed team")- self._create_email_integration("[email protected]", team.id, str(self.organization.id))-- with self.captureOnCommitCallbacks(execute=True):- team.delete()-- mock_delete_identity.assert_called_once_with("partner.com")-- @patch("products.workflows.backend.providers.SESProvider.delete_identity")- def test_cascade_delete_skips_ses_cleanup_while_domain_still_in_use(self, mock_delete_identity):- team = Team.objects.create(organization=self.organization, name="doomed team")- self._create_email_integration("[email protected]", team.id, str(self.organization.id))- self._create_email_integration("[email protected]", self.team.id, str(self.organization.id))-- with self.captureOnCommitCallbacks(execute=True):- team.delete()-- mock_delete_identity.assert_not_called()---class TestGitLabIntegrationSSRFProtection:- """Test SSRF protections in GitLabIntegration."""-- @patch("posthog.models.integration.requests.get")- @patch("posthog.models.integration.is_url_allowed")- def test_get_uses_allow_redirects_false(self, mock_is_url_allowed, mock_get):- """GET requests must use allow_redirects=False to prevent redirect-based SSRF bypass."""- from posthog.models.integration import GitLabIntegration-- mock_is_url_allowed.return_value = (True, None)- mock_get.return_value.json.return_value = {"data": "test"}-- GitLabIntegration.get("https://gitlab.com", "projects/1", "token123")-- mock_get.assert_called_once()- call_kwargs = mock_get.call_args.kwargs- assert call_kwargs.get("allow_redirects") is False, "GET must use allow_redirects=False for SSRF protection"-- @patch("posthog.models.integration.requests.post")- @patch("posthog.models.integration.is_url_allowed")- def test_post_uses_allow_redirects_false(self, mock_is_url_allowed, mock_post):- """POST requests must use allow_redirects=False to prevent redirect-based SSRF bypass."""- from posthog.models.integration import GitLabIntegration-- mock_is_url_allowed.return_value = (True, None)- mock_post.return_value.json.return_value = {"data": "test"}-- GitLabIntegration.post("https://gitlab.com", "projects/1/issues", "token123", {"title": "test"})-- mock_post.assert_called_once()- call_kwargs = mock_post.call_args.kwargs- assert call_kwargs.get("allow_redirects") is False, "POST must use allow_redirects=False for SSRF protection"-- @patch("posthog.models.integration.requests.get")- @patch("posthog.models.integration.is_url_allowed")- def test_get_validates_url_before_request(self, mock_is_url_allowed, mock_get):- """URL validation must happen before the request is made."""- from posthog.models.integration import GitLabIntegration, GitLabIntegrationError-- mock_is_url_allowed.return_value = (False, "Private IP address not allowed")-- with pytest.raises(GitLabIntegrationError, match="Invalid GitLab hostname"):- GitLabIntegration.get("http://192.168.1.1", "projects/1", "token123")-- mock_get.assert_not_called()-- @patch("posthog.models.integration.requests.post")- @patch("posthog.models.integration.is_url_allowed")- def test_post_validates_url_before_request(self, mock_is_url_allowed, mock_post):- """URL validation must happen before the request is made."""- from posthog.models.integration import GitLabIntegration, GitLabIntegrationError-- mock_is_url_allowed.return_value = (False, "Private IP address not allowed")-- with pytest.raises(GitLabIntegrationError, match="Invalid GitLab hostname"):- GitLabIntegration.post("http://192.168.1.1", "projects/1/issues", "token123", {"title": "test"})-- mock_post.assert_not_called()---@parameterized_class(- [- {- "integration_cls": PostgreSQLIntegration,- "integration_kind": Integration.IntegrationKind.POSTGRESQL,- },- {- "integration_cls": RedshiftIntegration,- "integration_kind": Integration.IntegrationKind.AWS_REDSHIFT,- },- ]-)-class TestPostgreSQLIntegrationModel(BaseTest):- integration_kind: Integration.IntegrationKind- integration_cls: type[RedshiftIntegration] | type[PostgreSQLIntegration]-- @parameterized.expand(- [- (- "require_no_cert",- {"ssl_mode": "require"},- {},- TLS(ssl_mode="require", ssl_root_cert=MISSING_CERT_PATH),- ),- (- "require_system_cert",- {"ssl_mode": "require", "ssl_root_cert": "system"},- {},- TLS(ssl_mode="require", ssl_root_cert="system"),- ),- (- "verify_ca_with_cert",- {- "ssl_mode": "verify-ca",- "ssl_root_cert": "-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----",- },- {},- TLS(- ssl_mode="verify-ca",- ssl_root_cert="-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----",- ),- ),- (- "prefer_no_cert",- {"ssl_mode": "prefer"},- {},- TLS(ssl_mode="prefer", ssl_root_cert=MISSING_CERT_PATH),- ),- ]- )- def test_tls_with_ssl_configs(self, _name, config_overrides, sensitive_config_overrides, expected_tls):- config = {"host": "db.example.com", "port": 5432, "user": "exporter"}- config.update(config_overrides)-- sensitive_config: dict = {"password": "hunter2"}- sensitive_config.update(sensitive_config_overrides)-- integration = Integration.objects.create(- team=self.team,- kind=self.integration_kind,- integration_id=f"{self.team.pk}-db.example.com-5432-exporter",- config=config,- sensitive_config=sensitive_config,- )-- pq = self.integration_cls(integration)- assert pq.tls() == expected_tls-- @parameterized.expand(- [- (- "defaults",- {},- TLS(ssl_mode="require", ssl_root_cert=MISSING_CERT_PATH),- ),- (- "system_cert",- {"ssl_root_cert": "system"},- TLS(ssl_mode="require", ssl_root_cert="system"),- ),- (- "verify_full_with_cert",- {"ssl_mode": "verify-full", "ssl_root_cert": "cert-data"},- TLS(ssl_mode="verify-full", ssl_root_cert="cert-data"),- ),- ]- )- def test_integration_from_config(self, _name, overrides, expected_tls):- kwargs = {- "team_id": self.team.pk,- "host": "localhost",- "port": 5432,- "user": "exporter",- "password": "super-secret",- }- kwargs.update(overrides)-- integration = self.integration_cls.integration_from_config(**kwargs) # type: ignore- pq = self.integration_cls(integration)-- assert pq.authority() == Authority(host="localhost", port=5432)- assert pq.credentials() == Credentials(user="exporter", password="super-secret")- assert pq.tls() == expected_tls-- assert "password" not in integration.config-- assert integration.sensitive_config["password"] == "super-secret"- assert pq.integration_kind == self.integration_kind---def _make_resend_jwt(payload: dict) -> str:- body = base64.urlsafe_b64encode(json.dumps(payload).encode()).rstrip(b"=").decode()- return f"header.{body}.signature"---@override_settings(RESEND_APP_CLIENT_ID="resend-client-id", RESEND_APP_CLIENT_SECRET="resend-client-secret")-class TestResendIntegrationModel(BaseTest):- def test_oauth_config(self):- config = OauthIntegration.oauth_config_for_kind("resend")- assert config.authorize_url == "https://resend.com/oauth/authorize"- assert config.token_url == "https://api.resend.com/oauth/token"- assert config.token_revoke_url == "https://api.resend.com/oauth/revoke"- assert config.client_id == "resend-client-id"- assert config.client_secret == "resend-client-secret"- assert config.scope == "full_access"- assert config.pkce is True- assert config.id_path == "resend_account_id"-- @override_settings(RESEND_APP_CLIENT_ID="", RESEND_APP_CLIENT_SECRET="")- def test_oauth_config_unconfigured_raises(self):- with pytest.raises(NotImplementedError, match="Resend app not configured"):- OauthIntegration.oauth_config_for_kind("resend")-- @patch("posthog.models.integration.requests.post")- def test_integration_from_oauth_response_extracts_account_from_jwt(self, mock_post):- access_token = _make_resend_jwt({"sub": "acct_123", "email": "[email protected]"})- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": access_token,- "refresh_token": "rt_1",- "expires_in": 900,- "token_type": "Bearer",- }-- with freeze_time("2024-01-01T12:00:00Z"):- integration = OauthIntegration.integration_from_oauth_response(- "resend",- self.team.id,- self.user,- {"code": "code", "state": "token=state_token"},- )-- assert integration.kind == "resend"- assert integration.integration_id == "acct_123"- assert integration.config["resend_account_id"] == "acct_123"- assert integration.config["resend_account_name"] == "[email protected]"- assert integration.config["expires_in"] == 900- assert integration.sensitive_config["access_token"] == access_token- assert integration.sensitive_config["refresh_token"] == "rt_1"-- @patch("posthog.models.integration.requests.post")- def test_integration_from_oauth_response_name_falls_back_without_email(self, mock_post):- access_token = _make_resend_jwt({"sub": "acct_xyz"})- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": access_token,- "refresh_token": "rt",- "expires_in": 900,- }-- integration = OauthIntegration.integration_from_oauth_response(- "resend",- self.team.id,- self.user,- {"code": "code", "state": "token=state_token"},- )-- assert integration.integration_id == "acct_xyz"- assert integration.config["resend_account_name"] == "Resend account acct_xyz"-- @patch("posthog.models.integration.requests.post")- def test_integration_from_oauth_response_without_sub_raises(self, mock_post):- access_token = _make_resend_jwt({"email": "[email protected]"})- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": access_token,- "refresh_token": "rt",- "expires_in": 900,- }-- with pytest.raises(Exception, match="failed to extract integration ID"):- OauthIntegration.integration_from_oauth_response(- "resend",- self.team.id,- self.user,- {"code": "code", "state": "token=state_token"},- )-- @patch("posthog.models.integration.requests.post")- def test_authorization_code_exchange_does_not_follow_redirects(self, mock_post):- # A 307/308 from the token endpoint must not forward client_secret + code to its Location.- access_token = _make_resend_jwt({"sub": "acct_1"})- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": access_token,- "refresh_token": "rt",- "expires_in": 900,- }-- OauthIntegration.integration_from_oauth_response(- "resend",- self.team.id,- self.user,- {"code": "code", "state": "token=state_token"},- )-- assert mock_post.call_args.kwargs["allow_redirects"] is False-- @patch("posthog.models.integration.requests.post")- def test_revoke_token_authenticates_with_client_credentials(self, mock_post):- integration = Integration.objects.create(- team=self.team,- kind="resend",- config={"resend_account_id": "acct_1"},- sensitive_config={"refresh_token": "rt_secret", "access_token": "at_secret"},- )-- OauthIntegration(integration).revoke_token()-- sent = mock_post.call_args.kwargs["data"]- assert sent["token"] == "rt_secret"- assert sent["client_id"] == "resend-client-id"- assert sent["client_secret"] == "resend-client-secret"- assert sent["token_type_hint"] == "refresh_token"---@override_settings(- SALESFORCE_CONSUMER_KEY="salesforce-client-id", SALESFORCE_CONSUMER_SECRET="salesforce-client-secret"-)-class TestPardotIntegrationModel(BaseTest):- def test_oauth_config_requests_the_account_engagement_scope(self):- config = OauthIntegration.oauth_config_for_kind("pardot")-- assert config.authorize_url == "https://login.salesforce.com/services/oauth2/authorize"- assert config.token_url == "https://login.salesforce.com/services/oauth2/token"- assert config.token_revoke_url == "https://login.salesforce.com/services/oauth2/revoke"- assert config.client_id == "salesforce-client-id"- assert config.client_secret == "salesforce-client-secret"- assert config.pkce is True- assert config.id_path == "instance_url"- # Salesforce's `full` scope does not cover the Account Engagement API, so a token- # minted for the CRM kind cannot call it. That is why this kind exists at all.- assert config.scope == "pardot_api refresh_token"- assert config.scope != OauthIntegration.oauth_config_for_kind("salesforce").scope-- def test_pardot_is_an_oauth_kind(self):- # Not being listed makes the authorize + callback endpoints reject the kind and drops- # it out of the scheduled token refresh sweep.- assert "pardot" in OauthIntegration.supported_kinds-- @override_settings(SALESFORCE_CONSUMER_KEY="", SALESFORCE_CONSUMER_SECRET="")- def test_oauth_config_unconfigured_raises(self):- with pytest.raises(NotImplementedError, match="Salesforce app not configured"):- OauthIntegration.oauth_config_for_kind("pardot")-- @patch("posthog.models.integration.reload_integrations_on_workers")- @patch("posthog.models.integration.requests.post")- def test_refresh_uses_the_org_instance_host_and_assumes_an_hour(self, mock_post, mock_reload):- # Account Engagement business units can live on a sandbox org, whose refresh token- # login.salesforce.com rejects, and Salesforce often omits expires_in — without the- # assumed hour the token is never treated as expired and syncs fail on a stale one.- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {"access_token": "REFRESHED_ACCESS_TOKEN"}-- instance_url = "https://acme--sandbox.sandbox.my.salesforce.com"- integration = Integration.objects.create(- team=self.team,- kind="pardot",- config={"instance_url": instance_url, "refreshed_at": int(time.time())},- sensitive_config={"refresh_token": "REFRESH"},- )-- OauthIntegration(integration).refresh_access_token()-- assert integration.errors == ""- assert mock_post.call_args.args[0] == f"{instance_url}/services/oauth2/token"- assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"- assert integration.config["expires_in"] == 3600-- @patch("posthog.models.integration.requests.post")- def test_expiry_is_assumed_when_the_token_response_omits_it(self, mock_post):- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {- "access_token": "at",- "refresh_token": "rt",- "instance_url": "https://acme.my.salesforce.com",- }-- integration = OauthIntegration.integration_from_oauth_response(- "pardot",- self.team.id,- self.user,- {"code": "code", "state": "token=state_token"},- )-- assert integration.integration_id == "https://acme.my.salesforce.com"- assert integration.config["expires_in"] == 3600---@override_settings(- YOUTUBE_ANALYTICS_APP_CLIENT_ID="youtube-client-id",- YOUTUBE_ANALYTICS_APP_CLIENT_SECRET="youtube-client-secret",-)-class TestYouTubeAnalyticsIntegrationModel(BaseTest):- def test_oauth_config(self):- config = OauthIntegration.oauth_config_for_kind("youtube-analytics")-- assert config.authorize_url == "https://accounts.google.com/o/oauth2/v2/auth"- assert config.token_url == "https://oauth2.googleapis.com/token"- assert config.client_id == "youtube-client-id"- assert config.client_secret == "youtube-client-secret"- assert config.id_path == "sub"- assert config.name_path == "email"- # A refresh token only comes back when consent is forced, and the sync depends on one.- assert config.additional_authorize_params == {"access_type": "offline", "prompt": "consent"}-- def test_oauth_config_requests_analytics_and_channel_read_scopes(self):- scopes = set(OauthIntegration.oauth_config_for_kind("youtube-analytics").scope.split())-- assert "https://www.googleapis.com/auth/yt-analytics.readonly" in scopes- assert "https://www.googleapis.com/auth/youtube.readonly" in scopes- # Channel reports carry no revenue metrics, so the monetary scope is never asked for.- assert "https://www.googleapis.com/auth/yt-analytics-monetary.readonly" not in scopes-- @override_settings(YOUTUBE_ANALYTICS_APP_CLIENT_ID="", YOUTUBE_ANALYTICS_APP_CLIENT_SECRET="")- def test_oauth_config_unconfigured_raises(self):- with pytest.raises(NotImplementedError, match="YouTube Analytics app not configured"):- OauthIntegration.oauth_config_for_kind("youtube-analytics")---@override_settings(INSTAGRAM_APP_CLIENT_ID="instagram-client-id", INSTAGRAM_APP_CLIENT_SECRET="instagram-client-secret")-class TestInstagramIntegrationModel(BaseTest):- def test_oauth_config(self):- config = OauthIntegration.oauth_config_for_kind("instagram")-- # Same Graph version as the other Meta kinds: an older pin here makes the OAuth dialog- # reject the permission set before anyone reaches a consent screen.- assert config.authorize_url == "https://www.facebook.com/v25.0/dialog/oauth"- assert config.token_url == "https://graph.facebook.com/v25.0/oauth/access_token"- assert config.token_info_url == "https://graph.facebook.com/v25.0/me"- assert config.client_id == "instagram-client-id"- assert config.client_secret == "instagram-client-secret"- assert config.id_path == "id"- assert config.name_path == "name"- # Instagram is reached through the Facebook page it is linked to, so the page scopes- # are as load-bearing as the Instagram ones.- assert set(config.scope.split(" ")) == {- "instagram_business_basic",- "instagram_business_manage_insights",- "instagram_business_manage_comments",- "pages_show_list",- "pages_read_engagement",- }-- @override_settings(INSTAGRAM_APP_CLIENT_ID="", INSTAGRAM_APP_CLIENT_SECRET="")- def test_oauth_config_unconfigured_raises(self):- with pytest.raises(NotImplementedError, match="Instagram app not configured"):- OauthIntegration.oauth_config_for_kind("instagram")-- def test_the_instagram_grant_is_separate_from_the_meta_ads_one(self):- # Both ride the same Meta app, but an ads grant carries none of the Instagram scopes,- # so pointing the Instagram source at a meta-ads integration must not be possible.- integration = Integration.objects.create(team=self.team, kind="meta-ads", integration_id="1")-- with pytest.raises(Exception, match="wrong 'kind'"):- InstagramIntegration(integration)-- @patch("posthog.models.integration.requests.post")- def test_refresh_exchanges_the_long_lived_token_rather_than_a_refresh_token(self, mock_post):- # Meta issues no refresh token: the current access token is swapped for a fresh one.- integration = Integration.objects.create(- team=self.team,- kind="instagram",- integration_id="fb-user-1",- config={"expires_in": 100, "refreshed_at": int(time.time()) - 90},- sensitive_config={"access_token": "old-token"},- )- mock_post.return_value.status_code = 200- mock_post.return_value.json.return_value = {"access_token": "new-token", "expires_in": 5184000}-- InstagramIntegration(integration).refresh_access_token()-- sent = mock_post.call_args.kwargs["data"]- assert sent["grant_type"] == "fb_exchange_token"- assert sent["fb_exchange_token"] == "old-token"- assert sent["client_id"] == "instagram-client-id"- integration.refresh_from_db()- assert integration.sensitive_config["access_token"] == "new-token"- assert integration.errors == ""diff --git a/posthog/models/test/test_integration_repository_cache.py b/posthog/models/test/test_integration_repository_cache.pyindex 8039f31e6341..6dffc104ae8c 100644--- a/posthog/models/test/test_integration_repository_cache.py+++ b/posthog/models/test/test_integration_repository_cache.py@@ -70,7 +70,7 @@ class TestGitHubRepositoryFullCache(BaseTest):return responses[path]return patch(- "posthog.models.integration.GitHubIntegration._gh_api_get", autospec=True, side_effect=_side_effect+ "posthog.models.integration.github.GitHubIntegration._gh_api_get", autospec=True, side_effect=_side_effect)def _cache_for(self, integration: Integration) -> GitHubRepositoryFullCache:@@ -108,7 +108,7 @@ class TestGitHubRepositoryFullCache(BaseTest):tree_paths="old/path",)- with patch("posthog.models.integration.GitHubIntegration._gh_api_get", autospec=True) as mock_gh_api_get:+ with patch("posthog.models.integration.github.GitHubIntegration._gh_api_get", autospec=True) as mock_gh_api_get:entry = async_to_sync(self._cache_for(integration).sync_full_cache_entry_async)("posthog/posthog")assert mock_gh_api_get.call_count == 0 # TTL short-circuits before any API calls@@ -209,7 +209,7 @@ class TestGitHubRepositoryFullCache(BaseTest):return responses[path]with patch(- "posthog.models.integration.GitHubIntegration._gh_api_get",+ "posthog.models.integration.github.GitHubIntegration._gh_api_get",autospec=True,side_effect=_side_effect,):@@ -233,7 +233,7 @@ class TestGitHubRepositoryFullCache(BaseTest):return responses[path]with patch(- "posthog.models.integration.GitHubIntegration._gh_api_get",+ "posthog.models.integration.github.GitHubIntegration._gh_api_get",autospec=True,side_effect=_side_effect,):@@ -253,7 +253,7 @@ class TestGitHubRepositoryFullCache(BaseTest):return responses[path]with patch(- "posthog.models.integration.GitHubIntegration._gh_api_get",+ "posthog.models.integration.github.GitHubIntegration._gh_api_get",autospec=True,side_effect=_side_effect,):diff --git a/posthog/tasks/test/test_integrations.py b/posthog/tasks/test/test_integrations.pyindex 487df83eefbe..d784aed8b2aa 100644--- a/posthog/tasks/test/test_integrations.py+++ b/posthog/tasks/test/test_integrations.py@@ -56,7 +56,7 @@ class TestIntegrationsTasks(APIBaseTest):# id reaches refresh_integration, it must not spend the rotating token via the unlocked path.integration = self.create_integration("resend", config={"refreshed_at": time.time() - 3600})- with patch("posthog.models.integration.OauthIntegration.refresh_access_token") as refresh_mock:+ with patch("posthog.models.integration.oauth.OauthIntegration.refresh_access_token") as refresh_mock:refresh_integration(integration.id)assert refresh_mock.called is False@@ -91,7 +91,7 @@ class TestIntegrationsTasks(APIBaseTest):},)- with patch("posthog.models.integration.OauthIntegration.refresh_access_token") as refresh_mock:+ with patch("posthog.models.integration.oauth.OauthIntegration.refresh_access_token") as refresh_mock:refresh_integration(integration.id)assert refresh_mock.called is False@@ -109,7 +109,7 @@ class TestIntegrationsTasks(APIBaseTest):# just-loaded row so a task that finds it already fresh skips the mint instead of re-minting.integration = self.create_integration("github", config={"refreshed_at": refreshed_at, "expires_in": 3600})- with patch("posthog.models.integration.GitHubIntegration.refresh_access_token") as refresh_mock:+ with patch("posthog.models.integration.github.GitHubIntegration.refresh_access_token") as refresh_mock:refresh_integration(integration.id)assert refresh_mock.called is expected_refresheddiff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex feaa686d2001..0cba2211b572 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -45,7 +45,7 @@1 posthog/management/commands/create_channel_definitions_file.py1 posthog/models/file_system/file_system_representation.py1 posthog/models/group/util.py-1 posthog/models/integration.py+1 posthog/models/integration/oauth.py1 posthog/models/person/bulk_delete.py1 posthog/models/person/util.py1 posthog/personhog_client/fake_client.pydiff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex 459febb8e3bb..a96d91a67105 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -52,7 +52,7 @@ post_delete:posthog.models.event_ingestion_restriction_config.delete_redis_cachepost_delete:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__init_subclass__.<locals>._file_system_post_deletepost_delete:posthog.models.file_system.file_system_view_log._drop_view_logs_when_file_deletedpost_delete:posthog.models.global_rate_limit_threshold_config.update_redis_thresholds_on_delete-post_delete:posthog.models.integration.cleanup_ses_identity_on_integration_delete+post_delete:posthog.models.integration.email.cleanup_ses_identity_on_integration_deletepost_delete:posthog.models.oauth._block_cimd_url_on_application_deletepost_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membership_removalpost_delete:posthog.models.organization.clean_up_event_streams_on_membership_removaldiff --git a/products/engineering_analytics/backend/logic/job_logs/coordinator.py b/products/engineering_analytics/backend/logic/job_logs/coordinator.pyindex 84716fdb7f4b..2f5d86ffdaa2 100644--- a/products/engineering_analytics/backend/logic/job_logs/coordinator.py+++ b/products/engineering_analytics/backend/logic/job_logs/coordinator.py@@ -28,7 +28,7 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context-from posthog.models.integration import _is_safe_github_repo_path+from posthog.models.integration.github import _is_safe_github_repo_pathfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowdiff --git a/products/engineering_analytics/backend/logic/job_logs/fetcher.py b/products/engineering_analytics/backend/logic/job_logs/fetcher.pyindex 8de8bf6ab36a..ede544f1ef4e 100644--- a/products/engineering_analytics/backend/logic/job_logs/fetcher.py+++ b/products/engineering_analytics/backend/logic/job_logs/fetcher.py@@ -9,7 +9,7 @@ the Temporal retry honors the reset.import contextlibfrom posthog.egress.github.transport import github_request, raise_if_github_rate_limited-from posthog.models.integration import _is_safe_github_repo_path+from posthog.models.integration.github import _is_safe_github_repo_path_GITHUB_API = "https://api.github.com"# A connected repo's failed job can print an arbitrarily large log; cap the bytes we pull into memorydiff --git a/products/review_hog/backend/tests/test_installation_auth.py b/products/review_hog/backend/tests/test_installation_auth.pyindex 9d4a88d92b01..13b88b3a53e9 100644--- a/products/review_hog/backend/tests/test_installation_auth.py+++ b/products/review_hog/backend/tests/test_installation_auth.py@@ -15,7 +15,7 @@ from products.review_hog.backend.temporal.activities import (# The true network boundary: first_for_team_repository probes GitHub with an authenticated# GET /repos/{repository} per candidate integration row.-_CAN_ACCESS = "posthog.models.integration.GitHubIntegration.installation_can_access_repository"+_CAN_ACCESS = "posthog.models.integration.github.GitHubIntegration.installation_can_access_repository"class TestInstallationAuth(BaseTest):diff --git a/products/slack_app/backend/tests/services/test_slack_user_oauth.py b/products/slack_app/backend/tests/services/test_slack_user_oauth.pyindex a425a07da67b..e6ab534a29df 100644--- a/products/slack_app/backend/tests/services/test_slack_user_oauth.py+++ b/products/slack_app/backend/tests/services/test_slack_user_oauth.py@@ -169,7 +169,7 @@ class TestResolveSlackUserWithLink:delegates the lookup to it."""- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.is_slack_app_oauth_enabled")def test_flag_off_falls_through_to_email_path_unchanged(self, mock_flag, mock_webclient_class, org_team_user, workspace_integration, link_user@@ -191,7 +191,7 @@ class TestResolveSlackUserWithLink:assert mock_client.users_info.calledassert result.slack_email == "[email protected]"- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.is_slack_app_oauth_enabled")def test_flag_on_with_link_short_circuits_email_lookup(self, mock_flag, mock_webclient_class, org_team_user, workspace_integration, link_user@@ -217,7 +217,7 @@ class TestResolveSlackUserWithLink:# `tests/test_zz_resolve_slack_user_with_link_no_access.py` — see that# file's module docstring for why it can't live next to its siblings here.- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.post_link_invite_message")@patch("products.slack_app.backend.api.is_slack_app_oauth_enabled")def test_flag_on_with_no_link_and_no_membership_posts_invite(@@ -255,7 +255,7 @@ class TestResolveSlackUserWithLink:assert invite_kwargs["slack_email"] == "[email protected]"assert invite_kwargs["invite_url"].startswith("http")- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.post_link_invite_message")@patch("products.slack_app.backend.api.is_slack_app_oauth_enabled")def test_flag_off_with_no_membership_does_not_post_invite(diff --git a/products/slack_app/backend/tests/test_get_slack_email_for_user.py b/products/slack_app/backend/tests/test_get_slack_email_for_user.pyindex ee99cbaf2cc3..09e3e44d4937 100644--- a/products/slack_app/backend/tests/test_get_slack_email_for_user.py+++ b/products/slack_app/backend/tests/test_get_slack_email_for_user.py@@ -34,7 +34,7 @@ def _slack_api_error(error_code):class TestGetSlackEmailForUser:- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_returns_email_when_present_in_fresh_response(self, mock_webclient_class, integration):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -47,7 +47,7 @@ class TestGetSlackEmailForUser:assert email == "[email protected]"assert SlackUserProfileCache.objects.filter(integration=integration, slack_user_id="U1").exists()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_logs_empty_response_when_users_info_returns_blank(self, mock_webclient_class, integration, caplog):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -62,7 +62,7 @@ class TestGetSlackEmailForUser:assert email is Noneassert any("slack_app_resolve_user_email_empty_response" in record.message for record in caplog.records)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_logs_missing_email_when_profile_has_no_email(self, mock_webclient_class, integration, caplog):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -88,7 +88,7 @@ class TestGetSlackEmailForUser:"token_expired",],)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_auth_error_logs_token_broken_flag(self, mock_webclient_class, integration, error_code, caplog):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -106,7 +106,7 @@ class TestGetSlackEmailForUser:assert any(f"'error_code': '{error_code}'" in r.message for r in failed)assert any("'token_broken': True" in r.message for r in failed)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_non_auth_slack_error_does_not_flag_token_broken(self, mock_webclient_class, integration, caplog):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -121,7 +121,7 @@ class TestGetSlackEmailForUser:assert all("'token_broken': False" in r.message for r in failed)assert any("'error_code': 'user_not_found'" in r.message for r in failed)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_generic_exception_logs_without_error_code(self, mock_webclient_class, integration, caplog):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -153,7 +153,7 @@ class TestAuthStateSideEffects:yieldcache.clear()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_success_does_not_touch_auth_state(self, mock_webclient_class, integration):# The positive cache verdict is owned by the resolver's eager# ``auth.test`` layer. A successful ``users.info`` can hit the DB cache@@ -176,7 +176,7 @@ class TestAuthStateSideEffects:"error_code",["token_revoked", "invalid_auth", "not_authed", "account_inactive", "token_expired"],)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_auth_class_error_writes_broken_state(self, mock_webclient_class, integration, error_code):from products.slack_app.backend.services.slack_auth import get_cached_auth_state@@ -191,7 +191,7 @@ class TestAuthStateSideEffects:assert state.ok is Falseassert state.error_code == error_code- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_non_auth_slack_error_does_not_touch_cache(self, mock_webclient_class, integration):# ``user_not_found`` says nothing about token validity, so leaving the# cache untouched keeps the resolver from demoting a healthy install@@ -206,7 +206,7 @@ class TestAuthStateSideEffects:assert get_cached_auth_state(integration.id) is None- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_transient_exception_does_not_touch_cache(self, mock_webclient_class, integration):# Network blips and Slack 5xx must not brick the workspace by writing# a negative verdict for the full TTL.diff --git a/products/slack_app/backend/tests/test_inbox_channel.py b/products/slack_app/backend/tests/test_inbox_channel.pyindex 00c0ab0de9dd..0c8e040c2866 100644--- a/products/slack_app/backend/tests/test_inbox_channel.py+++ b/products/slack_app/backend/tests/test_inbox_channel.py@@ -39,7 +39,7 @@ class TestInboxChannel:mock_webclient_class.return_value = clientreturn client- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_creates_channel_and_sets_team_default(self, mock_webclient_class):client = self._client(mock_webclient_class)client.conversations_list.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}@@ -51,7 +51,7 @@ class TestInboxChannel:client.conversations_create.assert_called_once_with(name="posthog-inbox", is_private=False)assert get_default_slack_notification_channel(self.team.id) == "C999|#posthog-inbox"- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_reuses_configured_channel(self, mock_webclient_class):client = self._client(mock_webclient_class)set_default_slack_notification_channel(self.team.id, "C777|#posthog-inbox")@@ -63,7 +63,7 @@ class TestInboxChannel:client.conversations_create.assert_not_called()client.conversations_list.assert_not_called()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_reuses_existing_channel_by_name_without_manage_scope(self, mock_webclient_class):# Without channels:manage we can't create, so the only path is to find an existing channel by name.client = self._client(mock_webclient_class)@@ -80,7 +80,7 @@ class TestInboxChannel:client.conversations_create.assert_not_called()assert get_default_slack_notification_channel(self.team.id) == "C555|#posthog-inbox"- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_create_name_taken_falls_back_to_lookup(self, mock_webclient_class):# Create-first: we attempt to create straight away; name_taken triggers the lookup to resolve the id.client = self._client(mock_webclient_class)@@ -95,7 +95,7 @@ class TestInboxChannel:assert result == ("C111", "#posthog-inbox")assert get_default_slack_notification_channel(self.team.id) == "C111|#posthog-inbox"- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_missing_scope_and_no_channel_returns_none(self, mock_webclient_class):client = self._client(mock_webclient_class)self.integration.config = {"scope": "chat:write"}@@ -108,7 +108,7 @@ class TestInboxChannel:client.conversations_create.assert_not_called()assert get_default_slack_notification_channel(self.team.id) is None- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_has_inbox_scopes(self, mock_webclient_class):self._client(mock_webclient_class)@@ -120,49 +120,49 @@ class TestInboxChannel:self.integration.save()assert inbox_channel.has_inbox_scopes(self.integration) is False- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_is_inbox_channel_by_configured_id(self, mock_webclient_class):self._client(mock_webclient_class)set_default_slack_notification_channel(self.team.id, "C222|#posthog-inbox")assert inbox_channel.is_inbox_channel(self.integration, "C222") is True- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_is_inbox_channel_by_name_fallback(self, mock_webclient_class):client = self._client(mock_webclient_class)client.conversations_info.return_value = {"channel": {"id": "C333", "name": "posthog-inbox"}}assert inbox_channel.is_inbox_channel(self.integration, "C333") is True- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_is_inbox_channel_false_for_other_channel(self, mock_webclient_class):client = self._client(mock_webclient_class)client.conversations_info.return_value = {"channel": {"id": "C444", "name": "random"}}assert inbox_channel.is_inbox_channel(self.integration, "C444") is False- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_invite_success(self, mock_webclient_class):client = self._client(mock_webclient_class)assert inbox_channel.invite_user_to_inbox(self.integration, "C1", "U1") is Trueclient.conversations_invite.assert_called_once_with(channel="C1", users="U1")- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_invite_already_in_channel_is_success(self, mock_webclient_class):client = self._client(mock_webclient_class)client.conversations_invite.side_effect = SlackApiError("already_in_channel", {"error": "already_in_channel"})assert inbox_channel.invite_user_to_inbox(self.integration, "C1", "U1") is True- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_invite_other_error_returns_false(self, mock_webclient_class):client = self._client(mock_webclient_class)client.conversations_invite.side_effect = SlackApiError("missing_scope", {"error": "missing_scope"})assert inbox_channel.invite_user_to_inbox(self.integration, "C1", "U1") is False- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_invite_joins_and_retries_on_not_in_channel(self, mock_webclient_class):client = self._client(mock_webclient_class)client.conversations_invite.side_effect = [@@ -174,7 +174,7 @@ class TestInboxChannel:client.conversations_join.assert_called_once_with(channel="C1")assert client.conversations_invite.call_count == 2- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_invite_returns_false_when_join_fails(self, mock_webclient_class):client = self._client(mock_webclient_class)client.conversations_invite.side_effect = SlackApiError("not_in_channel", {"error": "not_in_channel"})@@ -182,7 +182,7 @@ class TestInboxChannel:assert inbox_channel.invite_user_to_inbox(self.integration, "C1", "U1") is False- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_configured_channel_preserved_on_transient_error(self, mock_webclient_class):client = self._client(mock_webclient_class)set_default_slack_notification_channel(self.team.id, "C_CUSTOM|#alerts")@@ -195,7 +195,7 @@ class TestInboxChannel:client.conversations_list.assert_not_called()assert get_default_slack_notification_channel(self.team.id) == "C_CUSTOM|#alerts"- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_configured_channel_replaced_when_definitely_gone(self, mock_webclient_class):client = self._client(mock_webclient_class)set_default_slack_notification_channel(self.team.id, "C_OLD|#alerts")@@ -208,7 +208,7 @@ class TestInboxChannel:assert result == ("C_NEW", "#posthog-inbox")assert get_default_slack_notification_channel(self.team.id) == "C_NEW|#posthog-inbox"- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_ensure_returns_none_when_create_claimed_by_other(self, mock_webclient_class):client = self._client(mock_webclient_class)cache.add("slack_app:inbox_channel_create:v1:T12345", True, timeout=60)@@ -219,7 +219,7 @@ class TestInboxChannel:assert result is Noneclient.conversations_create.assert_not_called()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_ensure_handles_conversations_list_error(self, mock_webclient_class):# name_taken sends us to the lookup; a transient list error there must fail closed (None).client = self._client(mock_webclient_class)@@ -230,7 +230,7 @@ class TestInboxChannel:assert result is None- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_is_channel_member(self, mock_webclient_class):client = self._client(mock_webclient_class)client.conversations_members.return_value = {"members": ["U1", "U2"], "response_metadata": {"next_cursor": ""}}diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.pyindex 90d88ef77ef9..2ee7612cb301 100644--- a/products/slack_app/backend/tests/test_integration_resolver.py+++ b/products/slack_app/backend/tests/test_integration_resolver.py@@ -525,7 +525,7 @@ class TestLoadIntegrationsAuthStateFilter:# to hit the real Slack API every time the cache is cold. Context# manager so a failure inside ``yield`` still cleans up (manual# ``start()/stop()`` would leak the patch into sibling tests).- with patch("posthog.models.integration.WebClient") as mock_webclient_class:+ with patch("posthog.models.integration.slack.WebClient") as mock_webclient_class:mock_client = MagicMock()mock_webclient_class.return_value = mock_clientmock_client.auth_test.return_value = {"user_id": "U_BOT"}diff --git a/products/slack_app/backend/tests/test_onboarding.py b/products/slack_app/backend/tests/test_onboarding.pyindex 355d1eb67f3e..f84e299852b7 100644--- a/products/slack_app/backend/tests/test_onboarding.py+++ b/products/slack_app/backend/tests/test_onboarding.py@@ -61,7 +61,7 @@ class TestOnboarding:parts.append(txt if isinstance(txt, str) else (txt or {}).get("text", ""))return " ".join(parts)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_dm_join_button_when_channel_exists_with_scope(self, mock_webclient_class):client = self._client(mock_webclient_class)set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")@@ -71,7 +71,7 @@ class TestOnboarding:assert onboarding.INBOX_JOIN_ACTION_ID in self._action_ids(blocks)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_dm_instructions_when_channel_exists_without_scope(self, mock_webclient_class):client = self._client(mock_webclient_class)self.integration.config = {"scope": "chat:write"}@@ -84,7 +84,7 @@ class TestOnboarding:assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(blocks)assert "workspace" in self._all_text(blocks)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_dm_create_button_when_no_channel_with_scope(self, mock_webclient_class):self._client(mock_webclient_class)@@ -92,7 +92,7 @@ class TestOnboarding:assert onboarding.INBOX_CREATE_ACTION_ID in self._action_ids(blocks)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_dm_instructions_with_inbox_link_when_no_channel_no_scope(self, mock_webclient_class):self._client(mock_webclient_class)self.integration.config = {"scope": "chat:write"}@@ -103,7 +103,7 @@ class TestOnboarding:assert onboarding.INBOX_CREATE_ACTION_ID not in self._action_ids(blocks)assert "/inbox" in self._all_text(blocks)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_send_onboarding_dm_posts_each_call(self, mock_webclient_class):# No per-user dedupe — onboarding is sent once because the install hook fires once, not# because send_onboarding_dm suppresses repeats.@@ -113,14 +113,14 @@ class TestOnboarding:assert onboarding.send_onboarding_dm(self.integration, "U1") is Trueassert client.chat_postMessage.call_count == 2- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_send_onboarding_dm_skips_empty_user(self, mock_webclient_class):client = self._client(mock_webclient_class)assert onboarding.send_onboarding_dm(self.integration, "") is Falseclient.chat_postMessage.assert_not_called()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_run_install_onboarding_creates_invites_and_dms(self, mock_webclient_class):client = self._client(mock_webclient_class)self.integration.config = {"scope": "channels:manage,chat:write", "authed_user": {"id": "U_INSTALL"}}@@ -136,7 +136,7 @@ class TestOnboarding:assert client.chat_postMessage.calledassert get_default_slack_notification_channel(self.team.id) == "C_NEW|#posthog-inbox"- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_run_install_onboarding_noop_when_missing_scope(self, mock_webclient_class):client = self._client(mock_webclient_class)# No channels:manage scope -> onboarding is gated off for this install.@@ -148,7 +148,7 @@ class TestOnboarding:client.conversations_create.assert_not_called()client.chat_postMessage.assert_not_called()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_send_onboarding_dm_returns_false_on_post_failure(self, mock_webclient_class):client = self._client(mock_webclient_class)client.chat_postMessage.side_effect = [@@ -160,7 +160,7 @@ class TestOnboarding:assert onboarding.send_onboarding_dm(self.integration, "U1") is Trueassert client.chat_postMessage.call_count == 2- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_appends_github_button_when_missing(self, mock_webclient_class):self._client(mock_webclient_class)@@ -174,7 +174,7 @@ class TestOnboarding:)assert onboarding.INBOX_CREATE_ACTION_ID in self._action_ids(blocks)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_omits_join_when_already_member(self, mock_webclient_class):client = self._client(mock_webclient_class)set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")@@ -187,7 +187,7 @@ class TestOnboarding:assert blocks != []assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(blocks)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_already_member_shows_only_github(self, mock_webclient_class):client = self._client(mock_webclient_class)set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")@@ -204,7 +204,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding._has_team_github", return_value=True)@patch("products.slack_app.backend.onboarding._has_personal_github", return_value=True)@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_send_onboarding_dm_posts_even_when_all_steps_satisfied(self, mock_webclient_class, _resolve, _personal, _team, _responder):@@ -217,7 +217,7 @@ class TestOnboarding:assert onboarding.send_onboarding_dm(self.integration, "U1") is Trueclient.chat_postMessage.assert_called_once()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_no_github_block_when_connected(self, mock_webclient_class):self._client(mock_webclient_class)@@ -228,7 +228,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=123)@patch("products.slack_app.backend.onboarding._has_personal_github", return_value=False)@patch("products.slack_app.backend.onboarding._has_team_github", return_value=False)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_send_onboarding_dm_includes_github_button(self, mock_webclient_class, _mock_team, _mock_personal, _mock_resolve):@@ -239,7 +239,7 @@ class TestOnboarding:urls = self._url_buttons(client.chat_postMessage.call_args.kwargs["blocks"])assert any("/integrations/connect/github/" in u and "connect_from=slack" in u for u in urls)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_sources_inline_checkboxes(self, mock_webclient_class):self._client(mock_webclient_class)@@ -255,7 +255,7 @@ class TestOnboarding:assert block["block_id"] == f"{onboarding.INBOX_SOURCES_BLOCK_PREFIX}:{self.integration.id}"assert "Choose what I watch" in self._all_text(blocks)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_shows_done_steps_as_checks(self, mock_webclient_class):self._client(mock_webclient_class)@@ -269,7 +269,7 @@ class TestOnboarding:assert "Posting to #posthog-inbox" in textassert onboarding.INBOX_SOURCES_CHECKBOXES_ACTION in self._action_ids(blocks)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_omits_ai_approval_when_done(self, mock_webclient_class):self._client(mock_webclient_class)@@ -279,7 +279,7 @@ class TestOnboarding:assert "AI data processing" not in " ".join(str(b) for b in blocks)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_always_returns_message_even_when_all_done(self, mock_webclient_class):self._client(mock_webclient_class)@@ -292,7 +292,7 @@ class TestOnboarding:assert not any("/integrations/connect/github" in u for u in self._url_buttons(all_done))@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_apply_sources_selection_syncs_checkboxes(self, mock_webclient_class, _resolve):from products.signals.backend.facade.api import has_enabled_source@@ -313,7 +313,7 @@ class TestOnboarding:set_sources(self.team.id, None, ["error_tracking"])assert has_enabled_source(self.team.id) is True- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_ai_approval_checkbox_for_admin_and_trails(self, mock_webclient_class):self._client(mock_webclient_class)@@ -334,7 +334,7 @@ class TestOnboarding:assert ai_block["elements"][0]["type"] == "checkboxes"assert "AI data processing" not in text # fixed notification text, not the step copy- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_build_dm_ai_approval_note_for_non_admin_no_button(self, mock_webclient_class):self._client(mock_webclient_class)@@ -353,7 +353,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding._is_org_admin", return_value=True)@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_approve_ai_data_processing_admin_sets_org_flag(self, mock_webclient_class, _resolve, _admin):self._client(mock_webclient_class)self.organization.is_ai_data_processing_approved = False@@ -367,7 +367,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding._is_org_admin", return_value=False)@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_approve_ai_data_processing_non_admin_rejected(self, mock_webclient_class, _resolve, _admin):self._client(mock_webclient_class)self.organization.is_ai_data_processing_approved = False@@ -384,7 +384,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding._has_team_github", return_value=True)@patch("products.slack_app.backend.onboarding._has_personal_github", return_value=True)@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_send_onboarding_dm_gates_on_ai_approval_admin(self, mock_webclient_class, _resolve, _personal, _team, _responder, _admin):@@ -405,7 +405,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding._has_team_github", return_value=True)@patch("products.slack_app.backend.onboarding._has_personal_github", return_value=True)@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_send_onboarding_dm_non_admin_gets_note_not_button(self, mock_webclient_class, _resolve, _personal, _team, _responder, _admin):@@ -436,7 +436,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding.capture_slack_event")@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_send_onboarding_dm_captures_dm_sent(self, mock_webclient_class, _resolve, mock_capture):client = self._client(mock_webclient_class)client.conversations_list.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}@@ -446,7 +446,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding.capture_slack_event")@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_apply_sources_captures_source_enabled(self, mock_webclient_class, _resolve, mock_capture):self._client(mock_webclient_class)_resolve.return_value = self.user.id@@ -457,7 +457,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding.capture_slack_event")@patch("products.slack_app.backend.onboarding._onboarding_status")- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_maybe_complete_fires_completed_when_all_done(self, mock_webclient_class, mock_status, mock_capture):self._client(mock_webclient_class)mock_status.return_value = (7, dict.fromkeys(onboarding.OnboardingStep, True))@@ -468,7 +468,7 @@ class TestOnboarding:@patch("products.slack_app.backend.onboarding.capture_slack_event")@patch("products.slack_app.backend.onboarding._onboarding_status")- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_maybe_complete_no_completed_when_remaining(self, mock_webclient_class, mock_status, mock_capture):self._client(mock_webclient_class)status = dict.fromkeys(onboarding.OnboardingStep, True)@@ -479,7 +479,7 @@ class TestOnboarding:assert onboarding.EVENT_COMPLETED not in [c.args[1] for c in mock_capture.call_args_list]- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_dm_leads_with_self_driving_intro(self, mock_webclient_class):self._client(mock_webclient_class)diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.pyindex 4aa632e0089d..1baff7c7bfde 100644--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py@@ -187,7 +187,7 @@ class TestRepoPickerOptions(TestCase):assert response.status_code == 200assert response.json()["options"] == []- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")@patch("products.slack_app.backend.api.SlackIntegration.slack_config")@@ -221,7 +221,7 @@ class TestRepoPickerOptions(TestCase):mock_asyncio_run.assert_called_once()mock_webclient_class.return_value.chat_update.assert_called_once()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")@patch("products.slack_app.backend.api.SlackIntegration.slack_config")@@ -257,7 +257,7 @@ class TestRepoPickerOptions(TestCase):update_call = mock_webclient_class.return_value.chat_update.call_args.kwargsassert "without a repository" in update_call["text"].lower()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.SlackIntegration.slack_config")def test_submit_without_workflow_id_posts_expired(self, mock_config, mock_webclient_class):mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}@@ -285,7 +285,7 @@ class TestRepoPickerOptions(TestCase):assert "selection expired" in mock_client.chat_postMessage.call_args.kwargs["text"].lower()assert "posthog again" in mock_client.chat_postMessage.call_args.kwargs["text"].lower()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")@patch("products.slack_app.backend.api.SlackIntegration.slack_config")diff --git a/products/slack_app/backend/tests/test_resolve_slack_user.py b/products/slack_app/backend/tests/test_resolve_slack_user.pyindex 5d85f1d0a32b..f9c82ed6273e 100644--- a/products/slack_app/backend/tests/test_resolve_slack_user.py+++ b/products/slack_app/backend/tests/test_resolve_slack_user.py@@ -30,7 +30,7 @@ class TestResolveSlackUser:sensitive_config={"access_token": "xoxb-test"},)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_success(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -51,7 +51,7 @@ class TestResolveSlackUser:pytest.param("[email protected]", id="all_uppercase"),],)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_matches_email_case_insensitively(self, mock_webclient_class, slack_email):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -64,7 +64,7 @@ class TestResolveSlackUser:assert result.user.email == "[email protected]"assert result.slack_email == slack_email- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_missing_email(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -77,7 +77,7 @@ class TestResolveSlackUser:mock_client.chat_postMessage.assert_called_once()assert "email" in mock_client.chat_postMessage.call_args.kwargs["text"].lower()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_placeholder_user_skipped_silently(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -90,7 +90,7 @@ class TestResolveSlackUser:mock_client.chat_postMessage.assert_not_called()mock_client.chat_postEphemeral.assert_not_called()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_no_org_membership(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -106,7 +106,7 @@ class TestResolveSlackUser:assert call_kwargs["thread_ts"] == "1234.5678"assert "[email protected]" in call_kwargs["text"]- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.UserPermissions")def test_no_team_access(self, mock_permissions_class, mock_webclient_class):mock_client = MagicMock()@@ -124,7 +124,7 @@ class TestResolveSlackUser:call_text = mock_client.chat_postEphemeral.call_args.kwargs["text"]assert "access" in call_text.lower()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_uses_db_cached_slack_profile(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -154,7 +154,7 @@ class TestResolveSlackUser:pytest.param(lambda: None, id="null_refreshed_at"),],)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_refetches_when_profile_is_stale(self, mock_webclient_class, stale_refreshed_at):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -187,7 +187,7 @@ class TestResolveSlackUser:assert profile.is_admin is Trueassert profile.refreshed_at is not None and profile.refreshed_at >= before- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_persists_slack_profile_after_lookup(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -227,7 +227,7 @@ class TestLookupSlackUserIdByEmail:sensitive_config={"access_token": "xoxb-test"},)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_uses_db_cached_profile(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -245,7 +245,7 @@ class TestLookupSlackUserIdByEmail:assert slack_user_id == "U123"mock_client.users_lookupByEmail.assert_not_called()- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_lookup_by_email_api(self, mock_webclient_class):mock_client = MagicMock()mock_webclient_class.return_value = mock_client@@ -272,7 +272,7 @@ class TestLookupSlackUserIdByEmail:pytest.param(lambda: None, id="null_refreshed_at"),],)- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")def test_refetches_email_lookup_when_profile_is_stale(self, mock_webclient_class, stale_refreshed_at):mock_client = MagicMock()mock_webclient_class.return_value = mock_clientdiff --git a/products/slack_app/backend/tests/test_zz_resolve_slack_user_with_link_no_access.py b/products/slack_app/backend/tests/test_zz_resolve_slack_user_with_link_no_access.pyindex a992c848495a..dcae4928c9b6 100644--- a/products/slack_app/backend/tests/test_zz_resolve_slack_user_with_link_no_access.py+++ b/products/slack_app/backend/tests/test_zz_resolve_slack_user_with_link_no_access.py@@ -24,7 +24,7 @@ from products.slack_app.backend.tests.conftest import SLACK_USER_IDclass TestResolveSlackUserAccessDenied:- @patch("posthog.models.integration.WebClient")+ @patch("posthog.models.integration.slack.WebClient")@patch("products.slack_app.backend.api.UserPermissions")@patch("products.slack_app.backend.api.is_slack_app_oauth_enabled")def test_flag_on_with_link_but_no_team_access_returns_none(diff --git a/products/slack_app/backend/tests/views/test_slack_user_link.py b/products/slack_app/backend/tests/views/test_slack_user_link.pyindex d5478fcfe471..e3874a80b9c3 100644--- a/products/slack_app/backend/tests/views/test_slack_user_link.py+++ b/products/slack_app/backend/tests/views/test_slack_user_link.py@@ -174,7 +174,7 @@ class TestCallbackView:with (patch("products.slack_app.backend.views.slack_user_link.is_slack_app_oauth_enabled", return_value=True),patch("products.slack_app.backend.views.slack_user_link.exchange_code", return_value=self._identity()),- patch("posthog.models.integration.WebClient"),+ patch("posthog.models.integration.slack.WebClient"),):response = client.get(f"/complete/slack-link/?code=abc&state={state}")diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.pyindex 04f87ecc8aa7..128d546462a3 100644--- a/products/stamphog/backend/tests/fakes.py+++ b/products/stamphog/backend/tests/fakes.py@@ -418,7 +418,7 @@ class FakeSlackClient:class FakeSlackIntegration:- """Stand-in for ``posthog.models.integration.SlackIntegration``.+ """Stand-in for ``posthog.models.integration.slack.SlackIntegration``.Class-level state is shared across every instance a run constructs, so a test can read``posted_messages`` and script ``workspace_channels`` regardless of which module built thediff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.pyindex 35225a991631..fe9a48dd4513 100644--- a/products/tasks/backend/tests/test_channels_api.py+++ b/products/tasks/backend/tests/test_channels_api.py@@ -85,7 +85,7 @@ class ChannelsAPITestCase(TestCase):delete = self.client.delete(f"{self._channels_url()}{personal.id}/")self.assertEqual(delete.status_code, status.HTTP_403_FORBIDDEN)- @patch("posthog.models.integration.GitHubIntegration.list_all_cached_repositories")+ @patch("posthog.models.integration.github.GitHubIntegration.list_all_cached_repositories")def test_cannot_configure_someone_elses_personal_channel_repositories(self, list_repositories):list_repositories.return_value = [{"full_name": "posthog/posthog"}]integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})@@ -140,7 +140,7 @@ class ChannelsAPITestCase(TestCase):self.assertIsNone(channel.github_integration_id)self.assertEqual(channel.repositories, [])- @patch("posthog.models.integration.GitHubIntegration.list_all_cached_repositories")+ @patch("posthog.models.integration.github.GitHubIntegration.list_all_cached_repositories")def test_new_tasks_inherit_channel_repositories(self, list_repositories):list_repositories.return_value = [{"full_name": "posthog/posthog"},@@ -167,7 +167,7 @@ class ChannelsAPITestCase(TestCase):self.assertEqual(created.json()["repositories"], ["posthog/posthog", "posthog/posthog-js"])self.assertEqual(created.json()["github_integration"], integration.id)- @patch("posthog.models.integration.GitHubIntegration.list_all_cached_repositories")+ @patch("posthog.models.integration.github.GitHubIntegration.list_all_cached_repositories")def test_project_member_can_configure_or_rename_public_channel(self, list_repositories):list_repositories.return_value = [{"full_name": "posthog/posthog"}]integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})