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(authz): update authz response to prevent pre-compute (#10385)
Vikrant Guptae8add5942e02
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex 4236246e77..417a7aea01 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -80,6 +80,37 @@ components:updatedAt:format: date-timetype: string+ required:+ - id+ type: object+ AuthtypesGettableObjects:+ properties:+ resource:+ $ref: '#/components/schemas/AuthtypesResource'+ selectors:+ items:+ type: string+ type: array+ required:+ - resource+ - selectors+ type: object+ AuthtypesGettableResources:+ properties:+ relations:+ additionalProperties:+ items:+ type: string+ type: array+ nullable: true+ type: object+ resources:+ items:+ $ref: '#/components/schemas/AuthtypesResource'+ type: array+ required:+ - resources+ - relationstype: objectAuthtypesGettableToken:properties:@@ -130,8 +161,6 @@ components:serviceAccountJson:type: stringtype: object- AuthtypesName:- type: objectAuthtypesOIDCConfig:properties:claimMapping:@@ -154,7 +183,7 @@ components:resource:$ref: '#/components/schemas/AuthtypesResource'selector:- $ref: '#/components/schemas/AuthtypesSelector'+ type: stringrequired:- resource- selector@@ -175,6 +204,22 @@ components:provider:type: stringtype: object+ AuthtypesPatchableObjects:+ properties:+ additions:+ items:+ $ref: '#/components/schemas/AuthtypesGettableObjects'+ nullable: true+ type: array+ deletions:+ items:+ $ref: '#/components/schemas/AuthtypesGettableObjects'+ nullable: true+ type: array+ required:+ - additions+ - deletions+ type: objectAuthtypesPostableAuthDomain:properties:config:@@ -199,7 +244,7 @@ components:AuthtypesResource:properties:name:- $ref: '#/components/schemas/AuthtypesName'+ type: stringtype:type: stringrequired:@@ -231,8 +276,6 @@ components:samlIdp:type: stringtype: object- AuthtypesSelector:- type: objectAuthtypesSessionContext:properties:exists:@@ -245,8 +288,6 @@ components:type: objectAuthtypesTransaction:properties:- id:- type: stringobject:$ref: '#/components/schemas/AuthtypesObject'relation:@@ -1668,40 +1709,6 @@ components:- status- errortype: object- RoletypesGettableResources:- properties:- relations:- additionalProperties:- items:- type: string- type: array- nullable: true- type: object- resources:- items:- $ref: '#/components/schemas/AuthtypesResource'- nullable: true- type: array- required:- - resources- - relations- type: object- RoletypesPatchableObjects:- properties:- additions:- items:- $ref: '#/components/schemas/AuthtypesObject'- nullable: true- type: array- deletions:- items:- $ref: '#/components/schemas/AuthtypesObject'- nullable: true- type: array- required:- - additions- - deletions- type: objectRoletypesPatchableRole:properties:description:@@ -1737,6 +1744,7 @@ components:format: date-timetype: stringrequired:+ - id- name- description- type@@ -1874,6 +1882,8 @@ components:$ref: '#/components/schemas/TypesUser'userId:type: string+ required:+ - idtype: objectTypesGettableGlobalConfig:properties:@@ -1886,6 +1896,8 @@ components:properties:id:type: string+ required:+ - idtype: objectTypesInvite:properties:@@ -1909,6 +1921,8 @@ components:updatedAt:format: date-timetype: string+ required:+ - idtype: objectTypesOrganization:properties:@@ -1929,6 +1943,8 @@ components:updatedAt:format: date-timetype: string+ required:+ - idtype: objectTypesPostableAPIKey:properties:@@ -1992,6 +2008,8 @@ components:type: stringtoken:type: string+ required:+ - idtype: objectTypesStorableAPIKey:properties:@@ -2017,6 +2035,8 @@ components:type: stringuserId:type: string+ required:+ - idtype: objectTypesUser:properties:@@ -2038,6 +2058,8 @@ components:updatedAt:format: date-timetype: string+ required:+ - idtype: objectZeustypesGettableHost:properties:@@ -2170,6 +2192,35 @@ paths:summary: Check permissionstags:- authz+ /api/v1/authz/resources:+ get:+ deprecated: false+ description: Gets all the available resources+ operationId: AuthzResources+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/AuthtypesGettableResources'+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: OK+ "500":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Internal Server Error+ summary: Get resources+ tags:+ - authz/api/v1/changePassword/{id}:post:deprecated: false@@ -4342,7 +4393,7 @@ paths:properties:data:items:- $ref: '#/components/schemas/AuthtypesObject'+ $ref: '#/components/schemas/AuthtypesGettableObjects'type: arraystatus:type: string@@ -4415,7 +4466,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/RoletypesPatchableObjects'+ $ref: '#/components/schemas/AuthtypesPatchableObjects'responses:"204":content:@@ -4473,52 +4524,6 @@ paths:summary: Patch objects for a role by relationtags:- role- /api/v1/roles/resources:- get:- deprecated: false- description: Gets all the available resources for role assignment- operationId: GetResources- responses:- "200":- content:- application/json:- schema:- properties:- data:- $ref: '#/components/schemas/RoletypesGettableResources'- status:- type: string- required:- - status- - data- type: object- description: OK- "401":- content:- application/json:- schema:- $ref: '#/components/schemas/RenderErrorResponse'- description: Unauthorized- "403":- content:- application/json:- schema:- $ref: '#/components/schemas/RenderErrorResponse'- description: Forbidden- "500":- content:- application/json:- schema:- $ref: '#/components/schemas/RenderErrorResponse'- description: Internal Server Error- security:- - api_key:- - ADMIN- - tokenizer:- - ADMIN- summary: Get resources- tags:- - role/api/v1/user:get:deprecated: falsediff --git a/ee/authz/openfgaauthz/provider.go b/ee/authz/openfgaauthz/provider.goindex a69cae0d7a..266b32d959 100644--- a/ee/authz/openfgaauthz/provider.go+++ b/ee/authz/openfgaauthz/provider.go@@ -171,8 +171,6 @@ func (provider *provider) GetResources(_ context.Context) []*authtypes.Resourcefor _, register := range provider.registry {typeables = append(typeables, register.MustGetTypeables()...)}- // role module cannot self register itself!- typeables = append(typeables, provider.MustGetTypeables()...)resources := make([]*authtypes.Resource, 0)for _, typeable := range typeables {@@ -259,7 +257,7 @@ func (provider *provider) Delete(ctx context.Context, orgID valuer.UUID, id valu}role := roletypes.NewRoleFromStorableRole(storableRole)- err = role.CanEditDelete()+ err = role.ErrIfManaged()if err != nil {return err}diff --git a/frontend/src/api/generated/services/authz/index.ts b/frontend/src/api/generated/services/authz/index.tsindex 6ea4e55a3d..7e6aaa9d3c 100644--- a/frontend/src/api/generated/services/authz/index.ts+++ b/frontend/src/api/generated/services/authz/index.ts@@ -5,17 +5,24 @@* SigNoz*/import type {+ InvalidateOptions,MutationFunction,+ QueryClient,+ QueryFunction,+ QueryKey,UseMutationOptions,UseMutationResult,+ UseQueryOptions,+ UseQueryResult,} from 'react-query';-import { useMutation } from 'react-query';+import { useMutation, useQuery } from 'react-query';import type { BodyType, ErrorType } from '../../../generatedAPIInstance';import { GeneratedAPIInstance } from '../../../generatedAPIInstance';import type {AuthtypesTransactionDTO,AuthzCheck200,+ AuthzResources200,RenderErrorResponseDTO,} from '../sigNoz.schemas';@@ -106,3 +113,88 @@ export const useAuthzCheck = <return useMutation(mutationOptions);};+/**+ * Gets all the available resources+ * @summary Get resources+ */+export const authzResources = (signal?: AbortSignal) => {+ return GeneratedAPIInstance<AuthzResources200>({+ url: `/api/v1/authz/resources`,+ method: 'GET',+ signal,+ });+};++export const getAuthzResourcesQueryKey = () => {+ return [`/api/v1/authz/resources`] as const;+};++export const getAuthzResourcesQueryOptions = <+ TData = Awaited<ReturnType<typeof authzResources>>,+ TError = ErrorType<RenderErrorResponseDTO>+>(options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof authzResources>>,+ TError,+ TData+ >;+}) => {+ const { query: queryOptions } = options ?? {};++ const queryKey = queryOptions?.queryKey ?? getAuthzResourcesQueryKey();++ const queryFn: QueryFunction<Awaited<ReturnType<typeof authzResources>>> = ({+ signal,+ }) => authzResources(signal);++ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<+ Awaited<ReturnType<typeof authzResources>>,+ TError,+ TData+ > & { queryKey: QueryKey };+};++export type AuthzResourcesQueryResult = NonNullable<+ Awaited<ReturnType<typeof authzResources>>+>;+export type AuthzResourcesQueryError = ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Get resources+ */++export function useAuthzResources<+ TData = Awaited<ReturnType<typeof authzResources>>,+ TError = ErrorType<RenderErrorResponseDTO>+>(options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof authzResources>>,+ TError,+ TData+ >;+}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {+ const queryOptions = getAuthzResourcesQueryOptions(options);++ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {+ queryKey: QueryKey;+ };++ query.queryKey = queryOptions.queryKey;++ return query;+}++/**+ * @summary Get resources+ */+export const invalidateAuthzResources = async (+ queryClient: QueryClient,+ options?: InvalidateOptions,+): Promise<QueryClient> => {+ await queryClient.invalidateQueries(+ { queryKey: getAuthzResourcesQueryKey() },+ options,+ );++ return queryClient;+};diff --git a/frontend/src/api/generated/services/role/index.ts b/frontend/src/api/generated/services/role/index.tsindex 8d5297482d..c055767f27 100644--- a/frontend/src/api/generated/services/role/index.ts+++ b/frontend/src/api/generated/services/role/index.ts@@ -20,18 +20,17 @@ import { useMutation, useQuery } from 'react-query';import type { BodyType, ErrorType } from '../../../generatedAPIInstance';import { GeneratedAPIInstance } from '../../../generatedAPIInstance';import type {+ AuthtypesPatchableObjectsDTO,CreateRole201,DeleteRolePathParameters,GetObjects200,GetObjectsPathParameters,- GetResources200,GetRole200,GetRolePathParameters,ListRoles200,PatchObjectsPathParameters,PatchRolePathParameters,RenderErrorResponseDTO,- RoletypesPatchableObjectsDTO,RoletypesPatchableRoleDTO,RoletypesPostableRoleDTO,} from '../sigNoz.schemas';@@ -575,13 +574,13 @@ export const invalidateGetObjects = async (*/export const patchObjects = ({ id, relation }: PatchObjectsPathParameters,- roletypesPatchableObjectsDTO: BodyType<RoletypesPatchableObjectsDTO>,+ authtypesPatchableObjectsDTO: BodyType<AuthtypesPatchableObjectsDTO>,) => {return GeneratedAPIInstance<string>({url: `/api/v1/roles/${id}/relation/${relation}/objects`,method: 'PATCH',headers: { 'Content-Type': 'application/json' },- data: roletypesPatchableObjectsDTO,+ data: authtypesPatchableObjectsDTO,});};@@ -594,7 +593,7 @@ export const getPatchObjectsMutationOptions = <TError,{pathParams: PatchObjectsPathParameters;- data: BodyType<RoletypesPatchableObjectsDTO>;+ data: BodyType<AuthtypesPatchableObjectsDTO>;},TContext>;@@ -603,7 +602,7 @@ export const getPatchObjectsMutationOptions = <TError,{pathParams: PatchObjectsPathParameters;- data: BodyType<RoletypesPatchableObjectsDTO>;+ data: BodyType<AuthtypesPatchableObjectsDTO>;},TContext> => {@@ -620,7 +619,7 @@ export const getPatchObjectsMutationOptions = <Awaited<ReturnType<typeof patchObjects>>,{pathParams: PatchObjectsPathParameters;- data: BodyType<RoletypesPatchableObjectsDTO>;+ data: BodyType<AuthtypesPatchableObjectsDTO>;}> = (props) => {const { pathParams, data } = props ?? {};@@ -634,7 +633,7 @@ export const getPatchObjectsMutationOptions = <export type PatchObjectsMutationResult = NonNullable<Awaited<ReturnType<typeof patchObjects>>>;-export type PatchObjectsMutationBody = BodyType<RoletypesPatchableObjectsDTO>;+export type PatchObjectsMutationBody = BodyType<AuthtypesPatchableObjectsDTO>;export type PatchObjectsMutationError = ErrorType<RenderErrorResponseDTO>;/**@@ -649,7 +648,7 @@ export const usePatchObjects = <TError,{pathParams: PatchObjectsPathParameters;- data: BodyType<RoletypesPatchableObjectsDTO>;+ data: BodyType<AuthtypesPatchableObjectsDTO>;},TContext>;@@ -658,7 +657,7 @@ export const usePatchObjects = <TError,{pathParams: PatchObjectsPathParameters;- data: BodyType<RoletypesPatchableObjectsDTO>;+ data: BodyType<AuthtypesPatchableObjectsDTO>;},TContext> => {@@ -666,88 +665,3 @@ export const usePatchObjects = <return useMutation(mutationOptions);};-/**- * Gets all the available resources for role assignment- * @summary Get resources- */-export const getResources = (signal?: AbortSignal) => {- return GeneratedAPIInstance<GetResources200>({- url: `/api/v1/roles/resources`,- method: 'GET',- signal,- });-};--export const getGetResourcesQueryKey = () => {- return [`/api/v1/roles/resources`] as const;-};--export const getGetResourcesQueryOptions = <- TData = Awaited<ReturnType<typeof getResources>>,- TError = ErrorType<RenderErrorResponseDTO>->(options?: {- query?: UseQueryOptions<- Awaited<ReturnType<typeof getResources>>,- TError,- TData- >;-}) => {- const { query: queryOptions } = options ?? {};-- const queryKey = queryOptions?.queryKey ?? getGetResourcesQueryKey();-- const queryFn: QueryFunction<Awaited<ReturnType<typeof getResources>>> = ({- signal,- }) => getResources(signal);-- return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<- Awaited<ReturnType<typeof getResources>>,- TError,- TData- > & { queryKey: QueryKey };-};--export type GetResourcesQueryResult = NonNullable<- Awaited<ReturnType<typeof getResources>>->;-export type GetResourcesQueryError = ErrorType<RenderErrorResponseDTO>;--/**- * @summary Get resources- */--export function useGetResources<- TData = Awaited<ReturnType<typeof getResources>>,- TError = ErrorType<RenderErrorResponseDTO>->(options?: {- query?: UseQueryOptions<- Awaited<ReturnType<typeof getResources>>,- TError,- TData- >;-}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {- const queryOptions = getGetResourcesQueryOptions(options);-- const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {- queryKey: QueryKey;- };-- query.queryKey = queryOptions.queryKey;-- return query;-}--/**- * @summary Get resources- */-export const invalidateGetResources = async (- queryClient: QueryClient,- options?: InvalidateOptions,-): Promise<QueryClient> => {- await queryClient.invalidateQueries(- { queryKey: getGetResourcesQueryKey() },- options,- );-- return queryClient;-};diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex 9869a5f11f..07b91b4546 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -81,7 +81,7 @@ export interface AuthtypesGettableAuthDomainDTO {/*** @type string*/- id?: string;+ id: string;/*** @type string*/@@ -108,6 +108,33 @@ export interface AuthtypesGettableAuthDomainDTO {updatedAt?: Date;}+export interface AuthtypesGettableObjectsDTO {+ resource: AuthtypesResourceDTO;+ /**+ * @type array+ */+ selectors: string[];+}++/**+ * @nullable+ */+export type AuthtypesGettableResourcesDTORelations = {+ [key: string]: string[];+} | null;++export interface AuthtypesGettableResourcesDTO {+ /**+ * @type object+ * @nullable true+ */+ relations: AuthtypesGettableResourcesDTORelations;+ /**+ * @type array+ */+ resources: AuthtypesResourceDTO[];+}+export interface AuthtypesGettableTokenDTO {/*** @type string@@ -182,10 +209,6 @@ export interface AuthtypesGoogleConfigDTO {serviceAccountJson?: string;}-export interface AuthtypesNameDTO {- [key: string]: unknown;-}-export interface AuthtypesOIDCConfigDTO {claimMapping?: AuthtypesAttributeMappingDTO;/**@@ -216,7 +239,10 @@ export interface AuthtypesOIDCConfigDTO {export interface AuthtypesObjectDTO {resource: AuthtypesResourceDTO;- selector: AuthtypesSelectorDTO;+ /**+ * @type string+ */+ selector: string;}export interface AuthtypesOrgSessionContextDTO {@@ -239,6 +265,19 @@ export interface AuthtypesPasswordAuthNSupportDTO {provider?: string;}+export interface AuthtypesPatchableObjectsDTO {+ /**+ * @type array+ * @nullable true+ */+ additions: AuthtypesGettableObjectsDTO[] | null;+ /**+ * @type array+ * @nullable true+ */+ deletions: AuthtypesGettableObjectsDTO[] | null;+}+export interface AuthtypesPostableAuthDomainDTO {config?: AuthtypesAuthDomainConfigDTO;/**@@ -270,7 +309,10 @@ export interface AuthtypesPostableRotateTokenDTO {}export interface AuthtypesResourceDTO {- name: AuthtypesNameDTO;+ /**+ * @type string+ */+ name: string;/*** @type string*/@@ -320,10 +362,6 @@ export interface AuthtypesSamlConfigDTO {samlIdp?: string;}-export interface AuthtypesSelectorDTO {- [key: string]: unknown;-}-export interface AuthtypesSessionContextDTO {/*** @type boolean@@ -337,10 +375,6 @@ export interface AuthtypesSessionContextDTO {}export interface AuthtypesTransactionDTO {- /**- * @type string- */- id?: string;object: AuthtypesObjectDTO;/*** @type string@@ -1992,39 +2026,6 @@ export interface RenderErrorResponseDTO {status: string;}-/**- * @nullable- */-export type RoletypesGettableResourcesDTORelations = {- [key: string]: string[];-} | null;--export interface RoletypesGettableResourcesDTO {- /**- * @type object- * @nullable true- */- relations: RoletypesGettableResourcesDTORelations;- /**- * @type array- * @nullable true- */- resources: AuthtypesResourceDTO[] | null;-}--export interface RoletypesPatchableObjectsDTO {- /**- * @type array- * @nullable true- */- additions: AuthtypesObjectDTO[] | null;- /**- * @type array- * @nullable true- */- deletions: AuthtypesObjectDTO[] | null;-}-export interface RoletypesPatchableRoleDTO {/*** @type string@@ -2056,7 +2057,7 @@ export interface RoletypesRoleDTO {/*** @type string*/- id?: string;+ id: string;/*** @type string*/@@ -2197,7 +2198,7 @@ export interface TypesGettableAPIKeyDTO {/*** @type string*/- id?: string;+ id: string;/*** @type integer* @format int64@@ -2250,7 +2251,7 @@ export interface TypesIdentifiableDTO {/*** @type string*/- id?: string;+ id: string;}export interface TypesInviteDTO {@@ -2266,7 +2267,7 @@ export interface TypesInviteDTO {/*** @type string*/- id?: string;+ id: string;/*** @type string*/@@ -2311,7 +2312,7 @@ export interface TypesOrganizationDTO {/*** @type string*/- id?: string;+ id: string;/*** @type integer* @minimum 0@@ -2417,7 +2418,7 @@ export interface TypesResetPasswordTokenDTO {/*** @type string*/- id?: string;+ id: string;/*** @type string*/@@ -2441,7 +2442,7 @@ export interface TypesStorableAPIKeyDTO {/*** @type string*/- id?: string;+ id: string;/*** @type string*/@@ -2490,7 +2491,7 @@ export interface TypesUserDTO {/*** @type string*/- id?: string;+ id: string;/*** @type boolean*/@@ -2606,6 +2607,14 @@ export type AuthzCheck200 = {status: string;};+export type AuthzResources200 = {+ data: AuthtypesGettableResourcesDTO;+ /**+ * @type string+ */+ status: string;+};+export type ChangePasswordPathParameters = {id: string;};@@ -3017,7 +3026,7 @@ export type GetObjects200 = {/*** @type array*/- data: AuthtypesObjectDTO[];+ data: AuthtypesGettableObjectsDTO[];/*** @type string*/@@ -3028,14 +3037,6 @@ export type PatchObjectsPathParameters = {id: string;relation: string;};-export type GetResources200 = {- data: RoletypesGettableResourcesDTO;- /**- * @type string- */- status: string;-};-export type ListUsers200 = {/*** @type arraydiff --git a/frontend/src/container/OrganizationSettings/AuthDomain/__tests__/SSOEnforcementToggle.test.tsx b/frontend/src/container/OrganizationSettings/AuthDomain/__tests__/SSOEnforcementToggle.test.tsxindex 721bf3a8c9..94cafe26a5 100644--- a/frontend/src/container/OrganizationSettings/AuthDomain/__tests__/SSOEnforcementToggle.test.tsx+++ b/frontend/src/container/OrganizationSettings/AuthDomain/__tests__/SSOEnforcementToggle.test.tsx@@ -116,7 +116,7 @@ describe('SSOEnforcementToggle', () => {render(<SSOEnforcementToggleisDefaultChecked={true}- record={{ ...mockGoogleAuthDomain, id: undefined }}+ record={{ ...mockGoogleAuthDomain, id: '' }}/>,);diff --git a/pkg/apiserver/signozapiserver/authz.go b/pkg/apiserver/signozapiserver/authz.goindex badbc6e602..7a9b241238 100644--- a/pkg/apiserver/signozapiserver/authz.go+++ b/pkg/apiserver/signozapiserver/authz.go@@ -26,5 +26,22 @@ func (provider *provider) addAuthzRoutes(router *mux.Router) error {return err}+ if err := router.Handle("/api/v1/authz/resources", handler.New(provider.authZ.OpenAccess(provider.authzHandler.GetResources), handler.OpenAPIDef{+ ID: "AuthzResources",+ Tags: []string{"authz"},+ Summary: "Get resources",+ Description: "Gets all the available resources",+ Request: nil,+ RequestContentType: "",+ Response: new(authtypes.GettableResources),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{},+ Deprecated: false,+ SecuritySchemes: nil,+ })).Methods(http.MethodGet).GetError(); err != nil {+ return err+ }+return nil}diff --git a/pkg/apiserver/signozapiserver/role.go b/pkg/apiserver/signozapiserver/role.goindex 6271791813..e374157ad2 100644--- a/pkg/apiserver/signozapiserver/role.go+++ b/pkg/apiserver/signozapiserver/role.go@@ -45,23 +45,6 @@ func (provider *provider) addRoleRoutes(router *mux.Router) error {return err}- if err := router.Handle("/api/v1/roles/resources", handler.New(provider.authZ.AdminAccess(provider.authzHandler.GetResources), handler.OpenAPIDef{- ID: "GetResources",- Tags: []string{"role"},- Summary: "Get resources",- Description: "Gets all the available resources for role assignment",- Request: nil,- RequestContentType: "",- Response: new(roletypes.GettableResources),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{},- Deprecated: false,- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),- })).Methods(http.MethodGet).GetError(); err != nil {- return err- }-if err := router.Handle("/api/v1/roles/{id}", handler.New(provider.authZ.AdminAccess(provider.authzHandler.Get), handler.OpenAPIDef{ID: "GetRole",Tags: []string{"role"},@@ -86,7 +69,7 @@ func (provider *provider) addRoleRoutes(router *mux.Router) error {Description: "Gets all objects connected to the specified role via a given relation type",Request: nil,RequestContentType: "",- Response: make([]*authtypes.Object, 0),+ Response: make([]*authtypes.GettableObjects, 0),ResponseContentType: "application/json",SuccessStatusCode: http.StatusOK,ErrorStatusCodes: []int{http.StatusNotFound, http.StatusNotImplemented, http.StatusUnavailableForLegalReasons},@@ -118,7 +101,7 @@ func (provider *provider) addRoleRoutes(router *mux.Router) error {Tags: []string{"role"},Summary: "Patch objects for a role by relation",Description: "Patches the objects connected to the specified role via a given relation type",- Request: new(roletypes.PatchableObjects),+ Request: new(authtypes.PatchableObjects),RequestContentType: "",Response: nil,ResponseContentType: "application/json",diff --git a/pkg/authz/openfgaauthz/provider.go b/pkg/authz/openfgaauthz/provider.goindex 045399bed8..9373043f98 100644--- a/pkg/authz/openfgaauthz/provider.go+++ b/pkg/authz/openfgaauthz/provider.go@@ -190,7 +190,7 @@ func (provider *provider) GetOrCreate(_ context.Context, _ valuer.UUID, _ *rolet}func (provider *provider) GetResources(_ context.Context) []*authtypes.Resource {- return nil+ return []*authtypes.Resource{}}func (provider *provider) GetObjects(ctx context.Context, orgID valuer.UUID, id valuer.UUID, relation authtypes.Relation) ([]*authtypes.Object, error) {diff --git a/pkg/authz/signozauthzapi/handler.go b/pkg/authz/signozauthzapi/handler.goindex 0900e1f902..70abe90d26 100644--- a/pkg/authz/signozauthzapi/handler.go+++ b/pkg/authz/signozauthzapi/handler.go@@ -110,13 +110,13 @@ func (handler *handler) GetObjects(rw http.ResponseWriter, r *http.Request) {return}- render.Success(rw, http.StatusOK, objects)+ render.Success(rw, http.StatusOK, authtypes.NewGettableObjects(objects))}func (handler *handler) GetResources(rw http.ResponseWriter, r *http.Request) {resources := handler.authz.GetResources(r.Context())- render.Success(rw, http.StatusOK, roletypes.NewGettableResources(resources))+ render.Success(rw, http.StatusOK, authtypes.NewGettableResources(resources))}func (handler *handler) List(rw http.ResponseWriter, r *http.Request) {@@ -197,25 +197,30 @@ func (handler *handler) PatchObjects(rw http.ResponseWriter, r *http.Request) {return}- req := new(roletypes.PatchableObjects)- if err := binding.JSON.BindBody(r.Body, req); err != nil {+ role, err := handler.authz.Get(ctx, valuer.MustNewUUID(claims.OrgID), id)+ if err != nil {render.Error(rw, err)return}- role, err := handler.authz.Get(ctx, valuer.MustNewUUID(claims.OrgID), id)- if err != nil {+ if err := role.ErrIfManaged(); err != nil {+ render.Error(rw, err)+ return+ }++ req := new(authtypes.PatchableObjects)+ if err := binding.JSON.BindBody(r.Body, req); err != nil {render.Error(rw, err)return}- patchableObjects, err := role.NewPatchableObjects(req.Additions, req.Deletions, relation)+ additions, deletions, err := authtypes.NewPatchableObjects(req.Additions, req.Deletions, relation)if err != nil {render.Error(rw, err)return}- err = handler.authz.PatchObjects(ctx, valuer.MustNewUUID(claims.OrgID), role.Name, relation, patchableObjects.Additions, patchableObjects.Deletions)+ err = handler.authz.PatchObjects(ctx, valuer.MustNewUUID(claims.OrgID), role.Name, relation, additions, deletions)if err != nil {render.Error(rw, err)returndiff --git a/pkg/types/authtypes/name.go b/pkg/types/authtypes/name.goindex 6585664a7d..6ee9351278 100644--- a/pkg/types/authtypes/name.go+++ b/pkg/types/authtypes/name.go@@ -1,6 +1,7 @@package authtypesimport (+ "encoding""encoding/json""regexp"@@ -10,8 +11,10 @@ import (var (nameRegex = regexp.MustCompile("^[a-z-]{1,50}$")- _ json.Marshaler = new(Name)- _ json.Unmarshaler = new(Name)+ _ json.Marshaler = new(Name)+ _ json.Unmarshaler = new(Name)+ _ encoding.TextMarshaler = new(Name)+ _ encoding.TextUnmarshaler = new(Name))type Name struct {@@ -58,3 +61,16 @@ func (name *Name) UnmarshalJSON(data []byte) error {*name = shadowreturn nil}++func (name Name) MarshalText() ([]byte, error) {+ return []byte(name.val), nil+}++func (name *Name) UnmarshalText(text []byte) error {+ shadow, err := NewName(string(text))+ if err != nil {+ return err+ }+ *name = shadow+ return nil+}diff --git a/pkg/types/authtypes/object.go b/pkg/types/authtypes/object.gonew file mode 100644index 0000000000..ce1187d762--- /dev/null+++ b/pkg/types/authtypes/object.go@@ -0,0 +1,177 @@+package authtypes++import (+ "encoding/json"+ "slices"+ "strings"++ "github.com/SigNoz/signoz/pkg/errors"+)++type Resource struct {+ Name Name `json:"name" required:"true"`+ Type Type `json:"type" required:"true"`+}++type GettableResources struct {+ Resources []*Resource `json:"resources" required:"true" nullable:"false"`+ Relations map[Relation][]Type `json:"relations" required:"true"`+}++type Object struct {+ Resource Resource `json:"resource" required:"true"`+ Selector Selector `json:"selector" required:"true"`+}++type GettableObjects struct {+ Resource Resource `json:"resource" required:"true"`+ Selectors []Selector `json:"selectors" required:"true" nullable:"false"`+}++type PatchableObjects struct {+ Additions []*GettableObjects `json:"additions" required:"true" nullable:"true"`+ Deletions []*GettableObjects `json:"deletions" required:"true" nullable:"true"`+}++func NewObject(resource Resource, selector Selector) (*Object, error) {+ err := IsValidSelector(resource.Type, selector.String())+ if err != nil {+ return nil, err+ }++ return &Object{Resource: resource, Selector: selector}, nil+}++func NewObjectsFromGettableObjects(patchableObjects []*GettableObjects) ([]*Object, error) {+ objects := make([]*Object, 0)++ for _, patchObject := range patchableObjects {+ for _, selector := range patchObject.Selectors {+ object, err := NewObject(patchObject.Resource, selector)+ if err != nil {+ return nil, err+ }++ objects = append(objects, object)+ }+ }++ return objects, nil+}++func NewPatchableObjects(additions []*GettableObjects, deletions []*GettableObjects, relation Relation) ([]*Object, []*Object, error) {+ if len(additions) == 0 && len(deletions) == 0 {+ return nil, nil, errors.New(errors.TypeInvalidInput, ErrCodeInvalidPatchObject, "empty object patch request received, at least one of additions or deletions must be present")+ }++ for _, object := range additions {+ if !slices.Contains(TypeableRelations[object.Resource.Type], relation) {+ return nil, nil, errors.Newf(errors.TypeInvalidInput, ErrCodeAuthZInvalidRelation, "relation %s is invalid for type %s", relation.StringValue(), object.Resource.Type.StringValue())+ }+ }++ for _, object := range deletions {+ if !slices.Contains(TypeableRelations[object.Resource.Type], relation) {+ return nil, nil, errors.Newf(errors.TypeInvalidInput, ErrCodeAuthZInvalidRelation, "relation %s is invalid for type %s", relation.StringValue(), object.Resource.Type.StringValue())+ }+ }++ additionObjects, err := NewObjectsFromGettableObjects(additions)+ if err != nil {+ return nil, nil, err+ }++ deletionsObjects, err := NewObjectsFromGettableObjects(deletions)+ if err != nil {+ return nil, nil, err+ }++ return additionObjects, deletionsObjects, nil+}++func NewGettableResources(resources []*Resource) *GettableResources {+ return &GettableResources{+ Resources: resources,+ Relations: RelationsTypeable,+ }+}++func NewGettableObjects(objects []*Object) []*GettableObjects {+ grouped := make(map[Resource][]Selector)+ for _, obj := range objects {+ key := obj.Resource+ if _, ok := grouped[key]; !ok {+ grouped[key] = make([]Selector, 0)+ }++ grouped[key] = append(grouped[key], obj.Selector)+ }++ gettableObjects := make([]*GettableObjects, 0, len(grouped))+ for resource, selectors := range grouped {+ gettableObjects = append(gettableObjects, &GettableObjects{+ Resource: resource,+ Selectors: selectors,+ })+ }++ return gettableObjects+}++func MustNewObject(resource Resource, selector Selector) *Object {+ object, err := NewObject(resource, selector)+ if err != nil {+ panic(err)+ }++ return object+}++func MustNewObjectFromString(input string) *Object {+ parts := strings.Split(input, "/")+ if len(parts) != 4 {+ panic(errors.Newf(errors.TypeInternal, errors.CodeInternal, "invalid input format: %s", input))+ }++ typeParts := strings.Split(parts[0], ":")+ if len(typeParts) != 2 {+ panic(errors.Newf(errors.TypeInternal, errors.CodeInternal, "invalid type format: %s", parts[0]))+ }++ resource := Resource{+ Type: MustNewType(typeParts[0]),+ Name: MustNewName(parts[2]),+ }++ selector := MustNewSelector(resource.Type, parts[3])++ return &Object{Resource: resource, Selector: selector}+}++func MustNewObjectsFromStringSlice(input []string) []*Object {+ objects := make([]*Object, 0, len(input))+ for _, str := range input {+ objects = append(objects, MustNewObjectFromString(str))+ }+ return objects+}++func (object *Object) UnmarshalJSON(data []byte) error {+ var shadow = struct {+ Resource Resource+ Selector Selector+ }{}++ err := json.Unmarshal(data, &shadow)+ if err != nil {+ return err+ }++ obj, err := NewObject(shadow.Resource, shadow.Selector)+ if err != nil {+ return err+ }++ *object = *obj+ return nil+}diff --git a/pkg/types/authtypes/relation.go b/pkg/types/authtypes/relation.goindex 7cac3be315..41643c093a 100644--- a/pkg/types/authtypes/relation.go+++ b/pkg/types/authtypes/relation.go@@ -7,6 +7,7 @@ import (var (ErrCodeAuthZInvalidRelation = errors.MustNewCode("authz_invalid_relation")+ ErrCodeInvalidPatchObject = errors.MustNewCode("authz_invalid_patch_objects"))var (@@ -26,6 +27,14 @@ var TypeableRelations = map[Type][]Relation{TypeMetaResources: {RelationCreate, RelationList},}+var RelationsTypeable = map[Relation][]Type{+ RelationCreate: {TypeMetaResources},+ RelationRead: {TypeUser, TypeRole, TypeOrganization, TypeMetaResource},+ RelationList: {TypeMetaResources},+ RelationUpdate: {TypeUser, TypeRole, TypeOrganization, TypeMetaResource},+ RelationDelete: {TypeUser, TypeRole, TypeOrganization, TypeMetaResource},+}+type Relation struct{ valuer.String }func NewRelation(relation string) (Relation, error) {diff --git a/pkg/types/authtypes/selector.go b/pkg/types/authtypes/selector.goindex ea39d87536..dd243902ca 100644--- a/pkg/types/authtypes/selector.go+++ b/pkg/types/authtypes/selector.go@@ -1,6 +1,7 @@package authtypesimport (+ "encoding""encoding/json""net/http""regexp"@@ -15,8 +16,10 @@ var ()var (- _ json.Marshaler = new(Selector)- _ json.Unmarshaler = new(Selector)+ _ json.Marshaler = new(Selector)+ _ json.Unmarshaler = new(Selector)+ _ encoding.TextMarshaler = new(Selector)+ _ encoding.TextUnmarshaler = new(Selector))var (@@ -79,6 +82,15 @@ func (typed *Selector) UnmarshalJSON(data []byte) error {return nil}+func (selector Selector) MarshalText() ([]byte, error) {+ return []byte(selector.val), nil+}++func (selector *Selector) UnmarshalText(text []byte) error {+ *selector = Selector{val: string(text)}+ return nil+}+func IsValidSelector(typed Type, selector string) error {switch typed {case TypeUser:diff --git a/pkg/types/authtypes/transaction.go b/pkg/types/authtypes/transaction.goindex 59483ebf8c..6c59fe16ef 100644--- a/pkg/types/authtypes/transaction.go+++ b/pkg/types/authtypes/transaction.go@@ -3,24 +3,13 @@ package authtypesimport ("encoding/json""slices"- "strings""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/valuer")-type Resource struct {- Name Name `json:"name" required:"true"`- Type Type `json:"type" required:"true"`-}--type Object struct {- Resource Resource `json:"resource" required:"true"`- Selector Selector `json:"selector" required:"true"`-}-type Transaction struct {- ID valuer.UUID `json:"id"`+ ID valuer.UUID `json:"-"`Relation Relation `json:"relation" required:"true"`Object Object `json:"object" required:"true"`}@@ -31,53 +20,6 @@ type GettableTransaction struct {Authorized bool `json:"authorized" required:"true"`}-func NewObject(resource Resource, selector Selector) (*Object, error) {- err := IsValidSelector(resource.Type, selector.val)- if err != nil {- return nil, err- }-- return &Object{Resource: resource, Selector: selector}, nil-}--func MustNewObject(resource Resource, selector Selector) *Object {- object, err := NewObject(resource, selector)- if err != nil {- panic(err)- }-- return object-}--func MustNewObjectFromString(input string) *Object {- parts := strings.Split(input, "/")- if len(parts) != 4 {- panic(errors.Newf(errors.TypeInternal, errors.CodeInternal, "invalid input format: %s", input))- }-- typeParts := strings.Split(parts[0], ":")- if len(typeParts) != 2 {- panic(errors.Newf(errors.TypeInternal, errors.CodeInternal, "invalid type format: %s", parts[0]))- }-- resource := Resource{- Type: MustNewType(typeParts[0]),- Name: MustNewName(parts[2]),- }-- selector := MustNewSelector(resource.Type, parts[3])-- return &Object{Resource: resource, Selector: selector}-}--func MustNewObjectsFromStringSlice(input []string) []*Object {- objects := make([]*Object, 0, len(input))- for _, str := range input {- objects = append(objects, MustNewObjectFromString(str))- }- return objects-}-func NewTransaction(relation Relation, object Object) (*Transaction, error) {if !slices.Contains(TypeableRelations[object.Resource.Type], relation) {return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeAuthZInvalidRelation, "invalid relation %s for type %s", relation.StringValue(), object.Resource.Type.StringValue())@@ -100,26 +42,6 @@ func NewGettableTransaction(transactions []*Transaction, results map[string]*Tupreturn gettableTransactions}-func (object *Object) UnmarshalJSON(data []byte) error {- var shadow = struct {- Resource Resource- Selector Selector- }{}-- err := json.Unmarshal(data, &shadow)- if err != nil {- return err- }-- obj, err := NewObject(shadow.Resource, shadow.Selector)- if err != nil {- return err- }-- *object = *obj- return nil-}-func (transaction *Transaction) UnmarshalJSON(data []byte) error {var shadow = struct {Relation Relationdiff --git a/pkg/types/identity.go b/pkg/types/identity.goindex 3d94b2ee3f..c76dc4e1ca 100644--- a/pkg/types/identity.go+++ b/pkg/types/identity.go@@ -5,5 +5,5 @@ import ()type Identifiable struct {- ID valuer.UUID `json:"id" bun:"id,pk,type:text"`+ ID valuer.UUID `json:"id" bun:"id,pk,type:text" required:"true"`}diff --git a/pkg/types/roletypes/role.go b/pkg/types/roletypes/role.goindex 2eb5141f78..10b4c6ae67 100644--- a/pkg/types/roletypes/role.go+++ b/pkg/types/roletypes/role.go@@ -3,7 +3,6 @@ package roletypesimport ("encoding/json""regexp"- "slices""time""github.com/SigNoz/signoz/pkg/errors"@@ -84,16 +83,6 @@ type PatchableRole struct {Description string `json:"description" required:"true"`}-type PatchableObjects struct {- Additions []*authtypes.Object `json:"additions" required:"true"`- Deletions []*authtypes.Object `json:"deletions" required:"true"`-}--type GettableResources struct {- Resources []*authtypes.Resource `json:"resources" required:"true"`- Relations map[authtypes.Type][]authtypes.Relation `json:"relations" required:"true"`-}-func NewStorableRoleFromRole(role *Role) *StorableRole {return &StorableRole{Identifiable: role.Identifiable,@@ -142,15 +131,8 @@ func NewManagedRoles(orgID valuer.UUID) []*Role {}-func NewGettableResources(resources []*authtypes.Resource) *GettableResources {- return &GettableResources{- Resources: resources,- Relations: authtypes.TypeableRelations,- }-}-func (role *Role) PatchMetadata(description string) error {- err := role.CanEditDelete()+ err := role.ErrIfManaged()if err != nil {return err}@@ -160,32 +142,7 @@ func (role *Role) PatchMetadata(description string) error {return nil}-func (role *Role) NewPatchableObjects(additions []*authtypes.Object, deletions []*authtypes.Object, relation authtypes.Relation) (*PatchableObjects, error) {- err := role.CanEditDelete()- if err != nil {- return nil, err- }-- if len(additions) == 0 && len(deletions) == 0 {- return nil, errors.New(errors.TypeInvalidInput, ErrCodeRoleEmptyPatch, "empty object patch request received, at least one of additions or deletions must be present")- }-- for _, object := range additions {- if !slices.Contains(authtypes.TypeableRelations[object.Resource.Type], relation) {- return nil, errors.Newf(errors.TypeInvalidInput, authtypes.ErrCodeAuthZInvalidRelation, "relation %s is invalid for type %s", relation.StringValue(), object.Resource.Type.StringValue())- }- }-- for _, object := range deletions {- if !slices.Contains(authtypes.TypeableRelations[object.Resource.Type], relation) {- return nil, errors.Newf(errors.TypeInvalidInput, authtypes.ErrCodeAuthZInvalidRelation, "relation %s is invalid for type %s", relation.StringValue(), object.Resource.Type.StringValue())- }- }-- return &PatchableObjects{Additions: additions, Deletions: deletions}, nil-}--func (role *Role) CanEditDelete() error {+func (role *Role) ErrIfManaged() error {if role.Type == RoleTypeManaged {return errors.Newf(errors.TypeInvalidInput, ErrCodeRoleInvalidInput, "cannot edit/delete managed role: %s", role.Name)}