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
83 changes: 70 additions & 13 deletions src/sentry/api/endpoints/dsn_lookup.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,44 @@
from typing import Annotated, TypedDict
from urllib.parse import urlparse

from drf_spectacular.utils import OpenApiParameter, 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 cell_silo_endpoint
from sentry.api.bases.organization import OrganizationEndpoint
from sentry.apidocs.constants import (
RESPONSE_BAD_REQUEST,
RESPONSE_FORBIDDEN,
RESPONSE_NOT_FOUND,
RESPONSE_TOO_MANY_REQUESTS,
RESPONSE_UNAUTHORIZED,
)
from sentry.apidocs.descriptions import ApiDescription
from sentry.apidocs.examples.project_examples import ProjectExamples
from sentry.apidocs.parameters import GlobalParams
from sentry.apidocs.response_types import DetailResponse
from sentry.apidocs.utils import inline_sentry_response_serializer
from sentry.constants import ObjectStatus
from sentry.models.organization import Organization
from sentry.models.projectkey import ProjectKey, ProjectKeyStatus, UseCase
from sentry.ratelimits.config import RateLimitConfig
from sentry.types.ratelimit import RateLimit, RateLimitCategory


class DsnLookupResponse(TypedDict):
organizationSlug: Annotated[str, ApiDescription("Slug of the organization")]
projectSlug: Annotated[str, ApiDescription("Slug of the project the DSN belongs to")]
projectId: Annotated[str, ApiDescription("ID of the project the DSN belongs to")]
projectName: Annotated[str, ApiDescription("Name of the project the DSN belongs to")]
projectPlatform: Annotated[str | None, ApiDescription("Platform of the project, if set")]
keyLabel: Annotated[str | None, ApiDescription("Label of the client key")]
keyId: Annotated[str, ApiDescription("ID of the client key")]


@extend_schema(tags=["Projects"])
@cell_silo_endpoint
class DsnLookupEndpoint(OrganizationEndpoint):
"""Resolve a DSN to its project and key metadata within an organization.
Expand All @@ -24,7 +49,7 @@ class DsnLookupEndpoint(OrganizationEndpoint):

owner = ApiOwner.TELEMETRY_EXPERIENCE
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"GET": ApiPublishStatus.PUBLIC,
}
enforce_rate_limit = True
rate_limits = RateLimitConfig(
Expand All @@ -35,7 +60,40 @@ class DsnLookupEndpoint(OrganizationEndpoint):
}
)

def get(self, request: Request, organization: Organization) -> Response:
@extend_schema(
operation_id="resolveOrganizationDsn",
summary="Resolve a DSN to Its Project",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
OpenApiParameter(
name="dsn",
location="query",
required=True,
type=str,
description="The DSN to look up, such as `https://<public_key>@o1.ingest.sentry.io/2`.",
),
],
responses={
200: inline_sentry_response_serializer("DsnLookupResponse", DsnLookupResponse),
400: RESPONSE_BAD_REQUEST,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
429: RESPONSE_TOO_MANY_REQUESTS,
},
examples=ProjectExamples.RESOLVE_DSN,
)
def get(
self, request: Request, organization: Organization
) -> Response[DsnLookupResponse] | Response[DetailResponse]:
"""
Return the project and client key that a DSN belongs to. Only the DSN's public key
is used: the host and project ID in the DSN are ignored.

Returns 400 when `dsn` is missing. Returns 404 when the DSN has no public key, or
when it doesn't match an active client key of an active project in this
organization that you can access.
"""
dsn = request.GET.get("dsn")
if not dsn:
return Response({"detail": "Missing required parameter: dsn"}, status=400)
Expand All @@ -60,14 +118,13 @@ def get(self, request: Request, organization: Organization) -> Response:
if not request.access.has_project_access(project_key.project):
return Response({"detail": "DSN not found"}, status=404)

return Response(
{
"organizationSlug": organization.slug,
"projectSlug": project_key.project.slug,
"projectId": str(project_key.project.id),
"projectName": project_key.project.name,
"projectPlatform": project_key.project.platform,
"keyLabel": project_key.label,
"keyId": str(project_key.id),
}
)
data: DsnLookupResponse = {
"organizationSlug": organization.slug,
"projectSlug": project_key.project.slug,
"projectId": str(project_key.project.id),
"projectName": project_key.project.name,
"projectPlatform": project_key.project.platform,
"keyLabel": project_key.label,
"keyId": str(project_key.id),
}
return Response(data)
17 changes: 17 additions & 0 deletions src/sentry/apidocs/examples/project_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,3 +541,20 @@ class ProjectExamples:
response_only=True,
),
]

RESOLVE_DSN = [
OpenApiExample(
"Resolve a DSN to its project",
value={
"organizationSlug": "the-interstellar-jurisdiction",
"projectSlug": "pump-station",
"projectId": "2",
"projectName": "Pump Station",
"projectPlatform": "python",
"keyLabel": "Default",
"keyId": "60120449",
},
status_codes=["200"],
response_only=True,
),
]
24 changes: 24 additions & 0 deletions tests/apidocs/endpoints/projects/test_dsn_lookup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from urllib.parse import urlencode

from django.test.client import RequestFactory
from django.urls import reverse

from fixtures.apidocs_test_case import APIDocsTestCase


class DsnLookupDocsTest(APIDocsTestCase):
def setUp(self) -> None:
key = self.project.key_set.get()
self.url = reverse(
"sentry-api-0-organization-dsn-lookup",
kwargs={"organization_id_or_slug": self.organization.slug},
)
self.url = f"{self.url}?{urlencode({'dsn': key.dsn_public})}"
self.login_as(user=self.user)

def test_get(self) -> None:
response = self.client.get(self.url)
assert response.status_code == 200, response.content
request = RequestFactory().get(self.url)

self.validate_schema(request, response)
Original file line number Diff line number Diff line change
Expand Up @@ -1651,6 +1651,8 @@ def _query_params(self, endpoint: PublicGetEndpoint | PublicMutationEndpoint) ->
return {"file": "src/matrix.py", "platform": "python"}
if endpoint.endpoint_name == "OrganizationIntegrationChannelValidateEndpoint":
return {"channel": "permission-matrix"}
if endpoint.endpoint_name == "DsnLookupEndpoint":
return {"dsn": self._resource("project_key").dsn_public}
if endpoint.endpoint_name == "OrganizationEventsEndpoint":
return {
"field": ["id", "project"],
Expand Down
Loading