Skip to content
Closed
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
72 changes: 72 additions & 0 deletions src/sentry/api/endpoints/dsn_lookup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from urllib.parse import urlparse

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, region_silo_endpoint
from sentry.api.permissions import SentryIsAuthenticated
from sentry.models.organizationmember import OrganizationMember
from sentry.models.projectkey import ProjectKey
from sentry.ratelimits.config import RateLimitConfig
from sentry.types.ratelimit import RateLimit, RateLimitCategory


@region_silo_endpoint
class DsnLookupEndpoint(Endpoint):
owner = ApiOwner.TELEMETRY_EXPERIENCE
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (SentryIsAuthenticated,)
enforce_rate_limit = True
rate_limits = RateLimitConfig(
limit_overrides={
"GET": {
RateLimitCategory.USER: RateLimit(limit=5, window=1),
}
}
)

def get(self, request: Request) -> Response:
dsn = request.GET.get("dsn")
if not dsn:
return Response({"detail": "Missing required parameter: dsn"}, status=400)

try:
parsed = urlparse(dsn)
except Exception:
return Response({"detail": "Invalid DSN"}, status=404)

public_key = parsed.username
if not public_key:
return Response({"detail": "Invalid DSN"}, status=404)

try:
project_key = ProjectKey.objects.select_related("project__organization").get(
public_key=public_key,
)
except ProjectKey.DoesNotExist:
return Response({"detail": "DSN not found"}, status=404)

organization = project_key.project.organization

is_member = OrganizationMember.objects.filter(
organization_id=organization.id,
user_id=request.user.id,
).exists()
if not is_member:
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),
}
)
7 changes: 7 additions & 0 deletions src/sentry/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from django.conf.urls import include
from django.urls import URLPattern, URLResolver, re_path

