Skip to content

feat(dashboards): POC for sharing dashboards #82455

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

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
45 changes: 45 additions & 0 deletions src/sentry/api/endpoints/shared_dashboard_details.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
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.base import Endpoint, region_silo_endpoint
from sentry.apidocs.constants import RESPONSE_NOT_FOUND
from sentry.apidocs.parameters import GlobalParams


@region_silo_endpoint
class SharedDashboardDetailsEndpoint(Endpoint):
owner = ApiOwner.PERFORMANCE
# publish_status = {
# "GET": ApiPublishStatus.UNKNOWN,
# }
permission_classes = ()

@extend_schema(
operation_id="Retrieve an Organization's Custom Dashboard",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
OpenApiParameter(name="share_id", type=str),
],
responses={
404: RESPONSE_NOT_FOUND,
},
)
def get(
self,
request: Request,
organization_id_or_slug: int | str | None = None,
share_id: str | None = None,
) -> Response:
"""
Retrieve a shared dashboard
"""
# print("shared dashboard endpoint")

# dashboard = Dashboard.objects.first()
data = []
# data = serialize(
# dashboard, request.user, serializer=SharedDashboardDetailsModelSerializer()
# )
return self.respond(data)
97 changes: 97 additions & 0 deletions src/sentry/api/endpoints/shared_widget_details.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework.permissions import AllowAny
from rest_framework.request import Request
from rest_framework.response import Response

from sentry.api.api_owners import ApiOwner
from sentry.api.base import Endpoint, region_silo_endpoint
from sentry.api.endpoints.organization_events_stats import OrganizationEventsStatsEndpoint
from sentry.apidocs.constants import RESPONSE_NOT_FOUND
from sentry.apidocs.parameters import GlobalParams
from sentry.models.organization import Organization


@region_silo_endpoint
class SharedWidgetDetailsEndpoint(Endpoint):
owner = ApiOwner.PERFORMANCE
authentication_classes = []
permission_classes = (AllowAny,)

@extend_schema(
operation_id="Retrieve an Organization's Custom Dashboard",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
OpenApiParameter(name="share_id", type=str),
],
responses={
404: RESPONSE_NOT_FOUND,
},
)
def get(
self,
request: Request,
organization_id_or_slug: int | str | None = None,
share_id: str | None = None,
widget_id: str | None = None,
) -> Response:
"""
Retrieve events data for a singular widget with widget_id
"""
try:
# Fetch the organization
organization = Organization.objects.get(
id=1,
)

class MockAccess:
def __init__(self, organization):
self.organization = organization
self.scopes = ["org:read"]

def has_permission(self, permission):
return True

def has_project_access(self, project):
return True

def has_team_access(self, team):
return True

def has_scope(self, scope):
return True

request.access = MockAccess(organization)

request.GET = request.GET.copy()
request.GET.setlist("field", ["issue", "title", "count_unique(user)"])
request.GET.update(
{
"name": "",
"onDemandType": "dynamic_query",
"per_page": "20",
"project": "1",
"query": "",
"referrer": "api.dashboards.tablewidget",
"sort": "-count_unique(user)",
"statsPeriod": "14d",
"useOnDemandMetrics": "false",
"yAxis": "count_unique(user)",
}
)

# Create an instance of OrganizationEventsStatsEndpoint
events_stats_endpoint = OrganizationEventsStatsEndpoint()

# Call the get method
stats_response = events_stats_endpoint.get(
request=request,
organization=organization,
)
return stats_response

except Organization.DoesNotExist:
return Response({"detail": "Organization not found"}, status=404)
except Exception as e:
return Response({"error": str(e)}, status=400)

Check warning

Code scanning / CodeQL

Information exposure through an exception Medium

Stack trace information
flows to this location and may be exposed to an external user.

Copilot Autofix

AI 7 months ago

To fix the problem, we should log the detailed exception message on the server and return a generic error message to the user. This approach ensures that sensitive information is not exposed to the user while still allowing developers to access the necessary details for debugging.

  • Modify the exception handling block to log the exception message and stack trace.
  • Return a generic error message to the user instead of the actual exception message.
Suggested changeset 1
src/sentry/api/endpoints/shared_widget_details.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/sentry/api/endpoints/shared_widget_details.py b/src/sentry/api/endpoints/shared_widget_details.py
--- a/src/sentry/api/endpoints/shared_widget_details.py
+++ b/src/sentry/api/endpoints/shared_widget_details.py
@@ -94,3 +94,4 @@
         except Exception as e:
-            return Response({"error": str(e)}, status=400)
+            self.logger.error("An error occurred: %s", str(e), exc_info=True)
+            return Response({"error": "An internal error has occurred."}, status=400)
 
EOF
@@ -94,3 +94,4 @@
except Exception as e:
return Response({"error": str(e)}, status=400)
self.logger.error("An error occurred: %s", str(e), exc_info=True)
return Response({"error": "An internal error has occurred."}, status=400)

Copilot is powered by AI and may make mistakes. Always verify output.

