Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 13 additions & 16 deletions posthog/api/integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.auth import SessionAuthentication
from posthog.domain_connect import discover_domain_connect, extract_root_domain_and_host, get_available_providers
from posthog.exceptions_capture import capture_exception
from posthog.models import User
Expand Down Expand Up @@ -608,18 +608,6 @@ def perform_destroy(self, instance) -> None:

super().perform_destroy(instance)

def safely_get_queryset(self, queryset):
if isinstance(self.request.successful_authenticator, PersonalAPIKeyAuthentication) or isinstance(
self.request.successful_authenticator, OAuthAccessTokenAuthentication
):
# GitHub and Slack integrations are exposed via API-key / OAuth. The serializer
# only returns id, kind, config, errors, and display metadata — access tokens stay
# in sensitive_config and are never serialized. The channels action's kind guard
# (see `channels` below) is the actual gate against running Slack-only code on a
# non-Slack integration.
return defer_repository_cache_fields(queryset.filter(kind__in=["github", *SLACK_INTEGRATION_KINDS]))
return queryset

@action(methods=["GET"], detail=False)
Comment thread
MarconLP marked this conversation as resolved.
Resolved
Comment thread
MarconLP marked this conversation as resolved.
Resolved
def authorize(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:
kind = request.GET.get("kind")
Expand Down Expand Up @@ -902,7 +890,10 @@ def github_repos(self, request: Request, *args: Any, **kwargs: Any) -> Response:
limit = query_serializer.validated_data["limit"]
offset = query_serializer.validated_data["offset"]

github = GitHubIntegration(self.get_object())
instance = self.get_object()
if instance.kind != "github":
raise ValidationError("github_repos endpoint is only supported for GitHub integrations")
github = GitHubIntegration(instance)
repositories, has_more = github.list_cached_repositories(search=search, limit=limit, offset=offset)

return Response({"repositories": repositories, "has_more": has_more})
Expand Down Expand Up @@ -1062,7 +1053,10 @@ def github_oauth_authorize(self, request: Request, *args: Any, **kwargs: Any) ->
@extend_schema(request=None, responses={200: GitHubReposRefreshResponseSerializer})
@action(methods=["POST"], detail=True, url_path="github_repos/refresh")
def refresh_github_repos(self, request: Request, *args: Any, **kwargs: Any) -> Response:
github = GitHubIntegration(self.get_object())
instance = self.get_object()
if instance.kind != "github":
raise ValidationError("refresh_github_repos endpoint is only supported for GitHub integrations")
github = GitHubIntegration(instance)
repositories = github.sync_repository_cache(
min_refresh_interval_seconds=GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS
)
Expand All @@ -1085,7 +1079,10 @@ def github_branches(self, request: Request, *args: Any, **kwargs: Any) -> Respon

validate_github_repository_name(repo)

github = GitHubIntegration(self.get_object())
instance = self.get_object()
if instance.kind != "github":
raise ValidationError("github_branches endpoint is only supported for GitHub integrations")
github = GitHubIntegration(instance)
branches, default_branch, has_more = github.list_cached_branches(
repo,
search=search,
Expand Down
76 changes: 32 additions & 44 deletions posthog/api/test/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -568,47 +568,10 @@ def test_list_integrations_with_scope_succeeds(self, client: HttpClient):
HTTP_AUTHORIZATION=f"Bearer {key_value}",
)

assert response.status_code == status.HTTP_200_OK
assert len(response.json()["results"]) == 1
assert response.json()["results"][0]["kind"] == "github"

@patch(
"posthog.models.integration.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_list_integrations_shows_github_and_slack_for_api_keys(self, _mock_settings, client: HttpClient):
Integration.objects.create(
team=self.team,
kind="slack",
integration_id="T_LIST",
config={"authed_user": {"id": "test_user_id"}, "team": {"name": "Test Workspace"}},
sensitive_config={"access_token": "test-token"},
created_by=self.user,
)

key_value = "test_key_123"
PersonalAPIKey.objects.create(
label="Test Key",
user=self.user,
secure_value=hash_key_value(key_value),
scopes=["integration:read"],
)

response = client.get(
f"/api/environments/{self.team.pk}/integrations/",
HTTP_AUTHORIZATION=f"Bearer {key_value}",
)

assert response.status_code == status.HTTP_200_OK
results = response.json()["results"]
kinds = {integration["kind"] for integration in results}
assert kinds == {"github", "slack"}
# twilio_integration is created in the fixture but should remain hidden from API-key callers.
assert "twilio" not in kinds
assert kinds == {"github", "twilio"}
# Sensitive credentials never round-trip via the list serializer.
assert all("sensitive_config" not in integration for integration in results)

Expand All @@ -629,7 +592,7 @@ def test_retrieve_github_integration_with_scope_succeeds(self, client: HttpClien
assert response.status_code == status.HTTP_200_OK
assert response.json()["kind"] == "github"

def test_retrieve_non_github_integration_with_api_key_fails(self, client: HttpClient):
def test_retrieve_non_github_integration_with_api_key_succeeds(self, client: HttpClient):
key_value = "test_key_123"
PersonalAPIKey.objects.create(
label="Test Key",
Expand All @@ -643,7 +606,8 @@ def test_retrieve_non_github_integration_with_api_key_fails(self, client: HttpCl
HTTP_AUTHORIZATION=f"Bearer {key_value}",
)

assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.status_code == status.HTTP_200_OK
assert response.json()["kind"] == "twilio"

@patch(
"posthog.models.integration.get_instance_settings",
Expand Down Expand Up @@ -682,6 +646,31 @@ def test_retrieve_slack_integration_with_scope_succeeds(self, _mock_settings, cl
# Sensitive credentials never round-trip via the retrieve serializer.
assert "sensitive_config" not in body

@pytest.mark.parametrize(
"url_suffix,method",
[
("github_repos/", "get"),
("github_repos/refresh/", "post"),
("github_branches/?repo=org/repo", "get"),
],
)
def test_github_actions_on_non_github_integration_return_400(self, url_suffix, method, client: HttpClient):
key_value = "test_key_non_github"
PersonalAPIKey.objects.create(
label="Test Key",
user=self.user,
secure_value=hash_key_value(key_value),
scopes=["integration:read", "integration:write"],
)

response = getattr(client, method)(
f"/api/environments/{self.team.pk}/integrations/{self.twilio_integration.id}/{url_suffix}",
HTTP_AUTHORIZATION=f"Bearer {key_value}",
)

assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "GitHub" in response.json()["detail"]

@patch("posthog.models.integration.GitHubIntegration.list_cached_repositories")
def test_github_repos_with_scope_succeeds(self, mock_list_repos, client: HttpClient):
mock_list_repos.return_value = (
Expand Down Expand Up @@ -918,11 +907,10 @@ def test_github_repos_without_scope_fails(self, client: HttpClient):
("slack", "integration:read", status.HTTP_200_OK, None),
("slack-posthog-code", "integration:read", status.HTTP_200_OK, None),
("slack", "feature_flag:read", status.HTTP_403_FORBIDDEN, "integration:read"),
# GitHub passes the queryset filter (it's a read-allowed kind) but the channels
# action's kind guard rejects it with a 400 before SlackIntegration is constructed.
# GitHub and Twilio resolve via the queryset, but the channels action's kind
# guard rejects them with a 400 before SlackIntegration is constructed.
("github", "integration:read", status.HTTP_400_BAD_REQUEST, "Slack"),
# Twilio is filtered out of the queryset entirely for API-key callers — 404.
("twilio", "integration:read", status.HTTP_404_NOT_FOUND, None),
("twilio", "integration:read", status.HTTP_400_BAD_REQUEST, "Slack"),
],
)
@patch("posthog.api.integration.SlackIntegration")
Expand Down
4 changes: 2 additions & 2 deletions products/integrations/mcp/tools.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@ tools:
description: >
List all third-party integrations configured in the current project. Returns each integration's type (kind),
display name, non-sensitive configuration, error status, and creation metadata. Common kinds include slack,
github, hubspot, salesforce, and various ad platforms. When authenticated via personal API key or OAuth,
only GitHub and Slack integrations are returned (other kinds remain session-only).
github, hubspot, salesforce, and various ad platforms. Sensitive credentials (access tokens, secrets) are
never serialized.
integrations-twilio-phone-numbers-retrieve:
operation: integrations_twilio_phone_numbers_retrieve
enabled: false
Expand Down
2 changes: 1 addition & 1 deletion services/mcp/schema/generated-tool-definitions.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion services/mcp/schema/tool-definitions-all.json
Original file line number Diff line number Diff line change
Expand Up @@ -2426,7 +2426,7 @@
}
},
"integrations-list": {
"description": "List all third-party integrations configured in the current project. Returns each integration's type (kind), display name, non-sensitive configuration, error status, and creation metadata. Common kinds include slack, github, hubspot, salesforce, and various ad platforms. When authenticated via personal API key or OAuth, only GitHub and Slack integrations are returned (other kinds remain session-only).",
"description": "List all third-party integrations configured in the current project. Returns each integration's type (kind), display name, non-sensitive configuration, error status, and creation metadata. Common kinds include slack, github, hubspot, salesforce, and various ad platforms. Sensitive credentials (access tokens, secrets) are never serialized.",
"category": "Integrations",
"feature": "integrations",
"summary": "List integrations",
Expand Down
Loading