Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: v2 versions of public dashboard APIs (#11725)

Naman Verma832a6cc79433
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index faac87f230..89b10ddab9 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -2917,6 +2917,13 @@ components:
publicDashboard:
$ref: '#/components/schemas/DashboardtypesGettablePublicDasbhboard'
type: object
+ DashboardtypesGettablePublicDashboardDataV2:
+ properties:
+ dashboard:
+ $ref: '#/components/schemas/DashboardtypesGettableDashboardV2'
+ publicDashboard:
+ $ref: '#/components/schemas/DashboardtypesGettablePublicDasbhboard'
+ type: object
DashboardtypesHistogramBuckets:
properties:
bucketCount:
@@ -17518,6 +17525,138 @@ paths:
summary: Update my organization
tags:
- orgs
+ /api/v2/public/dashboards/{id}:
+ get:
+ deprecated: false
+ description: This endpoint returns the sanitized v2-shape dashboard data for
+ public access. Each panel query is reduced to a safe field subset, so filters
+ and raw query strings are not exposed.
+ operationId: GetPublicDashboardDataV2
+ parameters:
+ - in: path
+ name: id
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/DashboardtypesGettablePublicDashboardDataV2'
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: OK
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Bad Request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - anonymous:
+ - public-dashboard:read
+ summary: Get public dashboard data (v2)
+ tags:
+ - dashboard
+ /api/v2/public/dashboards/{id}/panels/{key}/query_range:
+ get:
+ deprecated: false
+ description: This endpoint returns query range results for a panel of a v2-shape
+ public dashboard. The panel is addressed by its key in spec.panels.
+ operationId: GetPublicDashboardPanelQueryRangeV2
+ parameters:
+ - in: path
+ name: id
+ required: true
+ schema:
+ type: string
+ - in: path
+ name: key
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/Querybuildertypesv5QueryRangeResponse'
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: OK
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Bad Request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - anonymous:
+ - public-dashboard:read
+ summary: Get query range result (v2)
+ tags:
+ - dashboard
/api/v2/readyz:
get:
operationId: Readyz
diff --git a/ee/modules/dashboard/impldashboard/module.go b/ee/modules/dashboard/impldashboard/module.go
index 024196884f..8a438b9b4c 100644
--- a/ee/modules/dashboard/impldashboard/module.go
+++ b/ee/modules/dashboard/impldashboard/module.go
@@ -29,6 +29,7 @@ type module struct {
settings factory.ScopedProviderSettings
querier querier.Querier
licensing licensing.Licensing
+ tagModule tag.Module
}
func NewModule(store dashboardtypes.Store, settings factory.ProviderSettings, analytics analytics.Analytics, orgGetter organization.Getter, queryParser queryparser.QueryParser, querier querier.Querier, licensing licensing.Licensing, tagModule tag.Module) dashboard.Module {
@@ -41,6 +42,7 @@ func NewModule(store dashboardtypes.Store, settings factory.ProviderSettings, an
settings: scopedProviderSettings,
querier: querier,
licensing: licensing,
+ tagModule: tagModule,
}
}
@@ -132,6 +134,55 @@ func (module *module) GetPublicWidgetQueryRange(ctx context.Context, id valuer.U
return module.querier.QueryRange(ctx, dashboard.OrgID, query)
}
+func (module *module) GetDashboardByPublicIDV2(ctx context.Context, id valuer.UUID) (*dashboardtypes.DashboardV2, error) {
+ storableDashboard, err := module.store.GetDashboardByPublicID(ctx, id.StringValue())
+ if err != nil {
+ return nil, err
+ }
+
+ tags, err := module.tagModule.ListForResource(ctx, storableDashboard.OrgID, coretypes.KindDashboard, storableDashboard.ID)
+ if err != nil {
+ return nil, err
+ }
+
+ return storableDashboard.ToDashboardV2(tags)
+}
+
+func (module *module) GetPublicWidgetQueryRangeV2(ctx context.Context, id valuer.UUID, panelKey, startTimeRaw, endTimeRaw string) (*querybuildertypesv5.QueryRangeResponse, error) {
+ ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
+ instrumentationtypes.CodeNamespace: "dashboard",
+ instrumentationtypes.CodeFunctionName: "GetPublicWidgetQueryRangeV2",
+ })
+
+ storableDashboard, err := module.store.GetDashboardByPublicID(ctx, id.StringValue())
+ if err != nil {
+ return nil, err
+ }
+
+ // tags are not needed for query range.
+ dashboard, err := storableDashboard.ToDashboardV2(nil)
+ if err != nil {
+ return nil, err
+ }
+
+ publicDashboard, err := module.GetPublic(ctx, dashboard.OrgID, dashboard.ID)
+ if err != nil {
+ return nil, err
+ }
+
+ startTime, endTime, err := publicDashboard.ResolveTimeRange(startTimeRaw, endTimeRaw)
+ if err != nil {
+ return nil, err
+ }
+
+ query, err := dashboard.GetPanelQuery(startTime, endTime, panelKey)
+ if err != nil {
+ return nil, err
+ }
+
+ return module.querier.QueryRange(ctx, dashboard.OrgID, query)
+}
+
func (module *module) UpdatePublic(ctx context.Context, orgID valuer.UUID, publicDashboard *dashboardtypes.PublicDashboard) error {
_, err := module.licensing.GetActive(ctx, orgID)
if err != nil {
diff --git a/frontend/src/api/generated/services/dashboard/index.ts b/frontend/src/api/generated/services/dashboard/index.ts
index 9839ec6485..060afa9c39 100644
--- a/frontend/src/api/generated/services/dashboard/index.ts
+++ b/frontend/src/api/generated/services/dashboard/index.ts
@@ -38,6 +38,10 @@ import type {
GetPublicDashboard200,
GetPublicDashboardData200,
GetPublicDashboardDataPathParameters,
+ GetPublicDashboardDataV2200,
+ GetPublicDashboardDataV2PathParameters,
+ GetPublicDashboardPanelQueryRangeV2200,
+ GetPublicDashboardPanelQueryRangeV2PathParameters,
GetPublicDashboardPathParameters,
GetPublicDashboardWidgetQueryRange200,
GetPublicDashboardWidgetQueryRangePathParameters,
@@ -1799,6 +1803,217 @@ export const useLockDashboardV2 = <
> => {
return useMutation(getLockDashboardV2MutationOptions(options));
};
+/**
+ * This endpoint returns the sanitized v2-shape dashboard data for public access. Each panel query is reduced to a safe field subset, so filters and raw query strings are not exposed.
+ * @summary Get public dashboard data (v2)
+ */
+export const getPublicDashboardDataV2 = (
+ { id }: GetPublicDashboardDataV2PathParameters,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<GetPublicDashboardDataV2200>({
+ url: `/api/v2/public/dashboards/${id}`,
+ method: 'GET',
+ signal,
+ });
+};
+
+export const getGetPublicDashboardDataV2QueryKey = ({
+ id,
+}: GetPublicDashboardDataV2PathParameters) => {
+ return [`/api/v2/public/dashboards/${id}`] as const;
+};
+
+export const getGetPublicDashboardDataV2QueryOptions = <
+ TData = Awaited<ReturnType<typeof getPublicDashboardDataV2>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ { id }: GetPublicDashboardDataV2PathParameters,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getPublicDashboardDataV2>>,
+ TError,
+ TData
+ >;
+ },
+) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey =
+ queryOptions?.queryKey ?? getGetPublicDashboardDataV2QueryKey({ id });
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof getPublicDashboardDataV2>>
+ > = ({ signal }) => getPublicDashboardDataV2({ id }, signal);
+
+ return {
+ queryKey,
+ queryFn,
+ enabled: !!id,
+ ...queryOptions,
+ } as UseQueryOptions<
+ Awaited<ReturnType<typeof getPublicDashboardDataV2>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type GetPublicDashboardDataV2QueryResult = NonNullable<
+ Awaited<ReturnType<typeof getPublicDashboardDataV2>>
+>;
+export type GetPublicDashboardDataV2QueryError =
+ ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Get public dashboard data (v2)
+ */
+
+export function useGetPublicDashboardDataV2<
+ TData = Awaited<ReturnType<typeof getPublicDashboardDataV2>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ { id }: GetPublicDashboardDataV2PathParameters,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getPublicDashboardDataV2>>,
+ TError,
+ TData
+ >;
+ },
+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getGetPublicDashboardDataV2QueryOptions({ id }, options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ return { ...query, queryKey: queryOptions.queryKey };
+}
+
+/**
+ * @summary Get public dashboard data (v2)
+ */
+export const invalidateGetPublicDashboardDataV2 = async (
+ queryClient: QueryClient,
+ { id }: GetPublicDashboardDataV2PathParameters,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getGetPublicDashboardDataV2QueryKey({ id }) },
+ options,
+ );
+
+ return queryClient;
+};
+
+/**
+ * This endpoint returns query range results for a panel of a v2-shape public dashboard. The panel is addressed by its key in spec.panels.
+ * @summary Get query range result (v2)
+ */
+export const getPublicDashboardPanelQueryRangeV2 = (
+ { id, key }: GetPublicDashboardPanelQueryRangeV2PathParameters,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<GetPublicDashboardPanelQueryRangeV2200>({
+ url: `/api/v2/public/dashboards/${id}/panels/${key}/query_range`,
+ method: 'GET',
+ signal,
+ });
+};
+
+export const getGetPublicDashboardPanelQueryRangeV2QueryKey = ({
+ id,
+ key,
+}: GetPublicDashboardPanelQueryRangeV2PathParameters) => {
+ return [`/api/v2/public/dashboards/${id}/panels/${key}/query_range`] as const;
+};
+
+export const getGetPublicDashboardPanelQueryRangeV2QueryOptions = <
+ TData = Awaited<ReturnType<typeof getPublicDashboardPanelQueryRangeV2>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ { id, key }: GetPublicDashboardPanelQueryRangeV2PathParameters,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getPublicDashboardPanelQueryRangeV2>>,
+ TError,
+ TData
+ >;
+ },
+) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey =
+ queryOptions?.queryKey ??
+ getGetPublicDashboardPanelQueryRangeV2QueryKey({ id, key });
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof getPublicDashboardPanelQueryRangeV2>>
+ > = ({ signal }) => getPublicDashboardPanelQueryRangeV2({ id, key }, signal);
+
+ return {
+ queryKey,
+ queryFn,
+ enabled: !!(id && key),
+ ...queryOptions,
+ } as UseQueryOptions<
+ Awaited<ReturnType<typeof getPublicDashboardPanelQueryRangeV2>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type GetPublicDashboardPanelQueryRangeV2QueryResult = NonNullable<
+ Awaited<ReturnType<typeof getPublicDashboardPanelQueryRangeV2>>
+>;
+export type GetPublicDashboardPanelQueryRangeV2QueryError =
+ ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Get query range result (v2)
+ */
+
+export function useGetPublicDashboardPanelQueryRangeV2<
+ TData = Awaited<ReturnType<typeof getPublicDashboardPanelQueryRangeV2>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ { id, key }: GetPublicDashboardPanelQueryRangeV2PathParameters,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getPublicDashboardPanelQueryRangeV2>>,
+ TError,
+ TData
+ >;
+ },
+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getGetPublicDashboardPanelQueryRangeV2QueryOptions(
+ { id, key },
+ options,
+ );
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ return { ...query, queryKey: queryOptions.queryKey };
+}
+
+/**
+ * @summary Get query range result (v2)
+ */
+export const invalidateGetPublicDashboardPanelQueryRangeV2 = async (
+ queryClient: QueryClient,
+ { id, key }: GetPublicDashboardPanelQueryRangeV2PathParameters,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getGetPublicDashboardPanelQueryRangeV2QueryKey({ id, key }) },
+ options,
+ );
+
+ return queryClient;
+};
+
/**
* Same as ListDashboardsV2 but personalized for the calling user: each dashboard carries the caller's `pinned` state, and pinned dashboards float to the top of the requested ordering. Supports the same filter DSL, sort, order, and pagination.
* @summary List dashboards for the current user (v2)
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index e80ee3836b..19df175f2d 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -4941,6 +4941,11 @@ export interface DashboardtypesGettablePublicDashboardDataDTO {
publicDashboard?: DashboardtypesGettablePublicDasbhboardDTO;
}
+export interface DashboardtypesGettablePublicDashboardDataV2DTO {
+ dashboard?: DashboardtypesGettableDashboardV2DTO;
+ publicDashboard?: DashboardtypesGettablePublicDasbhboardDTO;
+}
+
export enum DashboardtypesPatchOpDTO {
add = 'add',
remove = 'remove',
@@ -11192,6 +11197,29 @@ export type GetMyOrganization200 = {
status: string;
};
+export type GetPublicDashboardDataV2PathParameters = {
+ id: string;
+};
+export type GetPublicDashboardDataV2200 = {
+ data: DashboardtypesGettablePublicDashboardDataV2DTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
+export type GetPublicDashboardPanelQueryRangeV2PathParameters = {
+ id: string;
+ key: string;
+};
+export type GetPublicDashboardPanelQueryRangeV2200 = {
+ data: Querybuildertypesv5QueryRangeResponseDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
export type Readyz200 = {
data: FactoryResponseDTO;
/**
diff --git a/pkg/apiserver/signozapiserver/dashboard.go b/pkg/apiserver/signozapiserver/dashboard.go
index ea350acafd..ce656f9477 100644
--- a/pkg/apiserver/signozapiserver/dashboard.go
+++ b/pkg/apiserver/signozapiserver/dashboard.go
@@ -421,5 +421,61 @@ func (provider *provider) addDashboardRoutes(router *mux.Router) error {
return err
}
+ if err := router.Handle("/api/v2/public/dashboards/{id}", handler.New(provider.authzMiddleware.CheckWithoutClaims(
+ provider.dashboardHandler.GetPublicDataV2,
+ authtypes.Relation{Verb: coretypes.VerbRead},
+ coretypes.ResourceMetaResourcePublicDashboard,
+ func(req *http.Request, orgs []*types.Organization) ([]coretypes.Selector, valuer.UUID, error) {
+ id, err := valuer.NewUUID(mux.Vars(req)["id"])
+ if err != nil {
+ return nil, valuer.UUID{}, err
+ }
+
+ return provider.dashboardModule.GetPublicDashboardSelectorsAndOrg(req.Context(), id, orgs)
+ }, []string{}), handler.OpenAPIDef{
+ ID: "GetPublicDashboardDataV2",
+ Tags: []string{"dashboard"},
+ Summary: "Get public dashboard data (v2)",
+ Description: "This endpoint returns the sanitized v2-shape dashboard data for public access. Each panel query is reduced to a safe field subset, so filters and raw query strings are not exposed.",
+ Request: nil,
+ RequestContentType: "",
+ Response: new(dashboardtypes.GettablePublicDashboardDataV2),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: newAnonymousSecuritySchemes([]string{coretypes.ResourceMetaResourcePublicDashboard.Scope(coretypes.VerbRead)}),
+ })).Methods(http.MethodGet).GetError(); err != nil {
+ return err
+ }
+
+ if err := router.Handle("/api/v2/public/dashboards/{id}/panels/{key}/query_range", handler.New(provider.authzMiddleware.CheckWithoutClaims(
+ provider.dashboardHandler.GetPublicWidgetQueryRangeV2,
+ authtypes.Relation{Verb: coretypes.VerbRead},
+ coretypes.ResourceMetaResourcePublicDashboard,
+ func(req *http.Request, orgs []*types.Organization) ([]coretypes.Selector, valuer.UUID, error) {
+ id, err := valuer.NewUUID(mux.Vars(req)["id"])
+ if err != nil {
+ return nil, valuer.UUID{}, err
+ }
+
+ return provider.dashboardModule.GetPublicDashboardSelectorsAndOrg(req.Context(), id, orgs)
+ }, []string{}), handler.OpenAPIDef{
+ ID: "GetPublicDashboardPanelQueryRangeV2",
+ Tags: []string{"dashboard"},
+ Summary: "Get query range result (v2)",
+ Description: "This endpoint returns query range results for a panel of a v2-shape public dashboard. The panel is addressed by its key in spec.panels.",
+ Request: nil,
+ RequestContentType: "",
+ Response: new(querybuildertypesv5.QueryRangeResponse),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: newAnonymousSecuritySchemes([]string{coretypes.ResourceMetaResourcePublicDashboard.Scope(coretypes.VerbRead)}),
+ })).Methods(http.MethodGet).GetError(); err != nil {
+ return err
+ }
+
return nil
}
diff --git a/pkg/modules/dashboard/dashboard.go b/pkg/modules/dashboard/dashboard.go
index bb724af05d..c399100ff4 100644
--- a/pkg/modules/dashboard/dashboard.go
+++ b/pkg/modules/dashboard/dashboard.go
@@ -81,6 +81,12 @@ type Module interface {
DeletePreferencesForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID) error
+ // get the v2 dashboard data by public dashboard id
+ GetDashboardByPublicIDV2(context.Context, valuer.UUID) (*dashboardtypes.DashboardV2, error)
+
+ // gets the query results by panel key and public shared id for a v2 dashboard
+ GetPublicWidgetQueryRangeV2(ctx context.Context, id valuer.UUID, panelKey, startTimeRaw, endTimeRaw string) (*querybuildertypesv5.QueryRangeResponse, error)
+
CreateView(ctx context.Context, orgID valuer.UUID, postable dashboardtypes.PostableDashboardView) (*dashboardtypes.DashboardView, error)
ListViews(ctx context.Context, orgID valuer.UUID) (*dashboardtypes.ListableDashboardView, error)
@@ -101,6 +107,10 @@ type Handler interface {
GetPublicWidgetQueryRange(http.ResponseWriter, *http.Request)
+ GetPublicDataV2(http.ResponseWriter, *http.Request)
+
+ GetPublicWidgetQueryRangeV2(http.ResponseWriter, *http.Request)
+
UpdatePublic(http.ResponseWriter, *http.Request)
DeletePublic(http.ResponseWriter, *http.Request)
diff --git a/pkg/modules/dashboard/impldashboard/module.go b/pkg/modules/dashboard/impldashboard/module.go
index d86c0f8fef..2e29754e0a 100644
--- a/pkg/modules/dashboard/impldashboard/module.go
+++ b/pkg/modules/dashboard/impldashboard/module.go
@@ -254,6 +254,14 @@ func (module *module) GetPublicWidgetQueryRange(context.Context, valuer.UUID, ui
return nil, errors.Newf(errors.TypeUnsupported, dashboardtypes.ErrCodePublicDashboardUnsupported, "not implemented")
}
+func (module *module) GetDashboardByPublicIDV2(_ context.Context, _ valuer.UUID) (*dashboardtypes.DashboardV2, error) {
+ return nil, errors.Newf(errors.TypeUnsupported, dashboardtypes.ErrCodePublicDashboardUnsupported, "not implemented")
+}
+
+func (module *module) GetPublicWidgetQueryRangeV2(context.Context, valuer.UUID, string, string, string) (*qbtypes.QueryRangeResponse, error) {
+ return nil, errors.Newf(errors.TypeUnsupported, dashboardtypes.ErrCodePublicDashboardUnsupported, "not implemented")
+}
+
func (module *module) GetPublicDashboardSelectorsAndOrg(_ context.Context, _ valuer.UUID, _ []*types.Organization) ([]coretypes.Selector, valuer.UUID, error) {
return nil, valuer.UUID{}, errors.Newf(errors.TypeUnsupported, dashboardtypes.ErrCodePublicDashboardUnsupported, "not implemented")
}
diff --git a/pkg/modules/dashboard/impldashboard/v2_handler.go b/pkg/modules/dashboard/impldashboard/v2_handler.go
index 074eba5b21..9c2ab26846 100644
--- a/pkg/modules/dashboard/impldashboard/v2_handler.go
+++ b/pkg/modules/dashboard/impldashboard/v2_handler.go
@@ -376,3 +376,53 @@ func (handler *handler) DeleteV2(rw http.ResponseWriter, r *http.Request) {
render.Success(rw, http.StatusNoContent, nil)
}
+
+func (handler *handler) GetPublicDataV2(rw http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
+ defer cancel()
+
+ id, err := valuer.NewUUID(mux.Vars(r)["id"])
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ dashboard, err := handler.module.GetDashboardByPublicIDV2(ctx, id)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ publicDashboard, err := handler.module.GetPublic(ctx, dashboard.OrgID, dashboard.ID)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, dashboardtypes.NewPublicDashboardDataFromDashboardV2(dashboard, publicDashboard))
+}
+
+func (handler *handler) GetPublicWidgetQueryRangeV2(rw http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
+ defer cancel()
+
+ id, err := valuer.NewUUID(mux.Vars(r)["id"])
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ panelKey, ok := mux.Vars(r)["key"]
+ if !ok || panelKey == "" {
+ render.Error(rw, errors.New(errors.TypeInvalidInput, dashboardtypes.ErrCodePublicDashboardInvalidInput, "panel key is missing from the path"))
+ return
+ }
+
+ queryRangeResults, err := handler.module.GetPublicWidgetQueryRangeV2(ctx, id, panelKey, r.URL.Query().Get("startTime"), r.URL.Query().Get("endTime"))
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, queryRangeResults)
+}
diff --git a/pkg/types/dashboardtypes/perses_dashboard_data.go b/pkg/types/dashboardtypes/perses_dashboard_data.go
index 16bbf1ddc2..489e001d75 100644
--- a/pkg/types/dashboardtypes/perses_dashboard_data.go
+++ b/pkg/types/dashboardtypes/perses_dashboard_data.go
@@ -7,6 +7,7 @@ import (
"slices"
"unicode/utf8"
+ chparser "github.com/AfterShip/clickhouse-sql-parser/parser"
"github.com/SigNoz/signoz/pkg/errors"
qb "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/perses/spec/go/common"
@@ -109,8 +110,7 @@ func (d *DashboardSpec) validatePanels() error {
}
allowed := allowedQueryKinds[panelKind]
for qi, q := range panel.Spec.Queries {
- queryPath := fmt.Sprintf("%s.spec.queries[%d].spec.plugin", path, qi)
- if err := validateQueryAllowedForPanel(q.Spec.Plugin, allowed, panelKind, queryPath); err != nil {
+ if err := d.validateQuery(qi, q, panelKind, path, allowed); err != nil {
return err
}
}
@@ -118,6 +118,17 @@ func (d *DashboardSpec) validatePanels() error {
return nil
}
+func (d *DashboardSpec) validateQuery(qi int, q Query, panelKind PanelPluginKind, path string, allowed []QueryPluginKind) error {
+ queryPath := fmt.Sprintf("%s.spec.queries[%d].spec.plugin", path, qi)
+ if err := validateQueryAllowedForPanel(q.Spec.Plugin, allowed, panelKind, queryPath); err != nil {
+ return err
+ }
+ if err := validateQueryContent(q, queryPath); err != nil {
+ return err
+ }
+ return nil
+}
+
func validateQueryAllowedForPanel(plugin QueryPlugin, allowed []QueryPluginKind, panelKind PanelPluginKind, path string) error {
compositeSubQueryTypeToPluginKind := map[qb.QueryType]QueryPluginKind{
qb.QueryTypeBuilder: QueryKindBuilder,
@@ -153,6 +164,86 @@ func validateQueryAllowedForPanel(plugin QueryPlugin, allowed []QueryPluginKind,
return nil
}
+// validateQueryContent runs the query-builder type's own validation on the panel's
+// query - whatever its kind - by assembling the same v5 composite query the panel would
+// execute and delegating to it. The rules (aggregations, group by, order by, promql /
+// clickhouse / formula / trace-operator specifics, ...) live on querybuildertypesv5; this
+// only delegates, scoped to the query's request type, so a dashboard cannot persist a
+// query the querier would later reject. Request-type options keep e.g. a list (raw) panel
+// from being forced to carry an aggregation.
+func validateQueryContent(q Query, path string) error {
+ composite, err := q.Spec.Plugin.buildV5CompositeQueryFromPlugin()
+ if err != nil {
+ return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "%s: %s", path, err.Error())
+ }
+ if err := composite.Validate(qb.GetValidationOptions(q.Kind)...); err != nil {
+ return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "%s: %s", path, err.Error())
+ }
+ // Dashboard-write only, not the query-range request, so query-range behaviour is
+ // unchanged: agg_rewriter trims after a comma there; dashboards reject the packing.
+ if err := validateSingleExpressionAggregations(composite); err != nil {
+ return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "%s: %s", path, err.Error())
+ }
+ return nil
+}
+
+// validateSingleExpressionAggregations rejects a logs/traces aggregation that packs
+// several calls into one expression (e.g. "count(), sum(field)"), which the rewriter
+// would silently truncate to the first call.
+func validateSingleExpressionAggregations(composite qb.CompositeQuery) error {
+ for _, envelope := range composite.Queries {
+ switch query := envelope.Spec.(type) {
+ case qb.QueryBuilderQuery[qb.LogAggregation]:
+ for _, agg := range query.Aggregations {
+ if err := ensureSingleExpressionAggregation(agg.Expression); err != nil {
+ return err
+ }
+ }
+ case qb.QueryBuilderQuery[qb.TraceAggregation]:
+ for _, agg := range query.Aggregations {
+ if err := ensureSingleExpressionAggregation(agg.Expression); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ return nil
+}
+
+// ensureSingleExpressionAggregation rejects an expression that parses to more than one
+// SELECT item; exact where a regex count is not (string literals, nesting). Same
+// SELECT-wrap parse as parseFragment in pkg/querybuilder/agg_rewrite.go.
+func ensureSingleExpressionAggregation(expression string) error {
+ wrapped := fmt.Sprintf("SELECT %s", expression)
+ p := chparser.NewParser(wrapped)
+ stmts, err := p.ParseStmts()
+ if err != nil {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "invalid aggregation expression `%s`: unable to parse expression", expression)
+ }
+ if len(stmts) == 0 {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "invalid aggregation expression `%s`: no statements in the expression", expression)
+ }
+ sel, ok := stmts[0].(*chparser.SelectQuery)
+ if !ok {
+ // can't happen cuz wrapped is a SELECT query.
+ return errors.NewInternalf(errors.CodeInternal, "invalid aggregation expression `%s`", expression)
+ }
+ if len(sel.SelectItems) > 1 {
+ // this is the only part that is different from pkg/querybuilder/agg_rewrite.go.
+ return errors.NewInvalidInputf(
+ ErrCodeDashboardInvalidInput,
+ "aggregation expression `%s` must contain a single function call; provide multiple aggregations as separate entries",
+ expression,
+ )
+ }
+ if len(sel.SelectItems) == 0 {
+ // can't happen cuz wrapped is a SELECT query.
+ return errors.NewInternalf(errors.CodeInternal, "invalid aggregation expression `%s`", expression)
+ }
+ return nil
+}
+
+// validateLayouts rejects grid items referencing a panel that doesn't exist.
const maxLayoutsPerDashboard = 500
// validateLayouts validates the dashboard's layouts: bounded section count,
diff --git a/pkg/types/dashboardtypes/perses_dashboard_test.go b/pkg/types/dashboardtypes/perses_dashboard_test.go
index 1ec78874a6..218eb3c4ae 100644
--- a/pkg/types/dashboardtypes/perses_dashboard_test.go
+++ b/pkg/types/dashboardtypes/perses_dashboard_test.go
@@ -1392,11 +1392,23 @@ func TestSpanGaps(t *testing.T) {
}
func TestPanelTypeQueryTypeCompatibility(t *testing.T) {
+ // A panel's query carries the request type implied by the panel kind: list panels
+ // are raw (no aggregation), table-like panels are scalar, the rest time series.
+ requestKind := func(panelKind string) string {
+ switch panelKind {
+ case "signoz/ListPanel":
+ return "raw"
+ case "signoz/TablePanel", "signoz/NumberPanel", "signoz/PieChartPanel", "signoz/HistogramPanel":
+ return "scalar"
+ default:
+ return "time_series"
+ }
+ }
mkQuery := func(panelKind, queryKind, querySpec string) []byte {
return []byte(`{
"panels": {"p1": {"kind": "Panel", "spec": {
"plugin": {"kind": "` + panelKind + `", "spec": {}},
- "queries": [{"kind": "time_series", "spec": {"plugin": {"kind": "` + queryKind + `", "spec": ` + querySpec + `}}}]
+ "queries": [{"kind": "` + requestKind(panelKind) + `", "spec": {"plugin": {"kind": "` + queryKind + `", "spec": ` + querySpec + `}}}]
}}},
"layouts": []
}`)
@@ -1405,7 +1417,7 @@ func TestPanelTypeQueryTypeCompatibility(t *testing.T) {
return []byte(`{
"panels": {"p1": {"kind": "Panel", "spec": {
"plugin": {"kind": "` + panelKind + `", "spec": {}},
- "queries": [{"kind": "time_series", "spec": {"plugin": {"kind": "signoz/CompositeQuery", "spec": {
+ "queries": [{"kind": "` + requestKind(panelKind) + `", "spec": {"plugin": {"kind": "signoz/CompositeQuery", "spec": {
"queries": [{"type": "` + subType + `", "spec": ` + subSpec + `}]
}}}}]
}}},
@@ -1445,6 +1457,45 @@ func TestPanelTypeQueryTypeCompatibility(t *testing.T) {
}
}
+// TestCommaSeparatedAggregationRejectedOnWrite asserts the write path (unmarshalDashboard
+// runs DashboardSpec.Validate) rejects an aggregation that packs several comma-separated
+// calls into one expression, while accepting a single call and a properly pre-split list.
+func TestCommaSeparatedAggregationRejectedOnWrite(t *testing.T) {
+ buildDashboardWithLogsAggregation := func(aggregationsJSON string) []byte {
+ return []byte(`{
+ "panels": {"p1": {"kind": "Panel", "spec": {
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [{"kind": "time_series", "spec": {"plugin": {"kind": "signoz/BuilderQuery", "spec": {
+ "name": "A", "signal": "logs", "aggregations": ` + aggregationsJSON + `
+ }}}}]
+ }}},
+ "layouts": []
+ }`)
+ }
+
+ t.Run("comma-separated expression is rejected", func(t *testing.T) {
+ _, err := unmarshalDashboard(buildDashboardWithLogsAggregation(`[{"expression": "count(), sum(bytes)"}]`))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "single function call")
+ assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
+ })
+
+ t.Run("single-call expression is accepted", func(t *testing.T) {
+ _, err := unmarshalDashboard(buildDashboardWithLogsAggregation(`[{"expression": "count()"}]`))
+ require.NoError(t, err)
+ })
+
+ t.Run("pre-split aggregations are accepted", func(t *testing.T) {
+ _, err := unmarshalDashboard(buildDashboardWithLogsAggregation(`[{"expression": "count()"}, {"expression": "sum(bytes)"}]`))
+ require.NoError(t, err)
+ })
+
+ t.Run("comma inside function args is not mistaken for multiple calls", func(t *testing.T) {
+ _, err := unmarshalDashboard(buildDashboardWithLogsAggregation(`[{"expression": "countIf(day > 10, status)"}]`))
+ require.NoError(t, err)
+ })
+}
+
func TestValidateGridGeometry(t *testing.T) {
tests := []struct {
scenario string
@@ -1628,3 +1679,30 @@ func TestValidateDisplayNameAtMaxLength(t *testing.T) {
_, err := unmarshalDashboard([]byte(`{"display": {"name": "` + atLimit + `"}, "layouts": []}`))
assert.NoError(t, err)
}
+
+func TestEnsureSingleExpressionAggregation(t *testing.T) {
+ testCases := []struct {
+ description string
+ expression string
+ expectRejected bool
+ }{
+ {description: "single call is accepted", expression: "count()", expectRejected: false},
+ {description: "comma-separated calls are rejected", expression: "count(), sum(bytes)", expectRejected: true},
+ {description: "comma inside function args is a single call", expression: "countIf(day > 10, status)", expectRejected: false},
+ {description: "nested function call is a single aggregation", expression: "sum(toFloat64(x))", expectRejected: false},
+ {description: "parenthesis inside a string literal is not a call", expression: "countIf(body LIKE '%(done)%')", expectRejected: false},
+ {description: "closing paren inside a string literal followed by word-paren is not a second call", expression: "countIf(body = 'a)b(c)')", expectRejected: false},
+ {description: "unparseable expression is rejected", expression: "count(", expectRejected: true},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.description, func(t *testing.T) {
+ err := ensureSingleExpressionAggregation(testCase.expression)
+ if testCase.expectRejected {
+ require.Error(t, err)
+ } else {
+ require.NoError(t, err)
+ }
+ })
+ }
+}
diff --git a/pkg/types/dashboardtypes/perses_plugin_wrappers.go b/pkg/types/dashboardtypes/perses_plugin_wrappers.go
index 6578d06742..f44781ec67 100644
--- a/pkg/types/dashboardtypes/perses_plugin_wrappers.go
+++ b/pkg/types/dashboardtypes/perses_plugin_wrappers.go
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/SigNoz/signoz/pkg/errors"
+ qb "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/go-playground/validator/v10"
"github.com/swaggest/jsonschema-go"
@@ -125,6 +126,34 @@ func (QueryPlugin) JSONSchemaOneOf() []any {
}
}
+func (plugin QueryPlugin) buildV5CompositeQueryFromPlugin() (qb.CompositeQuery, error) {
+ switch spec := plugin.Spec.(type) {
+ case *qb.CompositeQuery:
+ if spec == nil {
+ return qb.CompositeQuery{}, errors.Newf(errors.TypeInvalidInput, ErrCodeDashboardInvalidWidgetQuery, "composite query is empty")
+ }
+ return *spec, nil
+ case *BuilderQuerySpec:
+ if spec == nil {
+ return qb.CompositeQuery{}, errors.Newf(errors.TypeInvalidInput, ErrCodeDashboardInvalidWidgetQuery, "builder query is empty")
+ }
+ return wrapEnvelope(qb.QueryTypeBuilder, spec.Spec), nil
+ case *qb.PromQuery:
+ return wrapEnvelope(qb.QueryTypePromQL, *spec), nil
+ case *qb.ClickHouseQuery:
+ return wrapEnvelope(qb.QueryTypeClickHouseSQL, *spec), nil
+ case *qb.QueryBuilderFormula:
+ return wrapEnvelope(qb.QueryTypeFormula, *spec), nil
+ case *qb.QueryBuilderTraceOperator:
+ return wrapEnvelope(qb.QueryTypeTraceOperator, *spec), nil
+ }
+ return qb.CompositeQuery{}, errors.Newf(errors.TypeInvalidInput, ErrCodeDashboardInvalidWidgetQuery, "unsupported query kind %q", plugin.Kind)
+}
+
+func wrapEnvelope(queryType qb.QueryType, spec any) qb.CompositeQuery {
+ return qb.CompositeQuery{Queries: []qb.QueryEnvelope{{Type: queryType, Spec: spec}}}
+}
+
type QueryPluginVariant[S any] struct {
Kind string `json:"kind" required:"true"`
Spec S `json:"spec" required:"true"`
diff --git a/pkg/types/dashboardtypes/perses_public_dashboard.go b/pkg/types/dashboardtypes/perses_public_dashboard.go
new file mode 100644
index 0000000000..60ee3f5659
--- /dev/null
+++ b/pkg/types/dashboardtypes/perses_public_dashboard.go
@@ -0,0 +1,204 @@
+package dashboardtypes
+
+import (
+ "github.com/SigNoz/signoz/pkg/errors"
+ qb "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/SigNoz/signoz/pkg/types/tagtypes"
+)
+
+// ════════════════════════════════════════════════════════════════════════
+// Gettable
+// ════════════════════════════════════════════════════════════════════════
+
+// GettablePublicDashboardDataV2 is the anonymous-facing payload of a v2 dashboard.
+type GettablePublicDashboardDataV2 struct {
+ Dashboard *GettableDashboardV2 `json:"dashboard"`
+ PublicDashboard *GettablePublicDasbhboard `json:"publicDashboard"`
+}
+
+// NewPublicDashboardDataFromDashboardV2 builds the anonymous v2 payload: panel queries
+// and query-variable queries are redacted, and only the body fields v1 exposed (name,
+// metadata, tags, spec) are set.
+func NewPublicDashboardDataFromDashboardV2(dashboard *DashboardV2, publicDashboard *PublicDashboard) *GettablePublicDashboardDataV2 {
+ spec := dashboard.Spec
+ redactPanelQueries(&spec)
+ redactVariableQueries(&spec)
+
+ return &GettablePublicDashboardDataV2{
+ Dashboard: &GettableDashboardV2{
+ DashboardV2MetadataBase: dashboard.DashboardV2MetadataBase,
+ Name: dashboard.Name,
+ Tags: tagtypes.NewGettableTagsFromTags(dashboard.Tags),
+ Spec: spec,
+ },
+ PublicDashboard: &GettablePublicDasbhboard{
+ TimeRangeEnabled: publicDashboard.TimeRangeEnabled,
+ DefaultTimeRange: publicDashboard.DefaultTimeRange,
+ PublicPath: publicDashboard.PublicPath(),
+ },
+ }
+}
+
+// ════════════════════════════════════════════════════════════════════════
+// Redaction
+// ════════════════════════════════════════════════════════════════════════
+
+func redactPanelQueries(spec *DashboardSpec) {
+ panels := make(map[string]*Panel, len(spec.Panels))
+ for key, panel := range spec.Panels {
+ if panel == nil {
+ panels[key] = nil
+ continue
+ }
+ redacted := *panel
+ queries := make([]Query, len(redacted.Spec.Queries))
+ for i, query := range redacted.Spec.Queries {
+ query.Spec.Plugin.Spec = redactQuery(query.Spec.Plugin.Spec)
+ queries[i] = query
+ }
+ redacted.Spec.Queries = queries
+ panels[key] = &redacted
+ }
+ spec.Panels = panels
+}
+
+// redactVariableQueries strips the raw query from query-kind list variables. The
+// query is the same class of secret as a panel query, and the anonymous viewer
+// never runs variable queries. Rebuilds the slice rather than mutating in place:
+// spec shares its Variables backing array with the stored dashboard.
+func redactVariableQueries(spec *DashboardSpec) {
+ variables := make([]Variable, len(spec.Variables))
+ copy(variables, spec.Variables)
+ for i := range variables {
+ list, ok := variables[i].Spec.(*ListVariableSpec)
+ if !ok || list.Plugin.Kind != VariableKindQuery {
+ continue
+ }
+ if _, ok := list.Plugin.Spec.(*QueryVariableSpec); ok {
+ redacted := *list
+ redacted.Plugin.Spec = &QueryVariableSpec{}
+ variables[i].Spec = &redacted
+ }
+ }
+ spec.Variables = variables
+}
+
+func redactQuery(spec any) any {
+ switch s := spec.(type) {
+ case *qb.CompositeQuery:
+ if s == nil {
+ return spec
+ }
+ queries := make([]qb.QueryEnvelope, len(s.Queries))
+ for i, envelope := range s.Queries {
+ envelope.Spec = redactLeafQuery(envelope.Spec)
+ queries[i] = envelope
+ }
+ return &qb.CompositeQuery{Queries: queries}
+ case *BuilderQuerySpec:
+ if s == nil {
+ return spec
+ }
+ return &BuilderQuerySpec{Spec: redactLeafQuery(s.Spec)}
+ case *qb.PromQuery:
+ return redactQueryPtr(s)
+ case *qb.ClickHouseQuery:
+ return redactQueryPtr(s)
+ case *qb.QueryBuilderFormula:
+ return redactQueryPtr(s)
+ case *qb.QueryBuilderTraceOperator:
+ return redactQueryPtr(s)
+ }
+ return spec
+}
+
+func redactQueryPtr[T any](s *T) any {
+ if s == nil {
+ return s
+ }
+ redacted := redactLeafQuery(*s).(T)
+ return &redacted
+}
+
+func redactLeafQuery(spec any) any {
+ switch s := spec.(type) {
+ case qb.QueryBuilderQuery[qb.LogAggregation]:
+ return redactBuilderQuery(s)
+ case qb.QueryBuilderQuery[qb.MetricAggregation]:
+ return redactBuilderQuery(s)
+ case qb.QueryBuilderQuery[qb.TraceAggregation]:
+ return redactBuilderQuery(s)
+ case qb.PromQuery:
+ return qb.PromQuery{Name: s.Name, Legend: s.Legend}
+ case qb.ClickHouseQuery:
+ return qb.ClickHouseQuery{Name: s.Name, Legend: s.Legend}
+ case qb.QueryBuilderFormula:
+ return qb.QueryBuilderFormula{Name: s.Name, Expression: s.Expression, Legend: s.Legend}
+ case qb.QueryBuilderTraceOperator:
+ return qb.QueryBuilderTraceOperator{
+ Name: s.Name,
+ Expression: s.Expression,
+ Aggregations: s.Aggregations,
+ GroupBy: s.GroupBy,
+ Legend: s.Legend,
+ }
+ }
+ return spec
+}
+
+func redactBuilderQuery[T any](q qb.QueryBuilderQuery[T]) qb.QueryBuilderQuery[T] {
+ return qb.QueryBuilderQuery[T]{
+ Name: q.Name,
+ Signal: q.Signal,
+ Source: q.Source,
+ Aggregations: q.Aggregations,
+ GroupBy: q.GroupBy,
+ Legend: q.Legend,
+ }
+}
+
+// ════════════════════════════════════════════════════════════════════════
+// Panel query
+// ════════════════════════════════════════════════════════════════════════
+
+func (d *DashboardV2) GetPanelQuery(startTime, endTime uint64, panelKey string) (*qb.QueryRangeRequest, error) {
+ panel, ok := d.Spec.Panels[panelKey]
+ if !ok || panel == nil {
+ return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeDashboardInvalidInput, "panel with key %q doesn't exist", panelKey)
+ }
+ // Validator guarantees exactly one query per panel.
+ if len(panel.Spec.Queries) != 1 {
+ return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeDashboardInvalidWidgetQuery, "panel %q must have exactly one query", panelKey)
+ }
+
+ query := panel.Spec.Queries[0]
+ composite, err := query.Spec.Plugin.buildV5CompositeQueryFromPlugin()
+ if err != nil {
+ return nil, err
+ }
+
+ // fillGaps lives on the panel visualization; only timeseries and bar chart carry it.
+ fillGaps := false
+ switch panelSpec := panel.Spec.Plugin.Spec.(type) {
+ case *TimeSeriesPanelSpec:
+ if panelSpec != nil {
+ fillGaps = panelSpec.Visualization.FillSpans
+ }
+ case *BarChartPanelSpec:
+ if panelSpec != nil {
+ fillGaps = panelSpec.Visualization.FillSpans
+ }
+ }
+
+ return &qb.QueryRangeRequest{
+ SchemaVersion: "v1",
+ Start: startTime,
+ End: endTime,
+ RequestType: query.Kind,
+ CompositeQuery: composite,
+ FormatOptions: &qb.FormatOptions{
+ FillGaps: fillGaps,
+ FormatTableResultForUI: panel.Spec.Plugin.Kind == PanelKindTable,
+ },
+ }, nil
+}
diff --git a/pkg/types/dashboardtypes/perses_public_dashboard_panel_query_test.go b/pkg/types/dashboardtypes/perses_public_dashboard_panel_query_test.go
new file mode 100644
index 0000000000..431caac0eb
--- /dev/null
+++ b/pkg/types/dashboardtypes/perses_public_dashboard_panel_query_test.go
@@ -0,0 +1,331 @@
+package dashboardtypes
+
+import (
+ "testing"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ qb "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestDashboardV2GetPanelQuery(t *testing.T) {
+ t.Run("returns error when the panel does not exist", func(t *testing.T) {
+ dashboard := &DashboardV2{
+ Spec: DashboardSpec{
+ Panels: map[string]*Panel{
+ "panel-1": {
+ Spec: PanelSpec{
+ Plugin: PanelPlugin{Kind: PanelKindTimeSeries},
+ Queries: []Query{
+ {
+ Kind: qb.RequestTypeTimeSeries,
+ Spec: QuerySpec{
+ Plugin: QueryPlugin{
+ Kind: QueryKindBuilder,
+ Spec: &BuilderQuerySpec{Spec: qb.QueryBuilderQuery[qb.MetricAggregation]{Name: "A"}},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+
+ _, err := dashboard.GetPanelQuery(1, 2, "wrongPanelKey")
+ require.Error(t, err)
+ assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
+ })
+
+ t.Run("returns error when the panel is nil", func(t *testing.T) {
+ dashboard := &DashboardV2{
+ Spec: DashboardSpec{
+ Panels: map[string]*Panel{
+ "panel-1": nil,
+ },
+ },
+ }
+
+ _, err := dashboard.GetPanelQuery(1, 2, "panel-1")
+ require.Error(t, err)
+ assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
+ })
+
+ t.Run("returns error unless the panel has exactly one query", func(t *testing.T) {
+ cases := []struct {
+ description string
+ queries []Query
+ }{
+ {description: "zero queries", queries: nil},
+ {description: "two queries", queries: []Query{{}, {}}},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.description, func(t *testing.T) {
+ dashboard := &DashboardV2{
+ Spec: DashboardSpec{
+ Panels: map[string]*Panel{
+ "panel-1": {
+ Spec: PanelSpec{Queries: tc.queries},
+ },
+ },
+ },
+ }
+
+ _, err := dashboard.GetPanelQuery(1, 2, "panel-1")
+ require.Error(t, err)
+ assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
+ })
+ }
+ })
+
+ t.Run("builds a single-envelope request for a builder query", func(t *testing.T) {
+ builder := qb.QueryBuilderQuery[qb.MetricAggregation]{Name: "A"}
+ dashboard := &DashboardV2{
+ Spec: DashboardSpec{
+ Panels: map[string]*Panel{
+ "panel-1": {
+ Spec: PanelSpec{
+ Plugin: PanelPlugin{Kind: PanelKindTimeSeries},
+ Queries: []Query{
+ {
+ Kind: qb.RequestTypeTimeSeries,
+ Spec: QuerySpec{
+ Plugin: QueryPlugin{
+ Kind: QueryKindBuilder,
+ Spec: &BuilderQuerySpec{Spec: builder},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+
+ req, err := dashboard.GetPanelQuery(100, 200, "panel-1")
+ require.NoError(t, err)
+
+ assert.Equal(t, "v1", req.SchemaVersion)
+ assert.Equal(t, uint64(100), req.Start)
+ assert.Equal(t, uint64(200), req.End)
+ assert.Equal(t, qb.RequestTypeTimeSeries, req.RequestType)
+ require.Len(t, req.CompositeQuery.Queries, 1)
+ assert.Equal(t, qb.QueryTypeBuilder, req.CompositeQuery.Queries[0].Type)
+ assert.Equal(t, builder, req.CompositeQuery.Queries[0].Spec)
+ require.NotNil(t, req.FormatOptions)
+ assert.False(t, req.FormatOptions.FormatTableResultForUI)
+ })
+
+ t.Run("uses a composite query as-is", func(t *testing.T) {
+ composite := &qb.CompositeQuery{Queries: []qb.QueryEnvelope{
+ {Type: qb.QueryTypeBuilder, Spec: qb.QueryBuilderQuery[qb.MetricAggregation]{Name: "A"}},
+ {Type: qb.QueryTypePromQL, Spec: qb.PromQuery{Name: "B"}},
+ }}
+ dashboard := &DashboardV2{
+ Spec: DashboardSpec{
+ Panels: map[string]*Panel{
+ "panel-1": {
+ Spec: PanelSpec{
+ Plugin: PanelPlugin{Kind: PanelKindTimeSeries},
+ Queries: []Query{
+ {
+ Kind: qb.RequestTypeTimeSeries,
+ Spec: QuerySpec{
+ Plugin: QueryPlugin{
+ Kind: QueryKindComposite,
+ Spec: composite,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+
+ req, err := dashboard.GetPanelQuery(1, 2, "panel-1")
+ require.NoError(t, err)
+ assert.Equal(t, composite.Queries, req.CompositeQuery.Queries)
+ })
+
+ t.Run("wraps a leaf query in a single typed envelope", func(t *testing.T) {
+ cases := []struct {
+ description string
+ plugin QueryPlugin
+ expectedType qb.QueryType
+ }{
+ {
+ description: "promql",
+ plugin: QueryPlugin{Kind: QueryKindPromQL, Spec: &qb.PromQuery{Name: "A", Query: "up"}},
+ expectedType: qb.QueryTypePromQL,
+ },
+ {
+ description: "clickhouse",
+ plugin: QueryPlugin{Kind: QueryKindClickHouseSQL, Spec: &qb.ClickHouseQuery{Name: "A", Query: "SELECT 1"}},
+ expectedType: qb.QueryTypeClickHouseSQL,
+ },
+ {
+ description: "formula",
+ plugin: QueryPlugin{Kind: QueryKindFormula, Spec: &qb.QueryBuilderFormula{Name: "F1", Expression: "A / B"}},
+ expectedType: qb.QueryTypeFormula,
+ },
+ {
+ description: "trace operator",
+ plugin: QueryPlugin{Kind: QueryKindTraceOperator, Spec: &qb.QueryBuilderTraceOperator{Name: "T1", Expression: "A => B"}},
+ expectedType: qb.QueryTypeTraceOperator,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.description, func(t *testing.T) {
+ dashboard := &DashboardV2{
+ Spec: DashboardSpec{
+ Panels: map[string]*Panel{
+ "panel-1": {
+ Spec: PanelSpec{
+ Plugin: PanelPlugin{Kind: PanelKindTimeSeries},
+ Queries: []Query{
+ {
+ Kind: qb.RequestTypeTimeSeries,
+ Spec: QuerySpec{Plugin: tc.plugin},
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+
+ req, err := dashboard.GetPanelQuery(1, 2, "panel-1")
+ require.NoError(t, err)
+ require.Len(t, req.CompositeQuery.Queries, 1)
+ assert.Equal(t, tc.expectedType, req.CompositeQuery.Queries[0].Type)
+ })
+ }
+ })
+
+ t.Run("sets FormatTableResultForUI only for table panels", func(t *testing.T) {
+ dashboard := &DashboardV2{
+ Spec: DashboardSpec{
+ Panels: map[string]*Panel{
+ "panel-1": {
+ Spec: PanelSpec{
+ Plugin: PanelPlugin{Kind: PanelKindTable},
+ Queries: []Query{
+ {
+ Kind: qb.RequestTypeScalar,
+ Spec: QuerySpec{
+ Plugin: QueryPlugin{
+ Kind: QueryKindBuilder,
+ Spec: &BuilderQuerySpec{Spec: qb.QueryBuilderQuery[qb.MetricAggregation]{Name: "A"}},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+
+ req, err := dashboard.GetPanelQuery(1, 2, "panel-1")
+ require.NoError(t, err)
+ require.NotNil(t, req.FormatOptions)
+ assert.True(t, req.FormatOptions.FormatTableResultForUI)
+ })
+
+ t.Run("sets FillGaps from the panel visualization", func(t *testing.T) {
+ cases := []struct {
+ description string
+ panelPlugin PanelPlugin
+ expectedFillGaps bool
+ }{
+ {
+ description: "timeseries with fillSpans enabled",
+ panelPlugin: PanelPlugin{Kind: PanelKindTimeSeries, Spec: &TimeSeriesPanelSpec{Visualization: TimeSeriesVisualization{FillSpans: true}}},
+ expectedFillGaps: true,
+ },
+ {
+ description: "timeseries with fillSpans disabled",
+ panelPlugin: PanelPlugin{Kind: PanelKindTimeSeries, Spec: &TimeSeriesPanelSpec{Visualization: TimeSeriesVisualization{FillSpans: false}}},
+ expectedFillGaps: false,
+ },
+ {
+ description: "bar chart with fillSpans enabled",
+ panelPlugin: PanelPlugin{Kind: PanelKindBarChart, Spec: &BarChartPanelSpec{Visualization: BarChartVisualization{FillSpans: true}}},
+ expectedFillGaps: true,
+ },
+ {
+ description: "table panel has no fillSpans",
+ panelPlugin: PanelPlugin{Kind: PanelKindTable, Spec: &TablePanelSpec{}},
+ expectedFillGaps: false,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.description, func(t *testing.T) {
+ dashboard := &DashboardV2{
+ Spec: DashboardSpec{
+ Panels: map[string]*Panel{
+ "panel-1": {
+ Spec: PanelSpec{
+ Plugin: tc.panelPlugin,
+ Queries: []Query{
+ {
+ Kind: qb.RequestTypeTimeSeries,
+ Spec: QuerySpec{
+ Plugin: QueryPlugin{
+ Kind: QueryKindBuilder,
+ Spec: &BuilderQuerySpec{Spec: qb.QueryBuilderQuery[qb.MetricAggregation]{Name: "A"}},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+
+ req, err := dashboard.GetPanelQuery(1, 2, "panel-1")
+ require.NoError(t, err)
+ require.NotNil(t, req.FormatOptions)
+ assert.Equal(t, tc.expectedFillGaps, req.FormatOptions.FillGaps)
+ })
+ }
+ })
+
+ t.Run("returns error for an unsupported plugin spec", func(t *testing.T) {
+ dashboard := &DashboardV2{
+ Spec: DashboardSpec{
+ Panels: map[string]*Panel{
+ "panel-1": {
+ Spec: PanelSpec{
+ Plugin: PanelPlugin{Kind: PanelKindTimeSeries},
+ Queries: []Query{
+ {
+ Kind: qb.RequestTypeTimeSeries,
+ Spec: QuerySpec{
+ Plugin: QueryPlugin{
+ Kind: QueryKindBuilder,
+ Spec: "not-a-query",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+
+ _, err := dashboard.GetPanelQuery(1, 2, "panel-1")
+ require.Error(t, err)
+ assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
+ })
+}
diff --git a/pkg/types/dashboardtypes/perses_public_dashboard_redaction_test.go b/pkg/types/dashboardtypes/perses_public_dashboard_redaction_test.go
new file mode 100644
index 0000000000..9c2e732932
--- /dev/null
+++ b/pkg/types/dashboardtypes/perses_public_dashboard_redaction_test.go
@@ -0,0 +1,240 @@
+package dashboardtypes
+
+import (
+ "testing"
+ "time"
+
+ qb "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"
+ "github.com/perses/spec/go/dashboard/variable"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestRedactLeafQuery(t *testing.T) {
+ t.Run("builder query drops filter, having, limit and keeps display fields", func(t *testing.T) {
+ input := qb.QueryBuilderQuery[qb.MetricAggregation]{
+ Name: "A",
+ Signal: telemetrytypes.SignalMetrics,
+ Aggregations: []qb.MetricAggregation{{MetricName: "system_cpu_usage"}},
+ GroupBy: []qb.GroupByKey{{}},
+ Legend: "cpu",
+ Disabled: true,
+ StepInterval: qb.Step{Duration: time.Minute},
+ Filter: &qb.Filter{Expression: "service.name = 'checkout'"},
+ Having: &qb.Having{},
+ Limit: 100,
+ }
+
+ redacted, ok := redactLeafQuery(input).(qb.QueryBuilderQuery[qb.MetricAggregation])
+ require.True(t, ok)
+
+ // dropped (not in the v1 whitelist)
+ assert.Nil(t, redacted.Filter)
+ assert.Nil(t, redacted.Having)
+ assert.Zero(t, redacted.Limit)
+ assert.Zero(t, redacted.StepInterval)
+ assert.False(t, redacted.Disabled)
+
+ // kept (display)
+ assert.Equal(t, "A", redacted.Name)
+ assert.Equal(t, telemetrytypes.SignalMetrics, redacted.Signal)
+ assert.Equal(t, "cpu", redacted.Legend)
+ require.Len(t, redacted.Aggregations, 1)
+ assert.Equal(t, "system_cpu_usage", redacted.Aggregations[0].MetricName)
+ assert.Len(t, redacted.GroupBy, 1)
+ })
+
+ t.Run("promql query drops the raw query, step and disabled", func(t *testing.T) {
+ redacted, ok := redactLeafQuery(qb.PromQuery{
+ Name: "A",
+ Query: "sum(rate(http_requests_total[5m]))",
+ Step: qb.Step{Duration: time.Minute},
+ Disabled: true,
+ Legend: "rps",
+ }).(qb.PromQuery)
+ require.True(t, ok)
+
+ assert.Empty(t, redacted.Query)
+ assert.Zero(t, redacted.Step)
+ assert.False(t, redacted.Disabled)
+ assert.Equal(t, "A", redacted.Name)
+ assert.Equal(t, "rps", redacted.Legend)
+ })
+
+ t.Run("clickhouse query drops the raw query string", func(t *testing.T) {
+ redacted, ok := redactLeafQuery(qb.ClickHouseQuery{
+ Name: "A",
+ Query: "SELECT * FROM signoz_logs WHERE user = 'admin'",
+ Legend: "logs",
+ }).(qb.ClickHouseQuery)
+ require.True(t, ok)
+
+ assert.Empty(t, redacted.Query)
+ assert.Equal(t, "A", redacted.Name)
+ assert.Equal(t, "logs", redacted.Legend)
+ })
+
+ t.Run("formula keeps its expression but drops limit and having", func(t *testing.T) {
+ redacted, ok := redactLeafQuery(qb.QueryBuilderFormula{
+ Name: "F1",
+ Expression: "A / B",
+ Legend: "ratio",
+ Limit: 50,
+ Having: &qb.Having{},
+ }).(qb.QueryBuilderFormula)
+ require.True(t, ok)
+
+ assert.Equal(t, "A / B", redacted.Expression)
+ assert.Equal(t, "F1", redacted.Name)
+ assert.Equal(t, "ratio", redacted.Legend)
+ assert.Zero(t, redacted.Limit)
+ assert.Nil(t, redacted.Having)
+ })
+
+ t.Run("trace operator drops filter but keeps expression and aggregations", func(t *testing.T) {
+ redacted, ok := redactLeafQuery(qb.QueryBuilderTraceOperator{
+ Name: "T1",
+ Expression: "A => B",
+ Aggregations: []qb.TraceAggregation{{}},
+ Legend: "spans",
+ Filter: &qb.Filter{Expression: "http.status_code = 500"},
+ ReturnSpansFrom: "A",
+ Limit: 10,
+ }).(qb.QueryBuilderTraceOperator)
+ require.True(t, ok)
+
+ assert.Nil(t, redacted.Filter)
+ assert.Empty(t, redacted.ReturnSpansFrom)
+ assert.Zero(t, redacted.Limit)
+ assert.Equal(t, "A => B", redacted.Expression)
+ assert.Equal(t, "T1", redacted.Name)
+ assert.Len(t, redacted.Aggregations, 1)
+ })
+
+ t.Run("unknown value is returned unchanged", func(t *testing.T) {
+ assert.Equal(t, "passthrough", redactLeafQuery("passthrough"))
+ })
+}
+
+func TestRedactQueryPluginWrappers(t *testing.T) {
+ t.Run("builder plugin pointer is redacted and stays a pointer", func(t *testing.T) {
+ plugin := &BuilderQuerySpec{Spec: qb.QueryBuilderQuery[qb.LogAggregation]{
+ Name: "A",
+ Filter: &qb.Filter{Expression: "body contains 'secret'"},
+ }}
+
+ result, ok := redactQuery(plugin).(*BuilderQuerySpec)
+ require.True(t, ok)
+
+ builder, ok := result.Spec.(qb.QueryBuilderQuery[qb.LogAggregation])
+ require.True(t, ok)
+ assert.Nil(t, builder.Filter)
+ assert.Equal(t, "A", builder.Name)
+ })
+
+ t.Run("composite plugin redacts every sub-query envelope", func(t *testing.T) {
+ composite := &qb.CompositeQuery{Queries: []qb.QueryEnvelope{
+ {Type: qb.QueryTypeBuilder, Spec: qb.QueryBuilderQuery[qb.MetricAggregation]{Name: "A", Filter: &qb.Filter{Expression: "x = 1"}}},
+ {Type: qb.QueryTypePromQL, Spec: qb.PromQuery{Name: "B", Query: "up"}},
+ }}
+
+ result, ok := redactQuery(composite).(*qb.CompositeQuery)
+ require.True(t, ok)
+ require.Len(t, result.Queries, 2)
+
+ builder, ok := result.Queries[0].Spec.(qb.QueryBuilderQuery[qb.MetricAggregation])
+ require.True(t, ok)
+ assert.Nil(t, builder.Filter)
+
+ prom, ok := result.Queries[1].Spec.(qb.PromQuery)
+ require.True(t, ok)
+ assert.Empty(t, prom.Query)
+ })
+
+ t.Run("promql plugin pointer drops the raw query", func(t *testing.T) {
+ result, ok := redactQuery(&qb.PromQuery{Name: "A", Query: "up"}).(*qb.PromQuery)
+ require.True(t, ok)
+ assert.Empty(t, result.Query)
+ assert.Equal(t, "A", result.Name)
+ })
+
+ t.Run("nil composite pointer is returned unchanged without panicking", func(t *testing.T) {
+ var nilComposite *qb.CompositeQuery
+ assert.Equal(t, nilComposite, redactQuery(nilComposite))
+ })
+
+ t.Run("unknown plugin spec is returned unchanged", func(t *testing.T) {
+ assert.Equal(t, 42, redactQuery(42))
+ })
+}
+
+func TestRedactPanelQueries(t *testing.T) {
+ t.Run("redacts panel queries without mutating the source spec", func(t *testing.T) {
+ sourcePlugin := &BuilderQuerySpec{Spec: qb.QueryBuilderQuery[qb.MetricAggregation]{
+ Name: "A",
+ Filter: &qb.Filter{Expression: "service.name = 'payments'"},
+ }}
+ sourcePanel := &Panel{Spec: PanelSpec{
+ Queries: []Query{{Spec: QuerySpec{Plugin: QueryPlugin{Kind: QueryKindBuilder, Spec: sourcePlugin}}}},
+ }}
+ spec := DashboardSpec{Panels: map[string]*Panel{"panel-1": sourcePanel}}
+
+ redactPanelQueries(&spec)
+
+ // redacted output has no filter
+ redactedPanel := spec.Panels["panel-1"]
+ require.NotNil(t, redactedPanel)
+ redactedBuilder := redactedPanel.Spec.Queries[0].Spec.Plugin.Spec.(*BuilderQuerySpec).Spec.(qb.QueryBuilderQuery[qb.MetricAggregation])
+ assert.Nil(t, redactedBuilder.Filter)
+
+ // source is untouched: original plugin still carries the filter
+ sourceBuilder := sourcePlugin.Spec.(qb.QueryBuilderQuery[qb.MetricAggregation])
+ require.NotNil(t, sourceBuilder.Filter)
+ assert.Equal(t, "service.name = 'payments'", sourceBuilder.Filter.Expression)
+ assert.NotSame(t, sourcePanel, redactedPanel)
+ })
+
+ t.Run("preserves nil panels without panicking", func(t *testing.T) {
+ spec := DashboardSpec{Panels: map[string]*Panel{"panel-1": nil}}
+
+ redactPanelQueries(&spec)
+
+ panel, ok := spec.Panels["panel-1"]
+ assert.True(t, ok)
+ assert.Nil(t, panel)
+ })
+}
+
+func TestRedactVariableQueries(t *testing.T) {
+ // Spec fields are pointers (*ListVariableSpec, *QueryVariableSpec) to match what
+ // the store produces after JSON decode; value types would slip past the type
+ // assertions in redactVariableQueries.
+ t.Run("drops the query-variable query without mutating the source", func(t *testing.T) {
+ source := &ListVariableSpec{
+ Name: "namespace",
+ Plugin: VariablePlugin{Kind: VariableKindQuery, Spec: &QueryVariableSpec{QueryValue: "SELECT DISTINCT namespace FROM secret_table"}},
+ }
+ spec := DashboardSpec{Variables: []Variable{{Kind: variable.KindList, Spec: source}}}
+
+ redactVariableQueries(&spec)
+
+ redacted := spec.Variables[0].Spec.(*ListVariableSpec)
+ assert.Empty(t, redacted.Plugin.Spec.(*QueryVariableSpec).QueryValue)
+ assert.Equal(t, "namespace", redacted.Name)
+ // source pointee is untouched
+ assert.Equal(t, "SELECT DISTINCT namespace FROM secret_table", source.Plugin.Spec.(*QueryVariableSpec).QueryValue)
+ })
+
+ t.Run("leaves non-query variables untouched", func(t *testing.T) {
+ spec := DashboardSpec{Variables: []Variable{
+ {Kind: variable.KindList, Spec: &ListVariableSpec{Name: "signal", Plugin: VariablePlugin{Kind: VariableKindDynamic, Spec: &DynamicVariableSpec{Name: "service.name", Signal: telemetrytypes.SignalTraces}}}},
+ {Kind: variable.KindList, Spec: &ListVariableSpec{Name: "env", Plugin: VariablePlugin{Kind: VariableKindCustom, Spec: &CustomVariableSpec{CustomValue: "prod,staging"}}}},
+ }}
+
+ redactVariableQueries(&spec)
+
+ assert.Equal(t, "service.name", spec.Variables[0].Spec.(*ListVariableSpec).Plugin.Spec.(*DynamicVariableSpec).Name)
+ assert.Equal(t, "prod,staging", spec.Variables[1].Spec.(*ListVariableSpec).Plugin.Spec.(*CustomVariableSpec).CustomValue)
+ })
+}
diff --git a/pkg/types/dashboardtypes/public_dashboard.go b/pkg/types/dashboardtypes/public_dashboard.go
index 682f893c63..5446dab5d3 100644
--- a/pkg/types/dashboardtypes/public_dashboard.go
+++ b/pkg/types/dashboardtypes/public_dashboard.go
@@ -2,6 +2,7 @@ package dashboardtypes
import (
"encoding/json"
+ "strconv"
"time"
"github.com/SigNoz/signoz/pkg/errors"
@@ -212,6 +213,30 @@ func (typ *PublicDashboard) PublicPath() string {
return "/public/dashboard/" + typ.ID.StringValue()
}
+// ResolveTimeRange returns the [start, end] window in epoch millis for a public
+// widget/panel query: the caller-supplied range when the dashboard allows it,
+// otherwise now minus the configured default range.
+func (typ *PublicDashboard) ResolveTimeRange(startTimeRaw, endTimeRaw string) (uint64, uint64, error) {
+ if typ.TimeRangeEnabled {
+ startTime, err := strconv.ParseUint(startTimeRaw, 10, 64)
+ if err != nil {
+ return 0, 0, errors.New(errors.TypeInvalidInput, ErrCodePublicDashboardInvalidInput, "invalid startTime")
+ }
+ endTime, err := strconv.ParseUint(endTimeRaw, 10, 64)
+ if err != nil {
+ return 0, 0, errors.New(errors.TypeInvalidInput, ErrCodePublicDashboardInvalidInput, "invalid endTime")
+ }
+ return startTime, endTime, nil
+ }
+
+ timeRange, err := time.ParseDuration(typ.DefaultTimeRange)
+ if err != nil {
+ return 0, 0, errors.WrapInternalf(err, errors.CodeInternal, "stored defaultTimeRange %q is not a valid duration", typ.DefaultTimeRange)
+ }
+ now := time.Now()
+ return uint64(now.Add(-timeRange).UnixMilli()), uint64(now.UnixMilli()), nil
+}
+
func (typ *PostablePublicDashboard) UnmarshalJSON(data []byte) error {
type alias PostablePublicDashboard
var temp alias
diff --git a/pkg/types/dashboardtypes/public_dashboard_test.go b/pkg/types/dashboardtypes/public_dashboard_test.go
new file mode 100644
index 0000000000..e2e679f538
--- /dev/null
+++ b/pkg/types/dashboardtypes/public_dashboard_test.go
@@ -0,0 +1,117 @@
+package dashboardtypes
+
+import (
+ "testing"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestPublicDashboardResolveTimeRange(t *testing.T) {
+ t.Run("returns the explicit range when time range is enabled", func(t *testing.T) {
+ cases := []struct {
+ description string
+ startTimeRaw string
+ endTimeRaw string
+ expectedStart uint64
+ expectedEnd uint64
+ }{
+ {
+ description: "valid epoch millis",
+ startTimeRaw: "1700000000000",
+ endTimeRaw: "1700000600000",
+ expectedStart: 1700000000000,
+ expectedEnd: 1700000600000,
+ },
+ {
+ description: "zero start is allowed",
+ startTimeRaw: "0",
+ endTimeRaw: "1700000600000",
+ expectedStart: 0,
+ expectedEnd: 1700000600000,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.description, func(t *testing.T) {
+ publicDashboard := &PublicDashboard{TimeRangeEnabled: true}
+
+ startTime, endTime, err := publicDashboard.ResolveTimeRange(tc.startTimeRaw, tc.endTimeRaw)
+ require.NoError(t, err)
+ assert.Equal(t, tc.expectedStart, startTime)
+ assert.Equal(t, tc.expectedEnd, endTime)
+ })
+ }
+ })
+
+ t.Run("rejects an invalid explicit range when time range is enabled", func(t *testing.T) {
+ cases := []struct {
+ description string
+ startTimeRaw string
+ endTimeRaw string
+ }{
+ {description: "non-numeric startTime", startTimeRaw: "abc", endTimeRaw: "1700000600000"},
+ {description: "empty startTime", startTimeRaw: "", endTimeRaw: "1700000600000"},
+ {description: "negative startTime", startTimeRaw: "-1", endTimeRaw: "1700000600000"},
+ {description: "non-numeric endTime", startTimeRaw: "1700000000000", endTimeRaw: "xyz"},
+ {description: "empty endTime", startTimeRaw: "1700000000000", endTimeRaw: ""},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.description, func(t *testing.T) {
+ publicDashboard := &PublicDashboard{TimeRangeEnabled: true}
+
+ _, _, err := publicDashboard.ResolveTimeRange(tc.startTimeRaw, tc.endTimeRaw)
+ assert.Error(t, err)
+ assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
+ })
+ }
+ })
+
+ t.Run("derives the range from now and the default when time range is disabled", func(t *testing.T) {
+ cases := []struct {
+ description string
+ defaultTimeRange string
+ expectedWidthMS uint64
+ }{
+ {description: "one hour", defaultTimeRange: "1h", expectedWidthMS: uint64(time.Hour.Milliseconds())},
+ {description: "thirty minutes", defaultTimeRange: "30m", expectedWidthMS: uint64((30 * time.Minute).Milliseconds())},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.description, func(t *testing.T) {
+ publicDashboard := &PublicDashboard{TimeRangeEnabled: false, DefaultTimeRange: tc.defaultTimeRange}
+
+ before := uint64(time.Now().UnixMilli())
+ startTime, endTime, err := publicDashboard.ResolveTimeRange("ignored", "ignored")
+ after := uint64(time.Now().UnixMilli())
+
+ require.NoError(t, err)
+ // end is "now"; both bounds share the same instant, so the width is exact.
+ assert.GreaterOrEqual(t, endTime, before)
+ assert.LessOrEqual(t, endTime, after)
+ assert.Equal(t, tc.expectedWidthMS, endTime-startTime)
+ })
+ }
+ })
+
+ t.Run("ignores caller-supplied bounds when time range is disabled", func(t *testing.T) {
+ publicDashboard := &PublicDashboard{TimeRangeEnabled: false, DefaultTimeRange: "1h"}
+
+ startTime, endTime, err := publicDashboard.ResolveTimeRange("123", "456")
+ require.NoError(t, err)
+ assert.NotEqual(t, uint64(123), startTime)
+ assert.NotEqual(t, uint64(456), endTime)
+ assert.Equal(t, uint64(time.Hour.Milliseconds()), endTime-startTime)
+ })
+
+ t.Run("returns an internal error for an unparseable stored default range", func(t *testing.T) {
+ publicDashboard := &PublicDashboard{TimeRangeEnabled: false, DefaultTimeRange: "not-a-duration"}
+
+ _, _, err := publicDashboard.ResolveTimeRange("", "")
+ assert.Error(t, err)
+ assert.True(t, errors.Ast(err, errors.TypeInternal))
+ })
+}
diff --git a/pkg/types/dashboardtypes/testdata/perses.json b/pkg/types/dashboardtypes/testdata/perses.json
index d211f4e0e8..6927724178 100644
--- a/pkg/types/dashboardtypes/testdata/perses.json
+++ b/pkg/types/dashboardtypes/testdata/perses.json
@@ -652,6 +652,7 @@
"type": "builder_trace_operator",
"spec": {
"name": "T1",
+ "expression": "A => B",
"aggregations": [
{
"expression": "count()",
diff --git a/tests/integration/tests/dashboard/03_v2_dashboard.py b/tests/integration/tests/dashboard/03_v2_dashboard.py
index 7fa8943c5c..2e3200f4c3 100644
--- a/tests/integration/tests/dashboard/03_v2_dashboard.py
+++ b/tests/integration/tests/dashboard/03_v2_dashboard.py
@@ -1403,3 +1403,83 @@ def test_dashboard_v2_get_by_metric_name(
assert sorted(by_dashboard[d1_id]) == ["D1 builder target"]
assert sorted(by_dashboard[d2_id]) == ["D2 clickhouse target", "D2 promql target"]
assert sorted(by_dashboard[d3_id]) == ["D3 promql target"]
+
+
+# ─── aggregation expression validation ───────────────────────────────────────
+
+
+def test_dashboard_v2_rejects_comma_separated_aggregation(
+ signoz: SigNoz,
+ create_user_admin: Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """The querier never splits aggregation expressions, so each aggregation entry must
+ be a single function call. A comma-separated expression ("count(), sum(...)") is
+ rejected at create time; the pre-split form of the same panel is accepted."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ def make_dashboard(aggregations: list[dict]) -> dict:
+ return {
+ "schemaVersion": "v6",
+ "name": f"agg-{uuid.uuid4().hex[:8]}",
+ "tags": [],
+ "spec": {
+ "display": {"name": "Aggregation"},
+ "panels": {
+ "p-agg": {
+ "kind": "Panel",
+ "spec": {
+ "display": {"name": "agg"},
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [
+ {
+ "kind": "time_series",
+ "spec": {
+ "plugin": {
+ "kind": "signoz/BuilderQuery",
+ "spec": {"name": "A", "signal": "logs", "aggregations": aggregations},
+ }
+ },
+ }
+ ],
+ },
+ }
+ },
+ },
+ }
+
+ # a single comma-separated expression is rejected
+ rejected = requests.post(
+ signoz.self.host_configs["8080"].get(BASE_URL),
+ json=make_dashboard([{"expression": "count(), sum(latency_ms)"}]),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert rejected.status_code == HTTPStatus.BAD_REQUEST, rejected.text
+ assert "single function call" in rejected.text, rejected.text
+
+ # the pre-split form of the same panel is accepted
+ accepted = requests.post(
+ signoz.self.host_configs["8080"].get(BASE_URL),
+ json=make_dashboard([{"expression": "count()"}, {"expression": "sum(latency_ms)"}]),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert accepted.status_code == HTTPStatus.CREATED, accepted.text
+
+ # a single call whose string literal contains parentheses is accepted (the check
+ # parses rather than counting "word(", so it does not mistake ')...(' for a second call)
+ literal_parens = requests.post(
+ signoz.self.host_configs["8080"].get(BASE_URL),
+ json=make_dashboard([{"expression": "countIf(body = 'a)b(c)')"}]),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert literal_parens.status_code == HTTPStatus.CREATED, literal_parens.text
+
+ for dashboard_id in (accepted.json()["data"]["id"], literal_parens.json()["data"]["id"]):
+ requests.delete(
+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{dashboard_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
diff --git a/tests/integration/tests/dashboard/05_v2_public_dashboard.py b/tests/integration/tests/dashboard/05_v2_public_dashboard.py
new file mode 100644
index 0000000000..ae4ece5206
--- /dev/null
+++ b/tests/integration/tests/dashboard/05_v2_public_dashboard.py
@@ -0,0 +1,251 @@
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+from http import HTTPStatus
+
+import requests
+from wiremock.resources.mappings import Mapping
+
+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD, add_license
+from fixtures.metrics import Metrics
+from fixtures.types import Operation, SigNoz, TestContainerDocker
+
+V2_BASE_URL = "/api/v2/dashboards"
+PANEL_KEY = "24e2697b"
+
+
+def test_apply_license(
+ signoz: SigNoz,
+ create_user_admin: Operation, # pylint: disable=unused-argument
+ make_http_mocks: Callable[[TestContainerDocker, list[Mapping]], None],
+ get_token: Callable[[str, str], str],
+) -> None:
+ """
+ Public dashboards are a licensed feature, so a license must be present.
+ """
+ add_license(signoz, make_http_mocks, get_token)
+
+
+def test_public_dashboard_v2(
+ signoz: SigNoz,
+ create_user_admin: Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ insert_metrics: Callable[[list[Metrics]], None],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ # Insert metric data so the panel query resolves to a result.
+ now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
+ insert_metrics(
+ [
+ Metrics(
+ metric_name="system.cpu.time",
+ labels={"service.name": "sampleapp"},
+ timestamp=now - timedelta(minutes=minutes),
+ value=value,
+ temporality="Cumulative",
+ )
+ for minutes, value in ((5, 100.0), (3, 200.0), (1, 300.0))
+ ]
+ )
+
+ # Create a v2 dashboard with one panel whose builder query carries a filter,
+ # so we can assert the filter is redacted from the anonymous payload.
+ create_response = requests.post(
+ signoz.self.host_configs["8080"].get(V2_BASE_URL),
+ json={
+ "schemaVersion": "v6",
+ "name": "v2-public-sample",
+ "tags": [{"key": "team", "value": "pulse"}],
+ "spec": {
+ "display": {"name": "Sample Dashboard", "description": "Used for integration tests"},
+ "duration": "1h",
+ "variables": [
+ {
+ "kind": "ListVariable",
+ "spec": {
+ "name": "host.name",
+ "display": {"name": "Host Name"},
+ "plugin": {
+ "kind": "signoz/QueryVariable",
+ "spec": {"queryValue": "SELECT JSONExtractString(labels, 'host.name') AS `host.name` FROM signoz_metrics.distributed_time_series_v4_1day WHERE metric_name = 'system.cpu.time' GROUP BY `host.name`"},
+ },
+ },
+ }
+ ],
+ "panels": {
+ PANEL_KEY: {
+ "kind": "Panel",
+ "spec": {
+ "display": {"name": "total"},
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {"visualization": {"fillSpans": True}}},
+ "queries": [
+ {
+ "kind": "time_series",
+ "spec": {
+ "plugin": {
+ "kind": "signoz/BuilderQuery",
+ "spec": {
+ "name": "A",
+ "signal": "metrics",
+ "aggregations": [
+ {
+ "metricName": "system.cpu.time",
+ "reduceTo": "sum",
+ "spaceAggregation": "sum",
+ "timeAggregation": "rate",
+ }
+ ],
+ "filter": {"expression": "service.name = 'sampleapp'"},
+ "groupBy": [{"name": "service.name", "fieldDataType": "string", "fieldContext": "tag"}],
+ },
+ }
+ },
+ }
+ ],
+ },
+ }
+ },
+ "layouts": [
+ {
+ "kind": "Grid",
+ "spec": {
+ "items": [
+ {
+ "x": 0,
+ "y": 0,
+ "width": 6,
+ "height": 6,
+ "content": {"$ref": f"#/spec/panels/{PANEL_KEY}"},
+ }
+ ]
+ },
+ }
+ ],
+ },
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert create_response.status_code == HTTPStatus.CREATED, create_response.text
+ dashboard_id = create_response.json()["data"]["id"]
+
+ # Enable public sharing (the public-config endpoint is shape-agnostic, still v1).
+ public_response = requests.post(
+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{dashboard_id}/public"),
+ json={"timeRangeEnabled": True, "defaultTimeRange": "10m"},
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert public_response.status_code == HTTPStatus.CREATED, public_response.text
+
+ config_response = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{dashboard_id}/public"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert config_response.status_code == HTTPStatus.OK, config_response.text
+ public_id = config_response.json()["data"]["publicPath"].split("/public/dashboard/")[-1]
+
+ # ── anonymous public data (no Authorization header) ──────────────────────
+ data_response = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/public/dashboards/{public_id}"),
+ timeout=5,
+ )
+ assert data_response.status_code == HTTPStatus.OK, data_response.text
+ body = data_response.json()
+ assert body["status"] == "success"
+
+ dashboard = body["data"]["dashboard"]
+ assert dashboard["schemaVersion"] == "v6"
+ assert dashboard["spec"]["display"]["name"] == "Sample Dashboard"
+ assert {"key": "team", "value": "pulse"} in dashboard["tags"]
+
+ # Identity/audit fields are not exposed to anonymous viewers.
+ assert dashboard["createdBy"] == ""
+ assert dashboard["updatedBy"] == ""
+
+ # The public config is echoed back.
+ assert body["data"]["publicDashboard"]["timeRangeEnabled"] is True
+
+ # The builder query is redacted: the filter is gone, display fields remain.
+ builder = dashboard["spec"]["panels"][PANEL_KEY]["spec"]["queries"][0]["spec"]["plugin"]["spec"]
+ assert "filter" not in builder
+ assert builder["name"] == "A"
+ assert builder["signal"] == "metrics"
+ assert builder["aggregations"][0]["metricName"] == "system.cpu.time"
+ assert builder["groupBy"][0]["name"] == "service.name"
+
+ # The query variable's query is redacted; its identity remains.
+ variable = dashboard["spec"]["variables"][0]["spec"]
+ assert variable["name"] == "host.name"
+ assert variable["plugin"]["kind"] == "signoz/QueryVariable"
+ assert variable["plugin"]["spec"]["queryValue"] == ""
+
+ # ── anonymous panel query range ──────────────────────────────────────────
+ start_time = int((now - timedelta(minutes=15)).timestamp() * 1000)
+ end_time = int(now.timestamp() * 1000)
+
+ query_response = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/public/dashboards/{public_id}/panels/{PANEL_KEY}/query_range"),
+ params={"startTime": start_time, "endTime": end_time},
+ timeout=10,
+ )
+ assert query_response.status_code == HTTPStatus.OK, query_response.text
+ query_body = query_response.json()
+ assert query_body["status"] == "success"
+
+ # The inserted metric is returned as a time series for query "A".
+ result = query_body["data"]
+ assert result["type"] == "time_series"
+ results = result["data"]["results"]
+ result_a = next((r for r in results if r.get("queryName") == "A"), None)
+ assert result_a is not None, results
+ series = result_a["aggregations"][0]["series"]
+ assert len(series) >= 1, result_a
+ assert len(series[0]["values"]) >= 1, series[0]
+
+ # With timeRangeEnabled, the bounds are required.
+ missing_range = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/public/dashboards/{public_id}/panels/{PANEL_KEY}/query_range"),
+ timeout=5,
+ )
+ assert missing_range.status_code == HTTPStatus.BAD_REQUEST, missing_range.text
+
+ # An unknown panel key is rejected.
+ unknown_panel = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/public/dashboards/{public_id}/panels/does-not-exist/query_range"),
+ params={"startTime": start_time, "endTime": end_time},
+ timeout=5,
+ )
+ assert unknown_panel.status_code == HTTPStatus.BAD_REQUEST, unknown_panel.text
+
+ # A bogus public id is rejected before any data is served.
+ bogus = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/public/dashboards/not-a-real-id/panels/{PANEL_KEY}/query_range"),
+ params={"startTime": start_time, "endTime": end_time},
+ timeout=5,
+ )
+ assert bogus.status_code >= HTTPStatus.BAD_REQUEST
+
+ # ── deleting the dashboard removes public access ─────────────────────────
+ # DeleteV2 drops the public-config row in the same transaction, so the public
+ # id no longer resolves to a dashboard.
+ delete_response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{dashboard_id}"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert delete_response.status_code == HTTPStatus.NO_CONTENT, delete_response.text
+
+ deleted_data = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/public/dashboards/{public_id}"),
+ timeout=5,
+ )
+ assert deleted_data.status_code == HTTPStatus.NOT_FOUND, deleted_data.text
+
+ deleted_query = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/public/dashboards/{public_id}/panels/{PANEL_KEY}/query_range"),
+ params={"startTime": start_time, "endTime": end_time},
+ timeout=5,
+ )
+ assert deleted_query.status_code == HTTPStatus.NOT_FOUND, deleted_query.text