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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat: enable FGA for dashboards and their public config (#12408)
Naman Vermae42e42ee71b7
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex 133e46e3f1..f3e4f8f63d 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -10247,9 +10247,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - ADMIN+ - dashboard:update- tokenizer:- - ADMIN+ - dashboard:updatesummary: Delete public dashboardtags:- dashboard@@ -10298,9 +10298,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - ADMIN+ - dashboard:read- tokenizer:- - ADMIN+ - dashboard:readsummary: Get public dashboardtags:- dashboard@@ -10355,9 +10355,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - ADMIN+ - dashboard:update- tokenizer:- - ADMIN+ - dashboard:updatesummary: Create public dashboardtags:- dashboard@@ -10399,9 +10399,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - ADMIN+ - dashboard:update- tokenizer:- - ADMIN+ - dashboard:updatesummary: Update public dashboardtags:- dashboard@@ -14739,9 +14739,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - VIEWER+ - dashboard:list- tokenizer:- - VIEWER+ - dashboard:listsummary: List dashboard saved viewstags:- dashboard@@ -14796,9 +14796,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:list- tokenizer:- - EDITOR+ - dashboard:listsummary: Create dashboard saved viewtags:- dashboard@@ -14849,9 +14849,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:list- tokenizer:- - EDITOR+ - dashboard:listsummary: Delete dashboard saved viewtags:- dashboard@@ -14917,9 +14917,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:list- tokenizer:- - EDITOR+ - dashboard:listsummary: Update dashboard saved viewtags:- dashboard@@ -14994,9 +14994,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - VIEWER+ - dashboard:list- tokenizer:- - VIEWER+ - dashboard:listsummary: List dashboards (v2)tags:- dashboard@@ -15051,9 +15051,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:create- tokenizer:- - EDITOR+ - dashboard:createsummary: Create dashboard (v2)tags:- dashboard@@ -15104,9 +15104,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:delete- tokenizer:- - EDITOR+ - dashboard:deletesummary: Delete dashboard (v2)tags:- dashboard@@ -15167,9 +15167,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - VIEWER+ - dashboard:read- tokenizer:- - VIEWER+ - dashboard:readsummary: Get dashboard (v2)tags:- dashboard@@ -15241,9 +15241,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:update- tokenizer:- - EDITOR+ - dashboard:updatesummary: Patch dashboard (v2)tags:- dashboard@@ -15310,9 +15310,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:update- tokenizer:- - EDITOR+ - dashboard:updatesummary: Update dashboard (v2)tags:- dashboard@@ -15378,9 +15378,11 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:read+ - dashboard:create- tokenizer:- - EDITOR+ - dashboard:read+ - dashboard:createsummary: Clone dashboard (v2)tags:- dashboard@@ -15431,9 +15433,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:update- tokenizer:- - EDITOR+ - dashboard:updatesummary: Unlock dashboard (v2)tags:- dashboard@@ -15483,9 +15485,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:update- tokenizer:- - EDITOR+ - dashboard:updatesummary: Lock dashboard (v2)tags:- dashboard@@ -15549,9 +15551,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - EDITOR+ - dashboard:update- tokenizer:- - EDITOR+ - dashboard:updatesummary: Migrate dashboard to v2tags:- dashboard@@ -23695,9 +23697,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - VIEWER+ - dashboard:list- tokenizer:- - VIEWER+ - dashboard:listsummary: List dashboards for the current user (v2)tags:- dashboard@@ -23742,9 +23744,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - VIEWER+ - dashboard:list- tokenizer:- - VIEWER+ - dashboard:listsummary: Unpin a dashboard for the current user (v2)tags:- dashboard@@ -23801,9 +23803,9 @@ paths:description: Internal Server Errorsecurity:- api_key:- - VIEWER+ - dashboard:list- tokenizer:- - VIEWER+ - dashboard:listsummary: Pin a dashboard for the current user (v2)tags:- dashboarddiff --git a/pkg/apiserver/signozapiserver/dashboard.go b/pkg/apiserver/signozapiserver/dashboard.goindex a1bed05d6e..d84aee62e4 100644--- a/pkg/apiserver/signozapiserver/dashboard.go+++ b/pkg/apiserver/signozapiserver/dashboard.go@@ -14,371 +14,592 @@ import ()func (provider *provider) addDashboardRoutes(router *mux.Router) error {- if err := router.Handle("/api/v2/dashboards", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.ListV2), handler.OpenAPIDef{- ID: "ListDashboardsV2",- Tags: []string{"dashboard"},- Summary: "List dashboards (v2)",- Description: "Returns a page of v2-shape dashboards for the org. This is the pure, user-independent list — it carries no pin state. Use ListDashboardsForUserV2 for the personalized, pin-aware list. Supports a filter DSL (`query`), sort (`updated_at`/`created_at`/`name`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`).",- Request: nil,- RequestQuery: new(dashboardtypes.ListDashboardsV2Params),- RequestContentType: "",- Response: new(dashboardtypes.ListableDashboardV2),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{http.StatusBadRequest},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleViewer),- })).Methods(http.MethodGet).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboards", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.ListV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "ListDashboardsV2",+ Tags: []string{"dashboard"},+ Summary: "List dashboards (v2)",+ Description: "Returns a page of v2-shape dashboards for the org. This is the pure, user-independent list — it carries no pin state. Use ListDashboardsForUserV2 for the personalized, pin-aware list. Supports a filter DSL (`query`), sort (`updated_at`/`created_at`/`name`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`).",+ Request: nil,+ RequestQuery: new(dashboardtypes.ListDashboardsV2Params),+ RequestContentType: "",+ Response: new(dashboardtypes.ListableDashboardV2),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbList)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbList,+ Category: coretypes.ActionCategoryDataAccess,+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodGet).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/users/me/dashboards", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.ListForUserV2), handler.OpenAPIDef{- ID: "ListDashboardsForUserV2",- Tags: []string{"dashboard"},- Summary: "List dashboards for the current user (v2)",- Description: "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.",- Request: nil,- RequestQuery: new(dashboardtypes.ListDashboardsV2Params),- RequestContentType: "",- Response: new(dashboardtypes.ListableDashboardForUserV2),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{http.StatusBadRequest},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleViewer),- })).Methods(http.MethodGet).GetError(); err != nil {+ if err := router.Handle("/api/v2/users/me/dashboards", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.ListForUserV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "ListDashboardsForUserV2",+ Tags: []string{"dashboard"},+ Summary: "List dashboards for the current user (v2)",+ Description: "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.",+ Request: nil,+ RequestQuery: new(dashboardtypes.ListDashboardsV2Params),+ RequestContentType: "",+ Response: new(dashboardtypes.ListableDashboardForUserV2),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbList)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbList,+ Category: coretypes.ActionCategoryDataAccess,+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodGet).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboards", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.CreateV2), handler.OpenAPIDef{- ID: "CreateDashboardV2",- Tags: []string{"dashboard"},- Summary: "Create dashboard (v2)",- Description: "This endpoint creates a dashboard in the v2 format that follows Perses spec.",- Request: new(dashboardtypes.PostableDashboardV2),- RequestContentType: "application/json",- Response: new(dashboardtypes.GettableDashboardV2),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusCreated,- // TODO: add http.StatusConflict once the dashboard name unique index is added.- ErrorStatusCodes: []int{http.StatusBadRequest},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodPost).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboards", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.CreateV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),+ handler.OpenAPIDef{+ ID: "CreateDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Create dashboard (v2)",+ Description: "This endpoint creates a dashboard in the v2 format that follows Perses spec.",+ Request: new(dashboardtypes.PostableDashboardV2),+ RequestContentType: "application/json",+ Response: new(dashboardtypes.GettableDashboardV2),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusCreated,+ // TODO: add http.StatusConflict once the dashboard name unique index is added.+ ErrorStatusCodes: []int{http.StatusBadRequest},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbCreate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbCreate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.ResponseJSONPath("data.id"),+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodPost).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboards/{id}/clone", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.CloneV2), handler.OpenAPIDef{- ID: "CloneDashboardV2",- Tags: []string{"dashboard"},- Summary: "Clone dashboard (v2)",- Description: "This endpoint clones an existing v2-shape dashboard. User and integration dashboards can be cloned; system dashboards are rejected. The clone keeps the source's display name, panels, and tags, but gets a freshly generated unique internal name and is always created as an unlocked user dashboard owned by the caller.",- Request: nil,- RequestContentType: "",- Response: new(dashboardtypes.GettableDashboardV2),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusCreated,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodPost).GetError(); err != nil {+ // Two defs: the clone reads the source dashboard and creates a new one, so+ // both read on the source id and create on the collection are checked.+ if err := router.Handle("/api/v2/dashboards/{id}/clone", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.CloneV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),+ handler.OpenAPIDef{+ ID: "CloneDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Clone dashboard (v2)",+ Description: "This endpoint clones an existing v2-shape dashboard. User and integration dashboards can be cloned; system dashboards are rejected. The clone keeps the source's display name, panels, and tags, but gets a freshly generated unique internal name and is always created as an unlocked user dashboard owned by the caller.",+ Request: nil,+ RequestContentType: "",+ Response: new(dashboardtypes.GettableDashboardV2),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusCreated,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{+ coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbRead),+ coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbCreate),+ }),+ },+ handler.WithResourceDefs(+ handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbRead,+ Category: coretypes.ActionCategoryDataAccess,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ },+ handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbCreate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.ResponseJSONPath("data.id"),+ Selector: coretypes.WildcardSelector,+ },+ ),+ )).Methods(http.MethodPost).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboards/{id}/migrate", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.MigrateV2), handler.OpenAPIDef{- ID: "MigrateDashboardV2",- Tags: []string{"dashboard"},- Summary: "Migrate dashboard to v2",- Description: "This endpoint retries the v1→v2 (Perses) migration on a dashboard still stored in the v1 schema and returns the v2-shape result. It is idempotent: a dashboard already in the v2 schema is returned unchanged.",- Request: nil,- RequestContentType: "",- Response: new(dashboardtypes.GettableDashboardV2),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodPost).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboards/{id}/migrate", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.MigrateV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),+ handler.OpenAPIDef{+ ID: "MigrateDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Migrate dashboard to v2",+ Description: "This endpoint retries the v1→v2 (Perses) migration on a dashboard still stored in the v1 schema and returns the v2-shape result. It is idempotent: a dashboard already in the v2 schema is returned unchanged.",+ Request: nil,+ RequestContentType: "",+ Response: new(dashboardtypes.GettableDashboardV2),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbUpdate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbUpdate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodPost).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboards/{id}", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.GetV2), handler.OpenAPIDef{- ID: "GetDashboardV2",- Tags: []string{"dashboard"},- Summary: "Get dashboard (v2)",- Description: "This endpoint returns a v2-shape dashboard.",- Request: nil,- RequestContentType: "",- Response: new(dashboardtypes.GettableDashboardV2),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleViewer),- })).Methods(http.MethodGet).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboards/{id}", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.GetV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "GetDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Get dashboard (v2)",+ Description: "This endpoint returns a v2-shape dashboard.",+ Request: nil,+ RequestContentType: "",+ Response: new(dashboardtypes.GettableDashboardV2),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbRead)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbRead,+ Category: coretypes.ActionCategoryDataAccess,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodGet).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboards/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.UpdateV2), handler.OpenAPIDef{- ID: "UpdateDashboardV2",- Tags: []string{"dashboard"},- Summary: "Update dashboard (v2)",- Description: "This endpoint updates a v2-shape dashboard's metadata, data, and tag set. Locked dashboards are rejected.",- Request: new(dashboardtypes.UpdatableDashboardV2),- RequestContentType: "application/json",- Response: new(dashboardtypes.GettableDashboardV2),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodPut).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboards/{id}", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.UpdateV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),+ handler.OpenAPIDef{+ ID: "UpdateDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Update dashboard (v2)",+ Description: "This endpoint updates a v2-shape dashboard's metadata, data, and tag set. Locked dashboards are rejected.",+ Request: new(dashboardtypes.UpdatableDashboardV2),+ RequestContentType: "application/json",+ Response: new(dashboardtypes.GettableDashboardV2),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbUpdate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbUpdate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodPut).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboards/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.PatchV2), handler.OpenAPIDef{- ID: "PatchDashboardV2",- Tags: []string{"dashboard"},- Summary: "Patch dashboard (v2)",- Description: "This endpoint applies an RFC 6902 JSON Patch to a v2-shape dashboard. The patch is applied against the postable view of the dashboard (metadata, data, tags), so individual panels, queries, variables, layouts, or tags can be updated without re-sending the rest of the dashboard. Apply is lenient: `remove` on a missing path is a no-op (idempotent) and `add` creates any missing parent objects, rather than failing as strict RFC 6902 would. The resulting dashboard is still validated. Locked dashboards are rejected.",- Request: new(dashboardtypes.PatchableDashboardV2),- // Strictly per RFC 6902 the content type is `application/json-patch+json`,- // but our OpenAPI generator only reflects schemas for content types it- // understands (application/json, form-urlencoded, multipart) — anything- // else degrades to `type: string`. Declaring application/json here keeps- // the array-of-ops schema visible to spec consumers; the runtime decoder- // parses JSON regardless of the request's actual Content-Type header.- RequestContentType: "application/json",- Response: new(dashboardtypes.GettableDashboardV2),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodPatch).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboards/{id}", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.PatchV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),+ handler.OpenAPIDef{+ ID: "PatchDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Patch dashboard (v2)",+ Description: "This endpoint applies an RFC 6902 JSON Patch to a v2-shape dashboard. The patch is applied against the postable view of the dashboard (metadata, data, tags), so individual panels, queries, variables, layouts, or tags can be updated without re-sending the rest of the dashboard. Apply is lenient: `remove` on a missing path is a no-op (idempotent) and `add` creates any missing parent objects, rather than failing as strict RFC 6902 would. The resulting dashboard is still validated. Locked dashboards are rejected.",+ Request: new(dashboardtypes.PatchableDashboardV2),+ // Strictly per RFC 6902 the content type is `application/json-patch+json`,+ // but our OpenAPI generator only reflects schemas for content types it+ // understands (application/json, form-urlencoded, multipart) — anything+ // else degrades to `type: string`. Declaring application/json here keeps+ // the array-of-ops schema visible to spec consumers; the runtime decoder+ // parses JSON regardless of the request's actual Content-Type header.+ RequestContentType: "application/json",+ Response: new(dashboardtypes.GettableDashboardV2),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbUpdate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbUpdate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodPatch).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboards/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.DeleteV2), handler.OpenAPIDef{- ID: "DeleteDashboardV2",- Tags: []string{"dashboard"},- Summary: "Delete dashboard (v2)",- Description: "This endpoint deletes a v2-shape dashboard along with its tag relations. Locked dashboards are rejected.",- Request: nil,- RequestContentType: "",- Response: nil,- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusNoContent,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodDelete).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboards/{id}", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.DeleteV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),+ handler.OpenAPIDef{+ ID: "DeleteDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Delete dashboard (v2)",+ Description: "This endpoint deletes a v2-shape dashboard along with its tag relations. Locked dashboards are rejected.",+ Request: nil,+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbDelete)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbDelete,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodDelete).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboards/{id}/lock", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.LockV2), handler.OpenAPIDef{- ID: "LockDashboardV2",- Tags: []string{"dashboard"},- Summary: "Lock dashboard (v2)",- Description: "This endpoint locks a v2-shape dashboard. Only the dashboard's creator or an org admin may lock or unlock.",- Request: nil,- RequestContentType: "",- Response: nil,- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusNoContent,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodPut).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboards/{id}/lock", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.LockV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),+ handler.OpenAPIDef{+ ID: "LockDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Lock dashboard (v2)",+ Description: "This endpoint locks a v2-shape dashboard. Only the dashboard's creator or an org admin may lock or unlock.",+ Request: nil,+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbUpdate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbUpdate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodPut).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboards/{id}/lock", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.UnlockV2), handler.OpenAPIDef{- ID: "UnlockDashboardV2",- Tags: []string{"dashboard"},- Summary: "Unlock dashboard (v2)",- Description: "This endpoint unlocks a v2-shape dashboard. Only the dashboard's creator or an org admin may lock or unlock.",- Request: nil,- RequestContentType: "",- Response: nil,- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusNoContent,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodDelete).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboards/{id}/lock", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.UnlockV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),+ handler.OpenAPIDef{+ ID: "UnlockDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Unlock dashboard (v2)",+ Description: "This endpoint unlocks a v2-shape dashboard. Only the dashboard's creator or an org admin may lock or unlock.",+ Request: nil,+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbUpdate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbUpdate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodDelete).GetError(); err != nil {return err}- // ViewAccess: pinning only mutates the calling user's pin list, not the- // dashboard itself — anyone who can view a dashboard can bookmark it.- if err := router.Handle("/api/v2/users/me/dashboards/{id}/pins", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.PinV2), handler.OpenAPIDef{- ID: "PinDashboardV2",- Tags: []string{"dashboard"},- Summary: "Pin a dashboard for the current user (v2)",- Description: "Pins the dashboard for the calling user. A user can pin at most 10 dashboards; pinning when at the limit returns 409. Re-pinning an already-pinned dashboard is a no-op success.",- Request: nil,- RequestContentType: "",- Response: nil,- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusNoContent,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound, http.StatusConflict},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleViewer),- })).Methods(http.MethodPut).GetError(); err != nil {+ // Pinning mutates the calling user's pin list, not the dashboard, so it rides+ // on the collection-level list permission rather than a per-dashboard check.+ // The id is still extracted, for audit.+ if err := router.Handle("/api/v2/users/me/dashboards/{id}/pins", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.PinV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "PinDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Pin a dashboard for the current user (v2)",+ Description: "Pins the dashboard for the calling user. A user can pin at most 10 dashboards; pinning when at the limit returns 409. Re-pinning an already-pinned dashboard is a no-op success.",+ Request: nil,+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound, http.StatusConflict},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbList)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbList,+ Category: coretypes.ActionCategoryDataAccess,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodPut).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/users/me/dashboards/{id}/pins", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.UnpinV2), handler.OpenAPIDef{- ID: "UnpinDashboardV2",- Tags: []string{"dashboard"},- Summary: "Unpin a dashboard for the current user (v2)",- Description: "Removes the pin for the calling user. Idempotent — unpinning a dashboard that wasn't pinned still returns 204.",- Request: nil,- RequestContentType: "",- Response: nil,- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusNoContent,- ErrorStatusCodes: []int{http.StatusBadRequest},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleViewer),- })).Methods(http.MethodDelete).GetError(); err != nil {+ if err := router.Handle("/api/v2/users/me/dashboards/{id}/pins", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.UnpinV2, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "UnpinDashboardV2",+ Tags: []string{"dashboard"},+ Summary: "Unpin a dashboard for the current user (v2)",+ Description: "Removes the pin for the calling user. Idempotent — unpinning a dashboard that wasn't pinned still returns 204.",+ Request: nil,+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{http.StatusBadRequest},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbList)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbList,+ Category: coretypes.ActionCategoryDataAccess,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodDelete).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboard_views", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.ListViews), handler.OpenAPIDef{- ID: "ListDashboardViews",- Tags: []string{"dashboard"},- Summary: "List dashboard saved views",- Description: "Returns every saved view in the calling user's org. Saved views are shared org-wide.",- Request: nil,- RequestContentType: "",- Response: new(dashboardtypes.ListableDashboardView),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleViewer),- })).Methods(http.MethodGet).GetError(); err != nil {+ // Saved views hold dashboard listing state (query, sort, order) rather than any+ // one dashboard, so all four ride on the collection-level list permission.+ if err := router.Handle("/api/v2/dashboard_views", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.ListViews, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "ListDashboardViews",+ Tags: []string{"dashboard"},+ Summary: "List dashboard saved views",+ Description: "Returns every saved view in the calling user's org. Saved views are shared org-wide.",+ Request: nil,+ RequestContentType: "",+ Response: new(dashboardtypes.ListableDashboardView),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbList)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbList,+ Category: coretypes.ActionCategoryDataAccess,+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodGet).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboard_views", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.CreateView), handler.OpenAPIDef{- ID: "CreateDashboardView",- Tags: []string{"dashboard"},- Summary: "Create dashboard saved view",- Description: "Persists the calling user's dashboard listing state (query, sort, order) as a named, reusable view shared across the org.",- Request: new(dashboardtypes.PostableDashboardView),- RequestContentType: "application/json",- Response: new(dashboardtypes.DashboardView),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusCreated,- ErrorStatusCodes: []int{http.StatusBadRequest},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodPost).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboard_views", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.CreateView, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "CreateDashboardView",+ Tags: []string{"dashboard"},+ Summary: "Create dashboard saved view",+ Description: "Persists the calling user's dashboard listing state (query, sort, order) as a named, reusable view shared across the org.",+ Request: new(dashboardtypes.PostableDashboardView),+ RequestContentType: "application/json",+ Response: new(dashboardtypes.DashboardView),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusCreated,+ ErrorStatusCodes: []int{http.StatusBadRequest},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbList)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbList,+ Category: coretypes.ActionCategoryConfigurationChange,+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodPost).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboard_views/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.UpdateView), handler.OpenAPIDef{- ID: "UpdateDashboardView",- Tags: []string{"dashboard"},- Summary: "Update dashboard saved view",- Description: "Replaces a saved view's name and data. Saved views are shared org-wide.",- Request: new(dashboardtypes.UpdatableDashboardView),- RequestContentType: "application/json",- Response: new(dashboardtypes.DashboardView),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodPut).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboard_views/{id}", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.UpdateView, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "UpdateDashboardView",+ Tags: []string{"dashboard"},+ Summary: "Update dashboard saved view",+ Description: "Replaces a saved view's name and data. Saved views are shared org-wide.",+ Request: new(dashboardtypes.UpdatableDashboardView),+ RequestContentType: "application/json",+ Response: new(dashboardtypes.DashboardView),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbList)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbList,+ Category: coretypes.ActionCategoryConfigurationChange,+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodPut).GetError(); err != nil {return err}- if err := router.Handle("/api/v2/dashboard_views/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.DeleteView), handler.OpenAPIDef{- ID: "DeleteDashboardView",- Tags: []string{"dashboard"},- Summary: "Delete dashboard saved view",- Description: "Removes a saved view. Saved views are shared org-wide. Deleting a non-existent view returns 404.",- Request: nil,- RequestContentType: "",- Response: nil,- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusNoContent,- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleEditor),- })).Methods(http.MethodDelete).GetError(); err != nil {+ if err := router.Handle("/api/v2/dashboard_views/{id}", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.DeleteView, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "DeleteDashboardView",+ Tags: []string{"dashboard"},+ Summary: "Delete dashboard saved view",+ Description: "Removes a saved view. Saved views are shared org-wide. Deleting a non-existent view returns 404.",+ Request: nil,+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbList)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbList,+ Category: coretypes.ActionCategoryConfigurationChange,+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodDelete).GetError(); err != nil {return err}- if err := router.Handle("/api/v1/dashboards/{id}/public", handler.New(provider.authzMiddleware.AdminAccess(provider.dashboardHandler.CreatePublic), handler.OpenAPIDef{- ID: "CreatePublicDashboard",- Tags: []string{"dashboard"},- Summary: "Create public dashboard",- Description: "This endpoint creates public sharing config and enables public sharing of the dashboard",- Request: new(dashboardtypes.PostablePublicDashboard),- RequestContentType: "",- Response: new(types.Identifiable),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusCreated,- ErrorStatusCodes: []int{},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),- })).Methods(http.MethodPost).GetError(); err != nil {+ if err := router.Handle("/api/v1/dashboards/{id}/public", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.CreatePublic, authtypes.SigNozAdminRoleName),+ handler.OpenAPIDef{+ ID: "CreatePublicDashboard",+ Tags: []string{"dashboard"},+ Summary: "Create public dashboard",+ Description: "This endpoint creates public sharing config and enables public sharing of the dashboard",+ Request: new(dashboardtypes.PostablePublicDashboard),+ RequestContentType: "",+ Response: new(types.Identifiable),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusCreated,+ ErrorStatusCodes: []int{},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbUpdate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbUpdate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodPost).GetError(); err != nil {return err}- if err := router.Handle("/api/v1/dashboards/{id}/public", handler.New(provider.authzMiddleware.AdminAccess(provider.dashboardHandler.GetPublic), handler.OpenAPIDef{- ID: "GetPublicDashboard",- Tags: []string{"dashboard"},- Summary: "Get public dashboard",- Description: "This endpoint returns public sharing config for a dashboard",- Request: nil,- RequestContentType: "",- Response: new(dashboardtypes.GettablePublicDasbhboard),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),- })).Methods(http.MethodGet).GetError(); err != nil {+ if err := router.Handle("/api/v1/dashboards/{id}/public", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.GetPublic, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "GetPublicDashboard",+ Tags: []string{"dashboard"},+ Summary: "Get public dashboard",+ Description: "This endpoint returns public sharing config for a dashboard",+ Request: nil,+ RequestContentType: "",+ Response: new(dashboardtypes.GettablePublicDasbhboard),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbRead)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbRead,+ Category: coretypes.ActionCategoryDataAccess,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodGet).GetError(); err != nil {return err}- if err := router.Handle("/api/v1/dashboards/{id}/public", handler.New(provider.authzMiddleware.AdminAccess(provider.dashboardHandler.UpdatePublic), handler.OpenAPIDef{- ID: "UpdatePublicDashboard",- Tags: []string{"dashboard"},- Summary: "Update public dashboard",- Description: "This endpoint updates the public sharing config for a dashboard",- Request: new(dashboardtypes.UpdatablePublicDashboard),- RequestContentType: "",- Response: nil,- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusNoContent,- ErrorStatusCodes: []int{},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),- })).Methods(http.MethodPut).GetError(); err != nil {+ if err := router.Handle("/api/v1/dashboards/{id}/public", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.UpdatePublic, authtypes.SigNozAdminRoleName),+ handler.OpenAPIDef{+ ID: "UpdatePublicDashboard",+ Tags: []string{"dashboard"},+ Summary: "Update public dashboard",+ Description: "This endpoint updates the public sharing config for a dashboard",+ Request: new(dashboardtypes.UpdatablePublicDashboard),+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbUpdate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbUpdate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodPut).GetError(); err != nil {return err}- if err := router.Handle("/api/v1/dashboards/{id}/public", handler.New(provider.authzMiddleware.AdminAccess(provider.dashboardHandler.DeletePublic), handler.OpenAPIDef{- ID: "DeletePublicDashboard",- Tags: []string{"dashboard"},- Summary: "Delete public dashboard",- Description: "This endpoint deletes the public sharing config and disables the public sharing of a dashboard",- Request: nil,- RequestContentType: "",- Response: nil,- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusNoContent,- ErrorStatusCodes: []int{},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),- })).Methods(http.MethodDelete).GetError(); err != nil {+ if err := router.Handle("/api/v1/dashboards/{id}/public", handler.New(+ provider.authzMiddleware.CheckResources(provider.dashboardHandler.DeletePublic, authtypes.SigNozAdminRoleName),+ handler.OpenAPIDef{+ ID: "DeletePublicDashboard",+ Tags: []string{"dashboard"},+ Summary: "Delete public dashboard",+ Description: "This endpoint deletes the public sharing config and disables the public sharing of a dashboard",+ Request: nil,+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceDashboard.Scope(coretypes.VerbUpdate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceDashboard,+ Verb: coretypes.VerbUpdate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodDelete).GetError(); err != nil {return err}diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.goindex bdab15a742..790cdfbe1a 100644--- a/pkg/signoz/provider.go+++ b/pkg/signoz/provider.go@@ -234,6 +234,7 @@ func NewSQLMigrationProviderFactories(sqlmigration.NewUpdateRoleTransactionGroupsFactory(),sqlmigration.NewFillDashboardSpecCollectionsFactory(sqlstore, dashboardStore),sqlmigration.NewScrubEmailChannelTransportFactory(sqlstore),+ sqlmigration.NewAddDashboardTuplesFactory(sqlstore),)}diff --git a/pkg/sqlmigration/108_add_dashboard_tuples.go b/pkg/sqlmigration/108_add_dashboard_tuples.gonew file mode 100644index 0000000000..189db8cacc--- /dev/null+++ b/pkg/sqlmigration/108_add_dashboard_tuples.go@@ -0,0 +1,149 @@+package sqlmigration++import (+ "context"+ "time"++ "github.com/SigNoz/signoz/pkg/factory"+ "github.com/SigNoz/signoz/pkg/sqlstore"+ "github.com/SigNoz/signoz/pkg/types/authtypes"+ "github.com/oklog/ulid/v2"+ "github.com/uptrace/bun"+ "github.com/uptrace/bun/dialect"+ "github.com/uptrace/bun/migrate"+)++type addDashboardTuples struct {+ sqlstore sqlstore.SQLStore+}++func NewAddDashboardTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {+ return factory.NewProviderFactory(factory.MustNewName("add_dashboard_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {+ return &addDashboardTuples{sqlstore: sqlstore}, nil+ })+}++func (migration *addDashboardTuples) Register(migrations *migrate.Migrations) error {+ return migrations.Register(migration.Up, migration.Down)+}++func (migration *addDashboardTuples) Up(ctx context.Context, db *bun.DB) error {+ tx, err := db.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer func() { _ = tx.Rollback() }()++ var storeID string+ err = tx.QueryRowContext(ctx, `SELECT id FROM store WHERE name = ? LIMIT 1`, "signoz").Scan(&storeID)+ if err != nil {+ return err+ }++ var orgIDs []string+ rows, err := tx.QueryContext(ctx, `SELECT id FROM organizations`)+ if err != nil {+ return err+ }+ defer rows.Close()+ for rows.Next() {+ var orgID string+ if err := rows.Scan(&orgID); err != nil {+ return err+ }+ orgIDs = append(orgIDs, orgID)+ }++ isPG := migration.sqlstore.BunDB().Dialect().Name() == dialect.PG++ // The dashboard routes, including the public sharing config, now authorize per+ // resource, so every org needs the managed-role dashboard tuples. Orgs+ // bootstrapped before these entries landed in ManagedRoleToTransactions never+ // got them.+ tuples := []migrationTuple{+ {authtypes.SigNozAdminRoleName, "metaresource", "dashboard", "read"},+ {authtypes.SigNozAdminRoleName, "metaresource", "dashboard", "update"},+ {authtypes.SigNozAdminRoleName, "metaresource", "dashboard", "delete"},+ {authtypes.SigNozAdminRoleName, "metaresource", "dashboard", "create"},+ {authtypes.SigNozAdminRoleName, "metaresource", "dashboard", "list"},+ {authtypes.SigNozEditorRoleName, "metaresource", "dashboard", "read"},+ {authtypes.SigNozEditorRoleName, "metaresource", "dashboard", "update"},+ {authtypes.SigNozEditorRoleName, "metaresource", "dashboard", "delete"},+ {authtypes.SigNozEditorRoleName, "metaresource", "dashboard", "create"},+ {authtypes.SigNozEditorRoleName, "metaresource", "dashboard", "list"},+ {authtypes.SigNozViewerRoleName, "metaresource", "dashboard", "read"},+ {authtypes.SigNozViewerRoleName, "metaresource", "dashboard", "list"},+ }++ for _, orgID := range orgIDs {+ for _, tuple := range tuples {+ entropy := ulid.DefaultEntropy()+ now := time.Now().UTC()+ tupleID := ulid.MustNew(ulid.Timestamp(now), entropy).String()++ objectID := "organization/" + orgID + "/" + tuple.objectName + "/*"+ roleSubject := "organization/" + orgID + "/role/" + tuple.roleName++ if isPG {+ user := "role:" + roleSubject + "#assignee"+ result, err := tx.ExecContext(ctx, `+ INSERT INTO tuple (store, object_type, object_id, relation, _user, user_type, ulid, inserted_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT (store, object_type, object_id, relation, _user) DO NOTHING`,+ storeID, tuple.objectType, objectID, tuple.relation, user, "userset", tupleID, now,+ )+ if err != nil {+ return err+ }+ rowsAffected, err := result.RowsAffected()+ if err != nil {+ return err+ }+ if rowsAffected == 0 {+ continue+ }+ _, err = tx.ExecContext(ctx, `+ INSERT INTO changelog (store, object_type, object_id, relation, _user, operation, ulid, inserted_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT (store, ulid, object_type) DO NOTHING`,+ storeID, tuple.objectType, objectID, tuple.relation, user, 0, tupleID, now,+ )+ if err != nil {+ return err+ }+ } else {+ result, err := tx.ExecContext(ctx, `+ INSERT INTO tuple (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, user_type, ulid, inserted_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation) DO NOTHING`,+ storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", "userset", tupleID, now,+ )+ if err != nil {+ return err+ }+ rowsAffected, err := result.RowsAffected()+ if err != nil {+ return err+ }+ if rowsAffected == 0 {+ continue+ }+ _, err = tx.ExecContext(ctx, `+ INSERT INTO changelog (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, operation, ulid, inserted_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT (store, ulid, object_type) DO NOTHING`,+ storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", 0, tupleID, now,+ )+ if err != nil {+ return err+ }+ }+ }+ }++ return tx.Commit()+}++func (migration *addDashboardTuples) Down(context.Context, *bun.DB) error {+ return nil+}diff --git a/pkg/types/coretypes/registry_resource.go b/pkg/types/coretypes/registry_resource.goindex 1e14d0873a..f6f8ec13bf 100644--- a/pkg/types/coretypes/registry_resource.go+++ b/pkg/types/coretypes/registry_resource.go@@ -54,7 +54,7 @@ var (ResourceMetaResourceCloudIntegration = NewResourceMetaResource(KindCloudIntegration)ResourceMetaResourceCloudIntegrationService = NewResourceMetaResource(KindCloudIntegrationService)ResourceMetaResourceIntegration = NewResourceMetaResource(KindIntegration)- ResourceMetaResourceDashboard = NewResourceMetaResource(KindDashboard)+ ResourceMetaResourceDashboard = NewResourceMetaResource(KindDashboard, VerbCreate, VerbList, VerbRead, VerbUpdate, VerbDelete)ResourceMetaResourcePublicDashboard = NewResourceMetaResource(KindPublicDashboard)ResourceMetaResourceIngestionKey = NewResourceMetaResource(KindIngestionKey)ResourceMetaResourceIngestionLimit = NewResourceMetaResource(KindIngestionLimit)diff --git a/tests/integration/tests/dashboard/06_authz.py b/tests/integration/tests/dashboard/06_authz.pynew file mode 100644index 0000000000..f5189f6608--- /dev/null+++ b/tests/integration/tests/dashboard/06_authz.py@@ -0,0 +1,623 @@+from collections.abc import Callable+from http import HTTPStatus++import requests+from wiremock.resources.mappings import Mapping++from fixtures.auth import (+ USER_ADMIN_EMAIL,+ USER_ADMIN_PASSWORD,+ add_license,+ change_user_role,+ create_active_user,+ find_user_by_email,+)+from fixtures.role import transaction_group+from fixtures.types import Operation, SigNoz, TestContainerDocker++V2_BASE_URL = "/api/v2/dashboards"+MAX_LIST_LIMIT = 200++_EDITOR_EMAIL = "[email protected]"+_EDITOR_PASSWORD = "password123Z$"+_VIEWER_EMAIL = "[email protected]"+_VIEWER_PASSWORD = "password123Z$"++_ACTOR_ROLE_NAME = "dashboard-fga-actor"+_ACTOR_EMAIL = "[email protected]"+_ACTOR_PASSWORD = "password123Z$"++# Instance verbs are granted on _TARGET_A only; _TARGET_B must stay forbidden.+_TARGET_A = "dashboard-authz-target-a"+_TARGET_B = "dashboard-authz-target-b"+_CLONE_SOURCE = "dashboard-authz-clone-source"+_VIEW_NAME = "dashboard-authz-view"++_SPEC = {+ "display": {"name": "Dashboard Authz"},+ "duration": "1h",+ "links": [],+ "variables": [],+ "panels": {},+ "layouts": [],+}+++# ─── managed roles (community-safe: no license, role gate only) ───────────────+++def test_setup_managed_role_users(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)++ # A rerun against a --reuse stack starts from the previous run's state, and+ # inviting an existing address fails, so only invite what is missing.+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ existing_emails = {user["email"] for user in response.json()["data"]}++ for email, role, password, name in (+ (_EDITOR_EMAIL, "EDITOR", _EDITOR_PASSWORD, "dashboard authz editor"),+ (_VIEWER_EMAIL, "VIEWER", _VIEWER_PASSWORD, "dashboard authz viewer"),+ ):+ if email not in existing_emails:+ create_active_user(signoz, admin_token, email=email, role=role, password=password, name=name)++ # (org_id, name) is unique, so leftovers from an earlier run have to go before+ # these are recreated.+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ for dashboard in response.json()["data"]["dashboards"]:+ if dashboard["name"] in (_TARGET_A, _TARGET_B, _CLONE_SOURCE):+ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{dashboard['id']}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text++ for name in (_TARGET_A, _TARGET_B, _CLONE_SOURCE):+ response = requests.post(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ json={"schemaVersion": "v6", "name": name, "spec": _SPEC, "tags": []},+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.CREATED, response.text+++def test_viewer_allowed_on_reads_and_pins(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ token = get_token(_VIEWER_EMAIL, _VIEWER_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ ids = {dashboard["name"]: dashboard["id"] for dashboard in response.json()["data"]["dashboards"]}++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids[_TARGET_A]}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ response = requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids[_TARGET_A]}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids[_TARGET_A]}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text+++def test_viewer_forbidden_on_mutations(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ token = get_token(_VIEWER_EMAIL, _VIEWER_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ ids = {dashboard["name"]: dashboard["id"] for dashboard in response.json()["data"]["dashboards"]}+ target_id = ids[_TARGET_A]++ response = requests.post(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ json={"schemaVersion": "v6", "name": "viewer-denied", "spec": _SPEC, "tags": []},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"create: expected 403, got {response.status_code}: {response.text}"++ response = requests.put(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{target_id}"),+ json={"schemaVersion": "v6", "name": _TARGET_A, "spec": _SPEC, "tags": []},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"update: expected 403, got {response.status_code}: {response.text}"++ response = requests.patch(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{target_id}"),+ json=[{"op": "replace", "path": "/spec/display/name", "value": "Patched"}],+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"patch: expected 403, got {response.status_code}: {response.text}"++ response = requests.post(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{target_id}/clone"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"clone: expected 403, got {response.status_code}: {response.text}"++ response = requests.post(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{target_id}/migrate"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"migrate: expected 403, got {response.status_code}: {response.text}"++ response = requests.put(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{target_id}/lock"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"lock: expected 403, got {response.status_code}: {response.text}"++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{target_id}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"delete: expected 403, got {response.status_code}: {response.text}"+++def test_editor_allowed_on_mutations(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ token = get_token(_EDITOR_EMAIL, _EDITOR_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ ids = {dashboard["name"]: dashboard["id"] for dashboard in response.json()["data"]["dashboards"]}++ response = requests.put(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids[_TARGET_A]}"),+ json={"schemaVersion": "v6", "name": _TARGET_A, "spec": _SPEC, "tags": [{"key": "team", "value": "pulse"}]},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ response = requests.post(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids[_CLONE_SOURCE]}/clone"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.CREATED, response.text+ clone_id = response.json()["data"]["id"]++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{clone_id}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text+++def test_viewer_forbidden_on_public_config(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ # The public config routes authorize on the dashboard itself, so a viewer is+ # refused before the handler runs, licensed or not.+ token = get_token(_VIEWER_EMAIL, _VIEWER_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ target_id = {dashboard["name"]: dashboard["id"] for dashboard in response.json()["data"]["dashboards"]}[_TARGET_A]++ response = requests.post(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ json={"timeRangeEnabled": True, "defaultTimeRange": "10m"},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"create public: expected 403, got {response.status_code}: {response.text}"++ response = requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ json={"timeRangeEnabled": False, "defaultTimeRange": "10m"},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"update public: expected 403, got {response.status_code}: {response.text}"++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"delete public: expected 403, got {response.status_code}: {response.text}"+++def test_viewer_allowed_on_saved_views(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ # Saved views ride on dashboard list, which a viewer holds, so the whole CRUD+ # surface is open to them.+ token = get_token(_VIEWER_EMAIL, _VIEWER_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/dashboard_views"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v2/dashboard_views"),+ json={"name": _VIEW_NAME, "data": {"version": "v1", "sort": "updated_at", "order": "desc"}},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.CREATED, response.text+ view_id = response.json()["data"]["id"]++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v2/dashboard_views/{view_id}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text+++# ─── per-object FGA scoping (enterprise, custom role) ─────────────────────────+++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:+ add_license(signoz, make_http_mocks, get_token)+++def test_editor_allowed_on_public_config(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ # An editor holds dashboard update, which is what the public config routes ask+ # for, so publishing is open to editors and not just admins.+ token = get_token(_EDITOR_EMAIL, _EDITOR_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ target_id = {dashboard["name"]: dashboard["id"] for dashboard in response.json()["data"]["dashboards"]}[_TARGET_B]++ response = requests.post(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ json={"timeRangeEnabled": True, "defaultTimeRange": "10m"},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.CREATED, response.text++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ # Reading the config asks only for dashboard read, so a viewer sees it too.+ viewer_token = get_token(_VIEWER_EMAIL, _VIEWER_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ headers={"Authorization": f"Bearer {viewer_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text+++def test_setup_scoped_actor(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ create_role: Callable[..., str],+):+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ ids = {dashboard["name"]: dashboard["id"] for dashboard in response.json()["data"]["dashboards"]}++ create_role(+ admin_token,+ _ACTOR_ROLE_NAME,+ [+ transaction_group("read", "metaresource", "dashboard", [ids[_TARGET_A]]),+ transaction_group("list", "metaresource", "dashboard", ["*"]),+ ],+ )++ user_id = create_active_user(signoz, admin_token, email=_ACTOR_EMAIL, role="VIEWER", password=_ACTOR_PASSWORD, name="dashboard fga actor")+ change_user_role(signoz, admin_token, user_id, "signoz-viewer", _ACTOR_ROLE_NAME)+++def test_read_scoped_to_granted_dashboard(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ ids = {dashboard["name"]: dashboard["id"] for dashboard in response.json()["data"]["dashboards"]}++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids[_TARGET_A]}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, f"read granted dashboard: {response.text}"++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids[_TARGET_B]}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"read other dashboard: expected 403, got {response.status_code}: {response.text}"+++def test_list_returns_every_dashboard(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)++ # list is collection-scoped: list on "*" returns every dashboard, including+ # the one the actor cannot read individually.+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ names = {dashboard["name"] for dashboard in response.json()["data"]["dashboards"]}+ assert {_TARGET_A, _TARGET_B} <= names+++def test_publish_and_unpublish_require_update_on_the_dashboard(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ find_role_id: Callable[[str, str], str],+):+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ actor_role_id = find_role_id(admin_token, _ACTOR_ROLE_NAME)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ target_id = {dashboard["name"]: dashboard["id"] for dashboard in response.json()["data"]["dashboards"]}[_TARGET_A]++ # read and list alone must not be enough to publish.+ response = requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{actor_role_id}"),+ json={+ "description": "",+ "transactionGroups": [+ transaction_group("read", "metaresource", "dashboard", [target_id]),+ transaction_group("list", "metaresource", "dashboard", ["*"]),+ ],+ },+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text++ token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)++ response = requests.post(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ json={"timeRangeEnabled": True, "defaultTimeRange": "10m"},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"publish without dashboard update: expected 403, got {response.status_code}: {response.text}"++ response = requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{actor_role_id}"),+ json={+ "description": "",+ "transactionGroups": [+ transaction_group("read", "metaresource", "dashboard", [target_id]),+ transaction_group("list", "metaresource", "dashboard", ["*"]),+ transaction_group("update", "metaresource", "dashboard", [target_id]),+ ],+ },+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text++ response = requests.post(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ json={"timeRangeEnabled": True, "defaultTimeRange": "10m"},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.CREATED, f"publish with dashboard update: {response.text}"++ # Unpublishing asks for the same update grant.+ response = requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{actor_role_id}"),+ json={+ "description": "",+ "transactionGroups": [+ transaction_group("read", "metaresource", "dashboard", [target_id]),+ transaction_group("list", "metaresource", "dashboard", ["*"]),+ ],+ },+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.FORBIDDEN, f"unpublish without dashboard update: expected 403, got {response.status_code}: {response.text}"++ response = requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{actor_role_id}"),+ json={+ "description": "",+ "transactionGroups": [+ transaction_group("read", "metaresource", "dashboard", [target_id]),+ transaction_group("list", "metaresource", "dashboard", ["*"]),+ transaction_group("update", "metaresource", "dashboard", [target_id]),+ ],+ },+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v1/dashboards/{target_id}/public"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, f"unpublish with dashboard update: {response.text}"+++def test_dashboard_authz_cleanup(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ find_role_id: Callable[[str, str], str],+):+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ actor = find_user_by_email(signoz, admin_token, _ACTOR_EMAIL)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/{actor['id']}/roles"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ actor_entry = next((role for role in response.json()["data"] if role["name"] == _ACTOR_ROLE_NAME), None)+ if actor_entry is not None:+ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/{actor['id']}/roles/{actor_entry['id']}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, f"remove role from user: {response.text}"++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{find_role_id(admin_token, _ACTOR_ROLE_NAME)}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, f"delete {_ACTOR_ROLE_NAME}: {response.text}"++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}?limit={MAX_LIST_LIMIT}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ ids = {dashboard["name"]: dashboard["id"] for dashboard in response.json()["data"]["dashboards"]}++ for name in (_TARGET_A, _TARGET_B, _CLONE_SOURCE):+ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids[name]}"),+ headers={"Authorization": f"Bearer {admin_token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, f"delete {name}: {response.text}"