Repository navigation
feat(slack): Add a team link context API #130554
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sentry-junior
wants to merge
2
commits into
ref/slack-extract-team-linking
from
feat/slack-link-team-context-api
+226
−1
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
87 changes: 87 additions & 0 deletions
87
src/sentry/integrations/slack/endpoints/link_team_context.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import TypedDict | ||
|
|
||
| from django.utils.decorators import method_decorator | ||
| from django.views.decorators.cache import never_cache | ||
| from rest_framework.request import Request | ||
| from rest_framework.response import Response | ||
|
|
||
| from sentry.api.api_owners import ApiOwner | ||
| from sentry.api.api_publish_status import ApiPublishStatus | ||
| from sentry.api.base import Endpoint, control_silo_endpoint | ||
| from sentry.api.permissions import SentryIsAuthenticated | ||
| from sentry.api.serializers import serialize | ||
| from sentry.api.serializers.models.organization import ( | ||
| ControlSiloOrganizationMappingSerializer, | ||
| ControlSiloOrganizationMappingSerializerResponse, | ||
| ) | ||
| from sentry.auth.principal import require_user | ||
| from sentry.constants import ObjectStatus | ||
| from sentry.integrations.models.integration import Integration | ||
| from sentry.integrations.models.organization_integration import OrganizationIntegration | ||
| from sentry.integrations.slack.team_linking import ( | ||
| INVALID_LINK_MESSAGE, | ||
| InvalidTeamLinkParams, | ||
| TeamLinkParams, | ||
| ) | ||
| from sentry.models.organization import OrganizationStatus | ||
| from sentry.models.organizationmapping import OrganizationMapping | ||
| from sentry.models.organizationmembermapping import OrganizationMemberMapping | ||
| from sentry.types.cell import find_all_cell_names | ||
|
|
||
|
|
||
| class SlackLinkTeamContextResponse(TypedDict): | ||
| channelName: str | ||
| channelUrl: str | ||
| organizations: list[ControlSiloOrganizationMappingSerializerResponse] | ||
|
|
||
|
|
||
| @control_silo_endpoint | ||
| @method_decorator(never_cache, name="dispatch") | ||
| class SlackLinkTeamContextEndpoint(Endpoint): | ||
| owner = ApiOwner.MESSAGING_INTEGRATIONS | ||
| publish_status = {"GET": ApiPublishStatus.PRIVATE} | ||
| permission_classes = (SentryIsAuthenticated,) | ||
|
|
||
| def get(self, request: Request, signed_params: str) -> Response: | ||
| """ | ||
| Describe a `/sentry link team` request: the Slack channel being linked, | ||
| with a deep link back to it, and the user's organizations, across every | ||
| cell, that have the Slack workspace installed. | ||
| """ | ||
| try: | ||
| params = TeamLinkParams.from_signed(signed_params) | ||
| except InvalidTeamLinkParams: | ||
| return Response({"detail": INVALID_LINK_MESSAGE}, status=400) | ||
|
|
||
| integration = Integration.objects.filter( | ||
| id=params.integration_id, status=ObjectStatus.ACTIVE | ||
| ).first() | ||
| if integration is None: | ||
| return Response({"detail": "The Slack workspace is no longer installed."}, status=404) | ||
|
|
||
| installed_org_ids = OrganizationIntegration.objects.filter( | ||
| integration_id=params.integration_id, status=ObjectStatus.ACTIVE | ||
| ).values("organization_id") | ||
| member_org_ids = OrganizationMemberMapping.objects.filter( | ||
| user_id=require_user(request).id, organization_id__in=installed_org_ids | ||
| ).values("organization_id") | ||
| # Serializing an org in a cell this deploy doesn't know about raises, | ||
| # so skip those instead of failing the whole page. | ||
| organizations = OrganizationMapping.objects.filter( | ||
| organization_id__in=member_org_ids, | ||
| status=OrganizationStatus.ACTIVE, | ||
| cell_name__in=list(find_all_cell_names()), | ||
| ).order_by("name") | ||
|
|
||
| response: SlackLinkTeamContextResponse = { | ||
| "channelName": params.channel_name, | ||
| "channelUrl": f"slack://channel?team={integration.external_id}&id={params.channel_id}", | ||
| "organizations": serialize( | ||
| list(organizations), | ||
| request.user, | ||
| serializer=ControlSiloOrganizationMappingSerializer(), | ||
| ), | ||
| } | ||
| return Response(response) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
93 changes: 93 additions & 0 deletions
93
tests/sentry/integrations/slack/endpoints/test_link_team_context.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| from datetime import timedelta | ||
|
|
||
| from django.utils import timezone | ||
|
|
||
| from sentry.constants import ObjectStatus | ||
| from sentry.integrations.slack.views import SALT | ||
| from sentry.models.organizationmapping import OrganizationMapping | ||
| from sentry.testutils.cases import APITestCase | ||
| from sentry.testutils.helpers.datetime import freeze_time | ||
| from sentry.testutils.silo import control_silo_test | ||
| from sentry.utils.signing import sign | ||
|
|
||
|
|
||
| @control_silo_test | ||
| class SlackLinkTeamContextTest(APITestCase): | ||
| endpoint = "sentry-api-0-slack-link-team-context" | ||
|
|
||
| def setUp(self) -> None: | ||
| super().setUp() | ||
| self.login_as(self.user) | ||
| self.integration = self.create_slack_integration(self.organization, external_id="TXXXXXXX1") | ||
|
|
||
| def sign_params(self, **overrides: object) -> str: | ||
| params: dict[str, object] = { | ||
| "integration_id": self.integration.id, | ||
| "slack_id": "UXXXXXXX1", | ||
| "channel_id": "CXXXXXXX1", | ||
| "channel_name": "alerts", | ||
| "response_url": "https://hooks.slack.com/commands/response", | ||
| **overrides, | ||
| } | ||
| return sign(salt=SALT, **params) | ||
|
|
||
| def test_lists_member_organizations_with_the_workspace(self) -> None: | ||
| other_org = self.create_organization(name="Another Org", owner=self.user) | ||
| self.integration.add_organization(other_org) | ||
| self.create_organization(name="No Slack", owner=self.user) | ||
| foreign_org = self.create_organization(name="Not A Member") | ||
| self.integration.add_organization(foreign_org) | ||
|
|
||
| response = self.get_success_response(self.sign_params()) | ||
|
|
||
| assert response.data["channelName"] == "alerts" | ||
| assert response.data["channelUrl"] == "slack://channel?team=TXXXXXXX1&id=CXXXXXXX1" | ||
| assert [org["slug"] for org in response.data["organizations"]] == [ | ||
| other_org.slug, | ||
| self.organization.slug, | ||
| ] | ||
| assert response.data["organizations"][0]["links"]["regionUrl"] | ||
|
|
||
| def test_omits_organizations_with_a_disabled_installation(self) -> None: | ||
| self.integration.organizationintegration_set.update(status=ObjectStatus.DISABLED) | ||
|
|
||
| response = self.get_success_response(self.sign_params()) | ||
|
|
||
| assert response.data["organizations"] == [] | ||
|
|
||
| def test_omits_organizations_in_unknown_cells(self) -> None: | ||
| other_org = self.create_organization(name="Another Org", owner=self.user) | ||
| self.integration.add_organization(other_org) | ||
| OrganizationMapping.objects.filter(organization_id=other_org.id).update( | ||
| cell_name="unknown-cell" | ||
| ) | ||
|
|
||
| response = self.get_success_response(self.sign_params()) | ||
|
|
||
| assert [org["slug"] for org in response.data["organizations"]] == [self.organization.slug] | ||
|
|
||
| def test_rejects_a_tampered_link(self) -> None: | ||
| response = self.get_error_response(self.sign_params() + "x", status_code=400) | ||
|
|
||
| assert "invalid or has expired" in response.data["detail"] | ||
|
|
||
| def test_rejects_an_expired_link(self) -> None: | ||
| signed_params = self.sign_params() | ||
|
|
||
| with freeze_time(timezone.now() + timedelta(days=3)): | ||
| self.get_error_response(signed_params, status_code=400) | ||
|
|
||
| def test_rejects_a_link_missing_the_channel(self) -> None: | ||
| signed_params = sign(salt=SALT, integration_id=self.integration.id, slack_id="UXXXXXXX1") | ||
|
|
||
| self.get_error_response(signed_params, status_code=400) | ||
|
|
||
| def test_rejects_an_uninstalled_workspace(self) -> None: | ||
| self.integration.update(status=ObjectStatus.DISABLED) | ||
|
|
||
| self.get_error_response(self.sign_params(), status_code=404) | ||
|
|
||
| def test_requires_authentication(self) -> None: | ||
| self.client.logout() | ||
|
|
||
| self.get_error_response(self.sign_params(), status_code=401) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.