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
1 change: 1 addition & 0 deletions frontend/src/lib/scopes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const API_SCOPES: APIScope[] = [
{ key: 'group', objectPlural: 'groups' },
{ key: 'hog_function', objectPlural: 'hog functions' },
{ key: 'insight', objectPlural: 'insights' },
{ key: 'integration', disabledActions: ['write'], objectPlural: 'integrations' },
{ key: 'notebook', objectPlural: 'notebooks' },
{ key: 'organization', disabledWhenProjectScoped: true, objectPlural: 'organizations' },
{
Expand Down
1 change: 1 addition & 0 deletions frontend/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4506,6 +4506,7 @@ export type APIScopeObject =
| 'group'
| 'hog_function'
| 'insight'
| 'integration'
| 'notebook'
| 'organization'
| 'organization_member'
Expand Down
9 changes: 8 additions & 1 deletion posthog/api/integration.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add some permissions tests here?

Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
from posthog.auth import PersonalAPIKeyAuthentication
from posthog.models.instance_setting import get_instance_setting
from posthog.models.integration import (
ClickUpIntegration,
Expand Down Expand Up @@ -154,10 +155,16 @@ class IntegrationViewSet(
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
scope_object = "INTERNAL"
scope_object = "integration"
scope_object_read_actions = ["list", "retrieve", "github_repos"]
queryset = Integration.objects.all()
serializer_class = IntegrationSerializer

def safely_get_queryset(self, queryset):
if isinstance(self.request.successful_authenticator, PersonalAPIKeyAuthentication):
return queryset.filter(kind="github")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we want to only return github integrations?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know how diligent people have been when separating config and sensitive_config on the Organization model for different integrations, so just reducing blast radius by only exposing our use case

return queryset

@action(methods=["GET"], detail=False)
def authorize(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:
kind = request.GET.get("kind")
Expand Down
1 change: 1 addition & 0 deletions posthog/api/test/__snapshots__/test_api_docs.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
'/home/runner/work/posthog/posthog/posthog/api/insight.py: Warning [EnterpriseInsightsViewSet > InsightSerializer]: unable to resolve type hint for function "get_result". Consider using a type hint or @extend_schema_field. Defaulting to string.',
'/home/runner/work/posthog/posthog/posthog/api/insight.py: Warning [EnterpriseInsightsViewSet > InsightSerializer]: unable to resolve type hint for function "get_timezone". Consider using a type hint or @extend_schema_field. Defaulting to string.',
'/home/runner/work/posthog/posthog/posthog/api/insight.py: Warning [EnterpriseInsightsViewSet > InsightSerializer]: unable to resolve type hint for function "get_types". Consider using a type hint or @extend_schema_field. Defaulting to string.',
'/home/runner/work/posthog/posthog/posthog/api/integration.py: Warning [IntegrationViewSet]: could not derive type of path parameter "project_id" because model "posthog.models.integration.Integration" contained no such field. Consider annotating parameter with @extend_schema. Defaulting to "string".',
"/home/runner/work/posthog/posthog/posthog/api/named_query.py: Error [NamedQueryViewSet]: exception raised while getting serializer. Hint: Is get_serializer_class() returning None or is get_queryset() not working without a request? Ignoring the view for now. (Exception: 'NoneType' object is not callable)",
'/home/runner/work/posthog/posthog/posthog/api/named_query.py: Warning [NamedQueryViewSet]: could not derive type of path parameter "project_id" because model "posthog.models.named_query.NamedQuery" contained no such field. Consider annotating parameter with @extend_schema. Defaulting to "string".',
'/home/runner/work/posthog/posthog/posthog/api/notebook.py: Warning [NotebookViewSet]: could not derive type of path parameter "project_id" because model "posthog.models.notebook.notebook.Notebook" contained no such field. Consider annotating parameter with @extend_schema. Defaulting to "string".',
Expand Down
196 changes: 196 additions & 0 deletions posthog/api/test/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from posthog.api.test.test_team import create_team
from posthog.models.integration import PRIVATE_CHANNEL_WITHOUT_ACCESS, EmailIntegration, Integration, SlackIntegration
from posthog.models.organization import Organization
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.team import Team
from posthog.models.user import User

Expand Down Expand Up @@ -486,3 +487,198 @@ def test_integration_from_config_with_invalid_config(

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


class TestIntegrationAPIKeyAccess:
@pytest.fixture(autouse=True)
def setup_integration(self, db):
self.organization = Organization.objects.create(name="Test Org")
self.team = Team.objects.create(organization=self.organization, name="Test Team")
self.user = User.objects.create_and_join(self.organization, "test@posthog.com", "test")

self.github_integration = Integration.objects.create(
team=self.team,
kind="github",
config={"installation_id": "12345"},
sensitive_config={"access_token": "test-token"},
)

self.twilio_integration = Integration.objects.create(
team=self.team,
kind="twilio",
config={"account_sid": "test_sid"},
sensitive_config={"auth_token": "twilio-token"},
)

def test_list_integrations_without_scope_fails(self, client: HttpClient):
key_value = "test_key_123"
PersonalAPIKey.objects.create(
label="Test Key",
user=self.user,
secure_value=hash_key_value(key_value),
scopes=["feature_flag:read"],
)

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

assert response.status_code == status.HTTP_403_FORBIDDEN
assert "integration:read" in response.json()["detail"]

def test_list_integrations_with_scope_succeeds(self, client: HttpClient):
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
assert len(response.json()["results"]) == 1
assert response.json()["results"][0]["kind"] == "github"

def test_list_integrations_only_shows_github_for_api_keys(self, client: HttpClient):
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"]
assert len(results) == 1
assert results[0]["kind"] == "github"
assert all(integration["kind"] == "github" for integration in results)

def test_retrieve_github_integration_with_scope_succeeds(self, client: HttpClient):
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/{self.github_integration.id}/",
HTTP_AUTHORIZATION=f"Bearer {key_value}",
)

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):
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/{self.twilio_integration.id}/",
HTTP_AUTHORIZATION=f"Bearer {key_value}",
)

assert response.status_code == status.HTTP_404_NOT_FOUND

@patch("posthog.models.integration.GitHubIntegration.list_repositories")
def test_github_repos_with_scope_succeeds(self, mock_list_repos, client: HttpClient):
mock_list_repos.return_value = ["repo1", "repo2"]

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/{self.github_integration.id}/github_repos/",
HTTP_AUTHORIZATION=f"Bearer {key_value}",
)

assert response.status_code == status.HTTP_200_OK
assert response.json()["repositories"] == ["repo1", "repo2"]

def test_github_repos_without_scope_fails(self, client: HttpClient):
key_value = "test_key_123"
PersonalAPIKey.objects.create(
label="Test Key",
user=self.user,
secure_value=hash_key_value(key_value),
scopes=["feature_flag:read"],
)

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

assert response.status_code == status.HTTP_403_FORBIDDEN
assert "integration:read" in response.json()["detail"]

def test_create_integration_with_api_key_fails(self, client: HttpClient):
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.post(
f"/api/environments/{self.team.pk}/integrations/",
{"kind": "github", "config": {"installation_id": "99999"}},
content_type="application/json",
HTTP_AUTHORIZATION=f"Bearer {key_value}",
)

assert response.status_code == status.HTTP_403_FORBIDDEN
assert "integration:write" in response.json()["detail"]

def test_delete_integration_with_api_key_fails(self, client: HttpClient):
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.delete(
f"/api/environments/{self.team.pk}/integrations/{self.github_integration.id}/",
HTTP_AUTHORIZATION=f"Bearer {key_value}",
)

assert response.status_code == status.HTTP_403_FORBIDDEN
assert "integration:write" in response.json()["detail"]

def test_session_auth_shows_all_integrations(self, client: HttpClient):
client.force_login(self.user)

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

assert response.status_code == status.HTTP_200_OK
results = response.json()["results"]
assert len(results) == 2
kinds = [integration["kind"] for integration in results]
assert "github" in kinds
assert "twilio" in kinds
1 change: 1 addition & 0 deletions posthog/scopes.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"group",
"hog_function",
"insight",
"integration",
"link",
"named_query",
"notebook",
Expand Down