from sentry.api.endpoints.dsn_lookup import DsnLookupEndpoint
from sentry.api.endpoints.organization_ai_conversation_details import (
OrganizationAIConversationDetailsEndpoint,
)
Expand Down Expand Up @@ -3802,6 +3803,12 @@ def create_group_urls(name_prefix: str) -> list[URLPattern | URLResolver]:
SecretScanningGitHubEndpoint.as_view(),
name="sentry-api-0-secret-scanning-github",
),
# DSN Lookup
re_path(
r"^dsn-lookup/$",
DsnLookupEndpoint.as_view(),
name="sentry-api-0-dsn-lookup",
),
# Catch all
re_path(
r"^$",
Expand Down
2 changes: 2 additions & 0 deletions src/sentry/features/temporary.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,8 @@ def register_temporary_features(manager: FeatureManager) -> None:
manager.add("organizations:disable-grace-period", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=False)
# Enables CMD+K supercharged (omni search)
manager.add("organizations:cmd-k-supercharged", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
# Enables DSN lookup in CMD+K palette
manager.add("organizations:cmd-k-dsn-lookup", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
# Enable Conversation focused views in AI Insights
manager.add("organizations:gen-ai-conversations", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
manager.add("organizations:on-demand-gen-metrics-deprecation-prefill", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=False)
Expand Down
2 changes: 1 addition & 1 deletion static/app/components/commandPalette/types.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {ReactNode} from 'react';
import type {LocationDescriptor} from 'history';

export type CommandPaletteGroupKey = 'navigate' | 'add' | 'help';
export type CommandPaletteGroupKey = 'search-result' | 'navigate' | 'add' | 'help';

interface CommonCommandPaletteAction {
display: {
Expand Down
3 changes: 3 additions & 0 deletions static/app/components/commandPalette/ui/constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ export const COMMAND_PALETTE_GROUP_KEY_CONFIG: Record<
label: string;
}
> = {
'search-result': {
label: t('Search Results'),
},
navigate: {
label: t('Go to…'),
},
Expand Down
18 changes: 14 additions & 4 deletions static/app/components/commandPalette/ui/content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import type {CommandPaletteActionWithKey} from 'sentry/components/commandPalette
import {COMMAND_PALETTE_GROUP_KEY_CONFIG} from 'sentry/components/commandPalette/ui/constants';
import {CommandPaletteList} from 'sentry/components/commandPalette/ui/list';
import {useCommandPaletteState} from 'sentry/components/commandPalette/ui/useCommandPaletteState';
import {useDsnLookupActions} from 'sentry/components/commandPalette/useDsnLookupActions';
import {SvgIcon} from 'sentry/icons/svgIcon';
import {unreachable} from 'sentry/utils/unreachable';
import normalizeUrl from 'sentry/utils/url/normalizeUrl';
import {useNavigate} from 'sentry/utils/useNavigate';
import useOrganization from 'sentry/utils/useOrganization';

type CommandPaletteActionMenuItem = MenuListItemProps & {
children: CommandPaletteActionMenuItem[];
Expand Down Expand Up @@ -41,12 +43,20 @@ function actionToMenuItem(
export function CommandPaletteContent() {
const {actions, selectedAction, selectAction, clearSelection, query, setQuery} =
useCommandPaletteState();
const organization = useOrganization({allowNull: true});
const hasDsnLookup = organization?.features?.includes('cmd-k-dsn-lookup') ?? false;
const dsnLookupActions = useDsnLookupActions(hasDsnLookup ? query : '');
const navigate = useNavigate();
const inputRef = useRef<HTMLInputElement>(null);

const mergedActions = useMemo(
() => [...dsnLookupActions, ...actions],
[dsnLookupActions, actions]
);

const groupedMenuItems = useMemo<CommandPaletteActionMenuItem[]>(() => {
const itemsBySection = new Map<string, CommandPaletteActionMenuItem[]>();
for (const action of actions) {
for (const action of mergedActions) {
const sectionLabel = action.groupingKey
? (COMMAND_PALETTE_GROUP_KEY_CONFIG[action.groupingKey]?.label ?? '')
: '';
Expand All @@ -65,7 +75,7 @@ export function CommandPaletteContent() {
};
})
.filter(section => section.children.length > 0);
}, [actions]);
}, [mergedActions]);

const handleSelect = useCallback(
(action: CommandPaletteActionWithKey) => {
Expand Down Expand Up @@ -94,12 +104,12 @@ export function CommandPaletteContent() {
if (selectionKey === null || selectionKey === undefined) {
return;
}
const action = actions.find(a => a.key === selectionKey);
const action = mergedActions.find(a => a.key === selectionKey);
if (action) {
handleSelect(action);
}
},
[actions, handleSelect]
[mergedActions, handleSelect]
);

// When an action has been selected, clear the query and focus the input
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import {renderHookWithProviders, waitFor} from 'sentry-test/reactTestingLibrary';

import {useDsnLookupActions} from 'sentry/components/commandPalette/useDsnLookupActions';

describe('useDsnLookupActions', () => {
beforeEach(() => {
MockApiClient.clearMockResponses();
});

it('returns actions for a valid DSN', async () => {
const dsn = 'https://abc123def456abc123def456abc123de@o1.ingest.sentry.io/123';
MockApiClient.addMockResponse({
url: '/dsn-lookup/',
body: {
organizationSlug: 'test-org',
projectSlug: 'test-project',
projectId: '42',
projectName: 'Test Project',
projectPlatform: 'javascript',
keyLabel: 'Default',
keyId: '1',
},
match: [MockApiClient.matchQuery({dsn})],
});

const {result} = renderHookWithProviders(() => useDsnLookupActions(dsn));

await waitFor(() => {
expect(result.current.length).toBeGreaterThan(0);
});

expect(result.current).toEqual(
expect.arrayContaining([
expect.objectContaining({
key: 'dsn-lookup-issues',
type: 'navigate',
to: '/organizations/test-org/issues/?project=42',
}),
expect.objectContaining({
key: 'dsn-lookup-project-settings',
type: 'navigate',
to: '/settings/test-org/projects/test-project/',
}),
expect.objectContaining({
key: 'dsn-lookup-client-keys',
type: 'navigate',
to: '/settings/test-org/projects/test-project/keys/',
}),
])
);
});

it('returns empty array for non-DSN query', () => {
const mockApi = MockApiClient.addMockResponse({
url: '/dsn-lookup/',
body: {},
});

const {result} = renderHookWithProviders(() =>
useDsnLookupActions('some random text')
);

expect(result.current).toEqual([]);
expect(mockApi).not.toHaveBeenCalled();
});

it('returns empty array for empty query', () => {
const mockApi = MockApiClient.addMockResponse({
url: '/dsn-lookup/',
body: {},
});

const {result} = renderHookWithProviders(() => useDsnLookupActions(''));

expect(result.current).toEqual([]);
expect(mockApi).not.toHaveBeenCalled();
});
});
81 changes: 81 additions & 0 deletions static/app/components/commandPalette/useDsnLookupActions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import {useMemo} from 'react';

import type {CommandPaletteActionWithKey} from 'sentry/components/commandPalette/types';
import {IconIssues, IconList, IconSettings} from 'sentry/icons';
import {t} from 'sentry/locale';
import {useApiQuery} from 'sentry/utils/queryClient';
import {useDebouncedValue} from 'sentry/utils/useDebouncedValue';

const DSN_PATTERN = /^https?:\/\/([a-f0-9]{32})(:[a-f0-9]{32})?@[^/]+\/\d+$/;

interface DsnLookupResponse {
keyId: string;
keyLabel: string;
organizationSlug: string;
projectId: string;
projectName: string;
projectPlatform: string | null;
projectSlug: string;
}

export function useDsnLookupActions(query: string): CommandPaletteActionWithKey[] {
const debouncedQuery = useDebouncedValue(query, 300);
const isDsn = DSN_PATTERN.test(debouncedQuery);

const {data} = useApiQuery<DsnLookupResponse>(
[`/dsn-lookup/`, {query: {dsn: debouncedQuery}}],
{
staleTime: 30_000,
enabled: isDsn,
}
);

return useMemo(() => {
if (!data) {
return [];
}

const orgSlug = data.organizationSlug;
const projectSlug = data.projectSlug;
const projectId = data.projectId;
const projectName = data.projectName;

const actions: CommandPaletteActionWithKey[] = [
{
key: 'dsn-lookup-issues',
type: 'navigate',
to: `/organizations/${orgSlug}/issues/?project=${projectId}`,
display: {
label: t('Issues for %s', projectName),
details: t('View issues'),
icon: <IconIssues />,
},
groupingKey: 'search-result',
},
{
key: 'dsn-lookup-project-settings',
type: 'navigate',
to: `/settings/${orgSlug}/projects/${projectSlug}/`,
display: {
label: t('%s Settings', projectName),
details: t('Project settings'),
icon: <IconSettings />,
},
groupingKey: 'search-result',
},
{
key: 'dsn-lookup-client-keys',
type: 'navigate',
to: `/settings/${orgSlug}/projects/${projectSlug}/keys/`,
display: {
label: t('Client Keys (DSN) for %s', projectName),
details: t('Manage DSN keys'),
icon: <IconList />,
},
groupingKey: 'search-result',
},
];

return actions;
}, [data]);
}
2 changes: 2 additions & 0 deletions static/app/components/search/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import useRouter from 'sentry/utils/useRouter';

import ApiSource from './sources/apiSource';
import CommandSource from './sources/commandSource';
import DsnLookupSource from './sources/dsnLookupSource';
import FormSource from './sources/formSource';
import OrganizationsSource from './sources/organizationsSource';
import RouteSource from './sources/routeSource';
Expand Down Expand Up @@ -203,6 +204,7 @@ function Search({
RouteSource,
OrganizationsSource,
CommandSource,
DsnLookupSource,
]
}
>
Expand Down
Loading
Loading