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
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from __future__ import annotations

from typing import Any
from typing import Any, TypedDict

import sentry_sdk
from django.core.exceptions import ValidationError
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, status
from rest_framework.request import Request
from rest_framework.response import Response
Expand All @@ -12,6 +13,10 @@
from sentry.api.api_owners import ApiOwner
from sentry.api.api_publish_status import ApiPublishStatus
from sentry.api.base import control_silo_endpoint
from sentry.apidocs.constants import RESPONSE_BAD_REQUEST, RESPONSE_FORBIDDEN, RESPONSE_NOT_FOUND
from sentry.apidocs.parameters import GlobalParams
from sentry.apidocs.response_types import ValidationErrorResponse, as_validation_errors
from sentry.apidocs.utils import inline_sentry_response_serializer
from sentry.integrations.api.bases.organization_integrations import (
OrganizationIntegrationBaseEndpoint,
)
Expand All @@ -24,28 +29,58 @@
from sentry.integrations.msteams.utils import find_channel_id as msteams_find_channel_id
from sentry.integrations.slack.utils.channel import get_channel_id
from sentry.integrations.types import IntegrationProviderSlug
from sentry.organizations.services.organization import RpcUserOrganizationContext
from sentry.shared_integrations.exceptions import ApiError


class ChannelValidateSerializer(serializers.Serializer):
channel = serializers.CharField(required=True, allow_blank=False)


class DetailOptionalResponse(TypedDict, total=False):
"""Use a total=False base because postponed NotRequired annotations become required in OpenAPI."""

detail: str


class IntegrationChannelValidationResponse(DetailOptionalResponse):
valid: bool