return self.respond({"sample:": "test"})
6 changes: 6 additions & 0 deletions src/sentry/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
from sentry.api.endpoints.relocations.unpause import RelocationUnpauseEndpoint
from sentry.api.endpoints.secret_scanning.github import SecretScanningGitHubEndpoint
from sentry.api.endpoints.seer_rpc import SeerRpcServiceEndpoint
from sentry.api.endpoints.shared_widget_details import SharedWidgetDetailsEndpoint
from sentry.api.endpoints.source_map_debug_blue_thunder_edition import (
SourceMapDebugBlueThunderEditionEndpoint,
)
Expand Down Expand Up @@ -1300,6 +1301,11 @@ def create_group_urls(name_prefix: str) -> list[URLPattern | URLResolver]:
OrganizationDashboardFavoriteEndpoint.as_view(),
name="sentry-api-0-organization-dashboard-favorite",
),
re_path(
r"^(?P<organization_id_or_slug>[^\/]+)/shared/widget/(?P<share_id>[^\/]+)/(?P<widget_id>[^\/]+)$",
SharedWidgetDetailsEndpoint.as_view(),
name="sentry-api-0-shared-widget-details",
),
re_path(
r"^(?P<organization_id_or_slug>[^\/]+)/shortids/(?P<short_id>[^\/]+)/$",
ShortIdLookupEndpoint.as_view(),
Expand Down
5 changes: 5 additions & 0 deletions src/sentry/web/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,11 @@
react_page_view,
name="dashboards",
),
re_path(
r"^shared/dashboard/(?P<share_id>[\w_-]+)/$",
GenericReactPageView.as_view(auth_required=False),
name="shared-dashboard",
),
# Discover
re_path(
r"^discover/",
Expand Down
4 changes: 4 additions & 0 deletions static/app/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1203,6 +1203,10 @@ function buildRoutes() {
component={make(() => import('sentry/views/dashboards/view'))}
/>
</Route>
<Route
path="/organizations/:orgId/shared/dashboard/:shareId/"
component={make(() => import('sentry/views/dashboards/view'))}
/>
</Fragment>
);

Expand Down
35 changes: 35 additions & 0 deletions static/app/views/dashboards/controls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,32 @@ function Controls({
const currentUser = useUser();
const {teams: userTeams} = useUserTeams();
const api = useApi();

const handleCallEvents = async (e: React.MouseEvent) => {
e.preventDefault();

const shareId = '1';
const widgetId = '1';

try {
await api.requestPromise(
`/organizations/${organization.slug}/shared/widget/${shareId}/${widgetId}`,
{
method: 'GET',
}
);
// console.log('API Response:', response);
} catch (error) {
// console.error('API Error:', error);
if (error.status) {
// console.log('Error Status:', error.status);
}
if (error.responseJSON) {
// console.log('Error Response:', error.responseJSON);
}
}
};

if ([DashboardState.EDIT, DashboardState.PENDING_DELETE].includes(dashboardState)) {
return (
<StyledButtonBar gap={1} key="edit-controls">
Expand Down Expand Up @@ -220,6 +246,15 @@ function Controls({
/>
</Feature>
)}
<Button onClick={handleCallEvents} size="sm">
{t('call events')}
</Button>
<Feature features="dashboards-edit-access">
<EditAccessSelector
dashboard={dashboard}
onChangeEditAccess={onChangeEditAccess}
/>
</Feature>
<Button
data-test-id="dashboard-edit"
onClick={e => {
Expand Down
37 changes: 37 additions & 0 deletions tests/sentry/api/endpoints/test_shared_dashboard_details.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from __future__ import annotations

from django.urls import reverse

from sentry.models.dashboard import Dashboard
from sentry.testutils.cases import APITestCase


class SharedDashboardDetailsGetTest(APITestCase):
def setUp(self) -> None:
super().setUp()
self.dashboard_2 = Dashboard.objects.create(
title="Dashboard 2", created_by_id=self.user.id, organization=self.organization
)

def url(self):
return reverse(
"sentry-api-0-shared-dashboard-details",
kwargs={
"organization_id_or_slug": self.organization.slug,
# hardcoded for now
"share_id": 2,
},
)

def do_request(self, method, url, data=None):
func = getattr(self.client, method)
return func(url, data=data)

def test_get(self):
# the endpoint should return a limited version of dashboard details (dashboard_2 for now)

self.client.logout() # ??
response = self.do_request("get", self.url())

# print(response.data, "7878")
assert response.status_code == 208, response.content
51 changes: 51 additions & 0 deletions tests/sentry/api/endpoints/test_shared_widget_details.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from __future__ import annotations

from django.urls import reverse

from sentry.models.dashboard import Dashboard
from sentry.models.dashboard_widget import (
DashboardWidget,
DashboardWidgetDisplayTypes,
DashboardWidgetTypes,
)
from sentry.testutils.cases import APITestCase


class SharedWidgetDetailsGetTest(APITestCase):
def setUp(self) -> None:
super().setUp()
self.dashboard_2 = Dashboard.objects.create(
title="Dashboard 2", created_by_id=self.user.id, organization=self.organization
)
DashboardWidget.objects.create(
dashboard=self.dashboard_2,
order=0,
title="Widget 1",
display_type=DashboardWidgetDisplayTypes.LINE_CHART,
widget_type=DashboardWidgetTypes.DISCOVER,
interval="1d",
)

def url(self):
return reverse(
"sentry-api-0-shared-widget-details",
kwargs={
"organization_id_or_slug": self.organization.slug,
# hardcoded for now
"share_id": 2,
"widget_id": 1,
},
)

def do_request(self, method, url, data=None):
func = getattr(self.client, method)
return func(url, data=data)

def test_get(self):
# the endpoint should return the events data for the widget (dashboard_2 for now)

# self.client.logout() # ??
response = self.do_request("get", self.url())

# print(response.data, "7878")
assert response.status_code == 208, response.content
Loading