@extend_schema(tags=["Integration"])
@control_silo_endpoint
class OrganizationIntegrationChannelValidateEndpoint(OrganizationIntegrationBaseEndpoint):
publish_status = {"GET": ApiPublishStatus.PRIVATE}
publish_status = {"GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL}
owner = ApiOwner.TELEMETRY_EXPERIENCE

class ChannelValidateSerializer(serializers.Serializer):
channel = serializers.CharField(required=True, allow_blank=False)

@extend_schema(
operation_id="validateOrganizationIntegrationChannel",
summary="Validate a Messaging Channel for an Integration",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
GlobalParams.INTEGRATION_ID,
ChannelValidateSerializer,
],
responses={
200: inline_sentry_response_serializer(
"IntegrationChannelValidationResponse", IntegrationChannelValidationResponse
),
400: RESPONSE_BAD_REQUEST,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def get(
self,
request: Request,
organization_context: Any,
organization_context: RpcUserOrganizationContext,
integration_id: int,
**kwargs: Any,
) -> Response:
) -> Response[IntegrationChannelValidationResponse] | Response[ValidationErrorResponse]:
"""Validate whether a channel exists for the given integration."""
serializer = self.ChannelValidateSerializer(data=request.GET)
serializer = ChannelValidateSerializer(data=request.GET)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response(as_validation_errors(serializer), status=status.HTTP_400_BAD_REQUEST)

channel = serializer.validated_data["channel"].strip()
integration = self.get_integration(organization_context.organization.id, integration_id)
Expand All @@ -55,11 +90,13 @@ def get(
try:
if provider == IntegrationProviderSlug.SLACK.value:
channel_data = get_channel_id(integration=integration, channel_name=channel)
return Response({"valid": bool(channel_data.channel_id)})
return Response(
IntegrationChannelValidationResponse(valid=bool(channel_data.channel_id))
)

elif provider == IntegrationProviderSlug.MSTEAMS.value:
channel_id = msteams_find_channel_id(integration=integration, name=channel)
return Response({"valid": bool(channel_id)})
return Response(IntegrationChannelValidationResponse(valid=bool(channel_id)))

elif provider == IntegrationProviderSlug.DISCORD.value:
channel_id = (
Expand All @@ -70,16 +107,18 @@ def get(
guild_id=str(integration.external_id),
guild_name=integration.name,
)
return Response({"valid": True})
return Response(IntegrationChannelValidationResponse(valid=True))

return Response(
{"valid": False, "detail": "Unsupported provider"},
IntegrationChannelValidationResponse(valid=False, detail="Unsupported provider"),
status=status.HTTP_400_BAD_REQUEST,
)

except (SlackApiError, ApiError, ValidationError):
return Response({"valid": False})
return Response(IntegrationChannelValidationResponse(valid=False))
except Exception as e:
sentry_sdk.capture_message(f"Unexpected {provider} channel validation error")
sentry_sdk.capture_exception(e)
return Response({"valid": False, "detail": "Unexpected error"})
return Response(
IntegrationChannelValidationResponse(valid=False, detail="Unexpected error")
)
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
from __future__ import annotations

import logging
from typing import Any
from typing import Any, TypedDict

from drf_spectacular.utils import extend_schema
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 control_silo_endpoint
from sentry.apidocs.constants import RESPONSE_BAD_REQUEST, RESPONSE_FORBIDDEN, RESPONSE_NOT_FOUND
from sentry.apidocs.parameters import GlobalParams
from sentry.apidocs.response_types import DetailResponse
from sentry.apidocs.utils import inline_sentry_response_serializer
from sentry.integrations.api.bases.organization_integrations import (
OrganizationIntegrationBaseEndpoint,
)
Expand All @@ -23,7 +28,22 @@
logger = logging.getLogger(__name__)


def _slack_list_channels(*, integration_id: int) -> list[dict[str, Any]]:
class IntegrationChannel(TypedDict):
id: str
name: str
display: str
type: str


class IntegrationChannelsResponseOptional(TypedDict, total=False):
warning: str


class IntegrationChannelsResponse(IntegrationChannelsResponseOptional):
results: list[IntegrationChannel]


def _slack_list_channels(*, integration_id: int) -> list[IntegrationChannel]:
"""
List Slack channels for a given integration.

Expand Down Expand Up @@ -56,7 +76,7 @@ def _slack_list_channels(*, integration_id: int) -> list[dict[str, Any]]:
)
return []

results: list[dict[str, Any]] = []
results: list[IntegrationChannel] = []
for ch in raw_channels:
if not isinstance(ch, dict):
continue
Expand All @@ -70,18 +90,18 @@ def _slack_list_channels(*, integration_id: int) -> list[dict[str, Any]]:
name_str = str(ch_name)

results.append(
{
"id": str(ch_id),
"name": name_str,
"display": f"#{name_str}",
"type": "private" if is_private else "public",
}
IntegrationChannel(
id=str(ch_id),
name=name_str,
display=f"#{name_str}",
type="private" if is_private else "public",
)
)

return results


def _discord_list_channels(*, guild_id: str) -> list[dict[str, Any]]:
def _discord_list_channels(*, guild_id: str) -> list[IntegrationChannel]:
"""
List Discord channels for a given guild that can receive messages.

Expand Down Expand Up @@ -119,7 +139,7 @@ def _discord_list_channels(*, guild_id: str) -> list[dict[str, Any]]:
return []

selectable_types = set(DISCORD_CHANNEL_TYPES.keys())
results: list[dict[str, Any]] = []
results: list[IntegrationChannel] = []

for item in raw_resp:
if not isinstance(item, dict):
Expand All @@ -135,20 +155,20 @@ def _discord_list_channels(*, guild_id: str) -> list[dict[str, Any]]:
continue

results.append(
{
"id": str(ch_id),
"name": str(ch_name),
"display": f"#{ch_name}",
"type": DISCORD_CHANNEL_TYPES.get(ch_type, "unknown"),
}
IntegrationChannel(
id=str(ch_id),
name=str(ch_name),
display=f"#{ch_name}",
type=DISCORD_CHANNEL_TYPES.get(ch_type, "unknown"),
)
)

return results


def _msteams_list_channels(
*, integration: Integration | RpcIntegration, team_id: str
) -> list[dict[str, Any]]:
) -> list[IntegrationChannel]:
"""
List Microsoft Teams channels for a given team.

Expand Down Expand Up @@ -187,7 +207,7 @@ def _msteams_list_channels(
)
return []

results: list[dict[str, Any]] = []
results: list[IntegrationChannel] = []
for item in raw_channels:
if not isinstance(item, dict):
continue
Expand All @@ -202,31 +222,45 @@ def _msteams_list_channels(
ch_type = str(item.get("type") or "standard")

results.append(
{
"id": str(ch_id),
"name": name,
"display": name,
"type": ch_type, # "standard", "private" or "shared"
}
IntegrationChannel(
id=str(ch_id),
name=name,
display=name,
type=ch_type, # "standard", "private" or "shared"
)
)

return results


@extend_schema(tags=["Integration"])
@control_silo_endpoint
class OrganizationIntegrationChannelsEndpoint(OrganizationIntegrationBaseEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL,
}
owner = ApiOwner.TELEMETRY_EXPERIENCE

@extend_schema(
operation_id="listOrganizationIntegrationChannels",
summary="List Messaging Channels for an Integration",
parameters=[GlobalParams.ORG_ID_OR_SLUG, GlobalParams.INTEGRATION_ID],
responses={
200: inline_sentry_response_serializer(
"IntegrationChannelsResponse", IntegrationChannelsResponse
),
400: RESPONSE_BAD_REQUEST,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def get(
self,
request: Request,
organization_context: RpcUserOrganizationContext,
integration_id: int,
**kwargs: Any,
) -> Response:
) -> Response[IntegrationChannelsResponse] | Response[DetailResponse]:
"""
List all messaging channels for an integration.
"""
Expand All @@ -246,12 +280,12 @@ def get(
)
case _:
return self.respond(
{
"results": [],
"warning": f"Channel listing not supported for provider '{integration.provider}'.",
}
IntegrationChannelsResponse(
results=[],
warning=f"Channel listing not supported for provider '{integration.provider}'.",
)
)
except ApiError as e:
return self.respond({"detail": str(e)}, status=400)

return self.respond({"results": results})
return self.respond(IntegrationChannelsResponse(results=results))
16 changes: 16 additions & 0 deletions tests/sentry/seer/endpoints/test_organization_agent_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,13 @@ def _resource(self, name: str) -> Any:
provider="example",
name="Matrix integration",
)
elif name == "channel_integration":
resource = self.create_integration(
organization=self.org,
external_id=f"matrix-slack-{uuid4()}",
provider="slack",
name="Matrix Slack integration",
)
elif name == "codeowners_integration":
resource = self.create_integration(
organization=self.org,
Expand Down Expand Up @@ -1135,6 +1142,8 @@ def _path_value(
if placeholder == "issue_id":
return str(self._resource("group").id)
if placeholder == "integration_id":
if endpoint.endpoint_name == "OrganizationIntegrationChannelValidateEndpoint":
return str(self._resource("channel_integration").id)
return str(self._resource("integration").id)
if placeholder == "data_forwarder_id":
return str(self._resource("data_forwarder").id)
Expand Down Expand Up @@ -1235,6 +1244,8 @@ def _path(self, endpoint: PublicGetEndpoint | PublicMutationEndpoint) -> str:
return path

def _query_params(self, endpoint: PublicGetEndpoint | PublicMutationEndpoint) -> dict[str, Any]:
if endpoint.endpoint_name == "OrganizationIntegrationChannelValidateEndpoint":
return {"channel": "permission-matrix"}
if endpoint.endpoint_name == "OrganizationEventsEndpoint":
return {
"field": ["id", "project"],
Expand Down Expand Up @@ -1980,6 +1991,11 @@ def _assert_public_get_authentication(
"sentry.api.endpoints.organization_trace_item_stats.Spans.run_table_query",
return_value={"data": []},
)
elif endpoint.endpoint_name == "OrganizationIntegrationChannelValidateEndpoint":
downstream_scope = patch(
"sentry.integrations.api.endpoints.organization_integration_channel_validate.get_channel_id",
return_value=SimpleNamespace(channel_id="C123"),
)
elif endpoint.endpoint_name in {
"OrganizationProfilingChunksEndpoint",
"OrganizationProfilingFlamegraphEndpoint",
Expand Down
Loading