@mondaydotcomorg/monday-authorization 3.3.0-feature-bashanye-navigate-can-action-in-scope-to-graph-9ad5fa5 → 3.3.0-feature-bashanye-navigate-can-action-in-scope-to-graph-752f21a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/DEBUG.md +203 -0
  2. package/dist/authorization-service.d.ts.map +1 -1
  3. package/dist/authorization-service.js +9 -0
  4. package/dist/clients/graph-api.client.d.ts.map +1 -1
  5. package/dist/clients/graph-api.client.js +21 -1
  6. package/dist/clients/platform-api.client.d.ts.map +1 -1
  7. package/dist/clients/platform-api.client.js +24 -1
  8. package/dist/esm/authorization-service.d.ts.map +1 -1
  9. package/dist/esm/authorization-service.mjs +9 -0
  10. package/dist/esm/clients/graph-api.client.d.ts.map +1 -1
  11. package/dist/esm/clients/graph-api.client.mjs +22 -2
  12. package/dist/esm/clients/platform-api.client.d.ts.map +1 -1
  13. package/dist/esm/clients/platform-api.client.mjs +25 -2
  14. package/dist/esm/utils/authorization.utils.d.ts.map +1 -1
  15. package/dist/esm/utils/authorization.utils.mjs +12 -0
  16. package/dist/utils/authorization.utils.d.ts.map +1 -1
  17. package/dist/utils/authorization.utils.js +12 -0
  18. package/package.json +7 -2
  19. package/src/attributions-service.ts +92 -0
  20. package/src/authorization-attributes-service.ts +234 -0
  21. package/src/authorization-internal-service.ts +129 -0
  22. package/src/authorization-middleware.ts +51 -0
  23. package/src/authorization-service.ts +384 -0
  24. package/src/clients/graph-api.client.ts +164 -0
  25. package/src/clients/platform-api.client.ts +151 -0
  26. package/src/constants/sns.ts +5 -0
  27. package/src/constants.ts +22 -0
  28. package/src/index.ts +46 -0
  29. package/src/prometheus-service.ts +147 -0
  30. package/src/roles-service.ts +125 -0
  31. package/src/testKit/index.ts +69 -0
  32. package/src/types/authorization-attributes-contracts.ts +33 -0
  33. package/src/types/express.ts +8 -0
  34. package/src/types/general.ts +32 -0
  35. package/src/types/graph-api.types.ts +19 -0
  36. package/src/types/roles.ts +42 -0
  37. package/src/types/scoped-actions-contracts.ts +48 -0
  38. package/src/utils/authorization.utils.ts +66 -0
@@ -0,0 +1,22 @@
1
+ import { RecursivePartial } from '@mondaydotcomorg/monday-fetch-api';
2
+ import { FetcherConfig } from '@mondaydotcomorg/trident-backend-api';
3
+
4
+ export const APP_NAME = 'authorization';
5
+
6
+ export const ERROR_MESSAGES = {
7
+ HTTP_CLIENT_NOT_INITIALIZED: 'MondayAuthorization: HTTP client is not initialized',
8
+ REQUEST_FAILED: (method: string, status: number, reason: string) =>
9
+ `MondayAuthorization: [${method}] request failed with status ${status} with reason: ${reason}`,
10
+ } as const;
11
+
12
+ export const DEFAULT_FETCH_OPTIONS: RecursivePartial<FetcherConfig> = {
13
+ retryPolicy: {
14
+ useRetries: true,
15
+ maxRetries: 3,
16
+ retryDelayMS: 10,
17
+ },
18
+ logPolicy: {
19
+ logErrors: 'error',
20
+ logRequests: 'info',
21
+ },
22
+ };
package/src/index.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
2
+ import { setPrometheus } from './prometheus-service';
3
+ import { setIgniteClient, setRedisClient, setRequestFetchOptions } from './authorization-service';
4
+ import * as TestKit from './testKit';
5
+
6
+ export interface InitOptions {
7
+ prometheus?: any;
8
+ mondayFetchOptions?: MondayFetchOptions;
9
+ redisClient?: any;
10
+ grantedFeatureRedisExpirationInSeconds?: number;
11
+ }
12
+
13
+ export async function init(options: InitOptions = {}) {
14
+ if (options.prometheus) {
15
+ setPrometheus(options.prometheus);
16
+ }
17
+
18
+ if (options.mondayFetchOptions) {
19
+ setRequestFetchOptions(options.mondayFetchOptions);
20
+ }
21
+ if (options.redisClient) {
22
+ setRedisClient(options.redisClient, options.grantedFeatureRedisExpirationInSeconds);
23
+ }
24
+
25
+ // add an ignite client for gradual release features
26
+ await setIgniteClient();
27
+ }
28
+
29
+ export {
30
+ authorizationCheckMiddleware,
31
+ getAuthorizationMiddleware,
32
+ skipAuthorizationMiddleware,
33
+ } from './authorization-middleware';
34
+ export { AuthorizationService, AuthorizeResponse } from './authorization-service';
35
+ export { AuthorizationAttributesService } from './authorization-attributes-service';
36
+ export { RolesService } from './roles-service';
37
+ export { AuthorizationObject, Resource, BaseRequest, ResourceGetter, ContextGetter } from './types/general';
38
+ export {
39
+ Translation,
40
+ ScopedAction,
41
+ ScopedActionResponseObject,
42
+ ScopedActionPermit,
43
+ } from './types/scoped-actions-contracts';
44
+ export { CustomRole, BasicRole, RoleType, RoleCreateRequest, RoleUpdateRequest, RolesResponse } from './types/roles';
45
+
46
+ export { TestKit };
@@ -0,0 +1,147 @@
1
+ import { Action } from './types/general';
2
+
3
+ let prometheus: any = null;
4
+ let authorizationCheckResponseTimeMetric: any = null;
5
+ let authorizationSuccessMetric: any = null;
6
+ let authorizationErrorMetric: any = null;
7
+ let graphAvailabilityMetric: any = null;
8
+
9
+ export const METRICS = {
10
+ AUTHORIZATION_CHECK: 'authorization_check',
11
+ AUTHORIZATION_CHECKS_PER_REQUEST: 'authorization_checks_per_request',
12
+ AUTHORIZATION_CHECK_RESPONSE_TIME: 'authorization_check_response_time',
13
+ };
14
+
15
+ const authorizationCheckResponseTimeMetricConfig = {
16
+ name: METRICS.AUTHORIZATION_CHECK_RESPONSE_TIME,
17
+ labels: ['resourceType', 'action', 'isAuthorized', 'responseStatus', 'apiType'],
18
+ description: 'Authorization check response time summary',
19
+ };
20
+
21
+ export function setPrometheus(customPrometheus) {
22
+ prometheus = customPrometheus;
23
+ if (!prometheus) {
24
+ authorizationCheckResponseTimeMetric = null;
25
+ authorizationSuccessMetric = null;
26
+ authorizationErrorMetric = null;
27
+ graphAvailabilityMetric = null;
28
+ return;
29
+ }
30
+
31
+ const { METRICS_TYPES } = prometheus;
32
+ const metricsManager = getMetricsManager();
33
+ if (metricsManager) {
34
+ authorizationCheckResponseTimeMetric = metricsManager.addMetric(
35
+ METRICS_TYPES.SUMMARY,
36
+ authorizationCheckResponseTimeMetricConfig.name,
37
+ authorizationCheckResponseTimeMetricConfig.labels,
38
+ authorizationCheckResponseTimeMetricConfig.description
39
+ );
40
+
41
+ initializeAdditionalMetrics();
42
+ }
43
+ }
44
+
45
+ export function getMetricsManager() {
46
+ return prometheus?.metricsManager;
47
+ }
48
+
49
+ export function sendAuthorizationCheckResponseTimeMetric(
50
+ resourceType: string,
51
+ action: Action,
52
+ isAuthorized: boolean,
53
+ responseStatus: number,
54
+ time: number,
55
+ apiType: 'platform' | 'graph' = 'platform'
56
+ ) {
57
+ try {
58
+ if (authorizationCheckResponseTimeMetric) {
59
+ authorizationCheckResponseTimeMetric
60
+ .labels(resourceType, action, isAuthorized, responseStatus, apiType)
61
+ .observe(time);
62
+ }
63
+ } catch (e) {
64
+ // ignore
65
+ }
66
+ }
67
+
68
+ const authorizationSuccessMetricConfig = {
69
+ name: 'authorization_success_total',
70
+ labels: ['resourceType', 'action'],
71
+ description: 'Total number of successful authorization checks',
72
+ };
73
+
74
+ const authorizationErrorMetricConfig = {
75
+ name: 'authorization_error_total',
76
+ labels: ['resourceType', 'action', 'statusCode'],
77
+ description: 'Total number of authorization errors',
78
+ };
79
+
80
+ const graphAvailabilityMetricConfig = {
81
+ name: 'graph_api_availability',
82
+ labels: ['available'],
83
+ description: 'Graph API availability status',
84
+ };
85
+
86
+ export function incrementAuthorizationSuccess(resourceType: string, action: Action) {
87
+ try {
88
+ if (authorizationSuccessMetric) {
89
+ authorizationSuccessMetric.labels(resourceType, action).inc();
90
+ }
91
+ } catch (e) {
92
+ // ignore
93
+ }
94
+ }
95
+
96
+ export function incrementAuthorizationError(resourceType: string, action: Action, statusCode: number) {
97
+ try {
98
+ if (authorizationErrorMetric) {
99
+ authorizationErrorMetric.labels(resourceType, action, statusCode).inc();
100
+ }
101
+ } catch (e) {
102
+ // ignore
103
+ }
104
+ }
105
+
106
+ export function setGraphAvailability(isAvailable: boolean) {
107
+ try {
108
+ if (graphAvailabilityMetric) {
109
+ graphAvailabilityMetric.labels(isAvailable ? 'true' : 'false').set(isAvailable ? 1 : 0);
110
+ }
111
+ } catch (e) {
112
+ // ignore
113
+ }
114
+ }
115
+
116
+ // Initialize additional metrics when prometheus is set
117
+ function initializeAdditionalMetrics() {
118
+ if (!prometheus) {
119
+ return;
120
+ }
121
+
122
+ const { METRICS_TYPES } = prometheus;
123
+ const metricsManager = getMetricsManager();
124
+
125
+ if (metricsManager) {
126
+ authorizationSuccessMetric = metricsManager.addMetric(
127
+ METRICS_TYPES.COUNTER,
128
+ authorizationSuccessMetricConfig.name,
129
+ authorizationSuccessMetricConfig.labels,
130
+ authorizationSuccessMetricConfig.description
131
+ );
132
+
133
+ authorizationErrorMetric = metricsManager.addMetric(
134
+ METRICS_TYPES.COUNTER,
135
+ authorizationErrorMetricConfig.name,
136
+ authorizationErrorMetricConfig.labels,
137
+ authorizationErrorMetricConfig.description
138
+ );
139
+
140
+ graphAvailabilityMetric = metricsManager.addMetric(
141
+ METRICS_TYPES.GAUGE,
142
+ graphAvailabilityMetricConfig.name,
143
+ graphAvailabilityMetricConfig.labels,
144
+ graphAvailabilityMetricConfig.description
145
+ );
146
+ }
147
+ }
@@ -0,0 +1,125 @@
1
+ import { Api, FetcherConfig, HttpClient } from '@mondaydotcomorg/trident-backend-api';
2
+ import { HttpFetcherError, RecursivePartial } from '@mondaydotcomorg/monday-fetch-api';
3
+ import { RoleCreateRequest, RolesResponse, RoleUpdateRequest } from 'types/roles';
4
+ import { getAttributionsFromApi } from 'attributions-service';
5
+ import { APP_NAME, DEFAULT_FETCH_OPTIONS, ERROR_MESSAGES } from './constants';
6
+
7
+ const API_PATH = '/roles/account/{accountId}';
8
+
9
+ export class RolesService {
10
+ private httpClient: HttpClient;
11
+ private fetchOptions: RecursivePartial<FetcherConfig>;
12
+ private attributionHeaders: { [key: string]: string };
13
+
14
+ /**
15
+ * Public constructor to create the AuthorizationAttributesService instance.
16
+ * @param httpClient The HTTP client to use for API requests, if not provided, the default HTTP client from Api will be used.
17
+ * @param fetchOptions The fetch options to use for API requests, if not provided, the default fetch options will be used.
18
+ */
19
+ constructor(httpClient?: HttpClient, fetchOptions?: RecursivePartial<FetcherConfig>) {
20
+ if (!httpClient) {
21
+ httpClient = Api.getPart('httpClient');
22
+ if (!httpClient) {
23
+ throw new Error(ERROR_MESSAGES.HTTP_CLIENT_NOT_INITIALIZED);
24
+ }
25
+ }
26
+
27
+ if (!fetchOptions) {
28
+ fetchOptions = DEFAULT_FETCH_OPTIONS;
29
+ } else {
30
+ fetchOptions = {
31
+ ...DEFAULT_FETCH_OPTIONS,
32
+ ...fetchOptions,
33
+ };
34
+ }
35
+ this.httpClient = httpClient;
36
+ this.fetchOptions = fetchOptions;
37
+ this.attributionHeaders = getAttributionsFromApi();
38
+ }
39
+
40
+ /**
41
+ * Get all roles for an account
42
+ * @param accountId - The account ID
43
+ * @param style - The style of the roles to return, either 'A' or 'B', default is 'A'. 'B' is not deprecated and only available for backward compatibility.
44
+ * @returns - The roles for the account, both basic and custom roles. Note that basic role ids are returned in A style and not B style.
45
+ */
46
+ async getRoles(accountId: number, resourceTypes: string[], style: 'A' | 'B' = 'A'): Promise<RolesResponse> {
47
+ return await this.sendRoleRequest('GET', accountId, {}, { resourceTypes, style });
48
+ }
49
+
50
+ /**
51
+ * Create a custom role for an account
52
+ * @param accountId - The account ID
53
+ * @param roles - The roles to create
54
+ * @returns - The created roles
55
+ * Note that basic role ids should be provided in A style and not in B style.
56
+ */
57
+ async createCustomRole(accountId: number, roles: RoleCreateRequest[]): Promise<RolesResponse> {
58
+ if (roles.length === 0) {
59
+ throw new Error('Roles array cannot be empty');
60
+ }
61
+
62
+ return await this.sendRoleRequest('PUT', accountId, {
63
+ customRoles: roles,
64
+ });
65
+ }
66
+
67
+ /**
68
+ * Delete a custom role for an account
69
+ * @param accountId - The account ID
70
+ * @param roleIds - The ids of the roles to delete
71
+ * @returns - The deleted roles. Note that basic role ids should be provided in A style and not in B style.
72
+ */
73
+ async deleteCustomRole(accountId: number, roleIds: number[]): Promise<RolesResponse> {
74
+ return await this.sendRoleRequest('DELETE', accountId, {
75
+ ids: roleIds,
76
+ });
77
+ }
78
+
79
+ /**
80
+ * Update a custom role for an account
81
+ * @param accountId - The account ID
82
+ * @param updateRequests - The requests to update the roles
83
+ * @returns - The updated roles. Note that basic role ids should be provided in A style and not in B style.
84
+ */
85
+ async updateCustomRole(accountId: number, updateRequests: RoleUpdateRequest[]): Promise<RolesResponse> {
86
+ return await this.sendRoleRequest('PATCH', accountId, {
87
+ customRoles: updateRequests,
88
+ });
89
+ }
90
+
91
+ private async sendRoleRequest(
92
+ method: 'PUT' | 'GET' | 'DELETE' | 'PATCH',
93
+ accountId: number,
94
+ body: any,
95
+ additionalQueryParams: { [key: string]: any } = {},
96
+ style: 'A' | 'B' = 'A'
97
+ ): Promise<RolesResponse> {
98
+ try {
99
+ return await this.httpClient.fetch<RolesResponse>(
100
+ {
101
+ url: {
102
+ appName: APP_NAME,
103
+ path: API_PATH.replace('{accountId}', accountId.toString()),
104
+ },
105
+ query: {
106
+ style: style,
107
+ ...additionalQueryParams,
108
+ },
109
+ method,
110
+ headers: {
111
+ 'Content-Type': 'application/json',
112
+ ...this.attributionHeaders,
113
+ },
114
+ body: method === 'GET' ? undefined : body,
115
+ },
116
+ this.fetchOptions
117
+ );
118
+ } catch (err) {
119
+ if (err instanceof HttpFetcherError) {
120
+ throw new Error(ERROR_MESSAGES.REQUEST_FAILED('sendRoleRequest', err.status, err.message));
121
+ }
122
+ throw err;
123
+ }
124
+ }
125
+ }
@@ -0,0 +1,69 @@
1
+ import { Action, BaseRequest, BaseResponse, ContextGetter, Resource, ResourceGetter } from '../types/general';
2
+ import { defaultContextGetter } from '../authorization-middleware';
3
+ import { AuthorizationInternalService } from '../authorization-internal-service';
4
+ import type { NextFunction } from 'express';
5
+
6
+ export type TestPermittedAction = {
7
+ accountId: number;
8
+ userId: number;
9
+ resources: Resource[];
10
+ action: Action;
11
+ };
12
+
13
+ let testPermittedActions: TestPermittedAction[] = [];
14
+ export const addTestPermittedAction = (accountId: number, userId: number, resources: Resource[], action: Action) => {
15
+ testPermittedActions.push({ accountId, userId, resources, action });
16
+ };
17
+
18
+ export const clearTestPermittedActions = () => {
19
+ testPermittedActions = [];
20
+ };
21
+
22
+ const isActionAuthorized = (accountId: number, userId: number, resources: Resource[], action: Action) => {
23
+ // If no resources to check, deny access
24
+ if (resources.length === 0) {
25
+ return { isAuthorized: false };
26
+ }
27
+
28
+ return {
29
+ isAuthorized: resources.every(resource => {
30
+ return testPermittedActions.some(combination => {
31
+ return (
32
+ combination.accountId === accountId &&
33
+ combination.userId === userId &&
34
+ combination.action === action &&
35
+ combination.resources.some(combinationResource => {
36
+ return (
37
+ combinationResource.id === resource.id &&
38
+ combinationResource.type === resource.type &&
39
+ JSON.stringify(combinationResource.wrapperData) === JSON.stringify(resource.wrapperData)
40
+ );
41
+ })
42
+ );
43
+ });
44
+ }),
45
+ };
46
+ };
47
+
48
+ export const getTestAuthorizationMiddleware = (
49
+ action: Action,
50
+ resourceGetter: ResourceGetter,
51
+ contextGetter?: ContextGetter
52
+ ) => {
53
+ return async function authorizationMiddleware(
54
+ request: BaseRequest,
55
+ response: BaseResponse,
56
+ next: NextFunction
57
+ ): Promise<void> {
58
+ contextGetter ||= defaultContextGetter;
59
+ const { userId, accountId } = contextGetter(request);
60
+ const resources = resourceGetter(request);
61
+ const { isAuthorized } = isActionAuthorized(accountId, userId, resources, action);
62
+ if (!isAuthorized) {
63
+ response.status(403).json({ message: 'Access denied' });
64
+ return;
65
+ }
66
+ AuthorizationInternalService.markAuthorized(request);
67
+ next();
68
+ };
69
+ };
@@ -0,0 +1,33 @@
1
+ import { Resource } from './general';
2
+
3
+ export interface ResourceAttributeAssignment {
4
+ resourceType: Resource['type'];
5
+ resourceId: Resource['id'];
6
+ key: string;
7
+ value: string;
8
+ }
9
+
10
+ export interface ResourceAttributeResponse {
11
+ attributes: ResourceAttributeAssignment[];
12
+ }
13
+
14
+ export interface ResourceAttributeDelete {
15
+ resourceType: Resource['type'];
16
+ resourceId: Resource['id'];
17
+ key: string;
18
+ }
19
+
20
+ export enum ResourceAttributeOperationEnum {
21
+ UPSERT = 'upsert',
22
+ DELETE = 'delete',
23
+ }
24
+
25
+ interface UpsertResourceAttributeOperation extends ResourceAttributeAssignment {
26
+ operationType: ResourceAttributeOperationEnum.UPSERT;
27
+ }
28
+
29
+ interface DeleteResourceAttributeOperation extends ResourceAttributeDelete {
30
+ operationType: ResourceAttributeOperationEnum.DELETE;
31
+ }
32
+
33
+ export type ResourceAttributesOperation = UpsertResourceAttributeOperation | DeleteResourceAttributeOperation;
@@ -0,0 +1,8 @@
1
+ // eslint-disable-next-line @typescript-eslint/no-namespace, @typescript-eslint/no-unused-vars
2
+ declare namespace Express {
3
+ export interface Request {
4
+ payload: { accountId: number; userId: number };
5
+ authorizationCheckPerformed: boolean;
6
+ authorizationSkipPerformed: boolean;
7
+ }
8
+ }
@@ -0,0 +1,32 @@
1
+ import type { Request, Response } from 'express';
2
+
3
+ export interface Resource {
4
+ id?: number;
5
+ type: string;
6
+ wrapperData?: object;
7
+ }
8
+ export type Action = string;
9
+ export interface Context {
10
+ accountId: number;
11
+ userId: number;
12
+ }
13
+ export interface AuthorizationObject {
14
+ resource_id?: Resource['id'];
15
+ resource_type: Resource['type'];
16
+ wrapper_data?: Resource['wrapperData'];
17
+ action: Action;
18
+ }
19
+ export interface AuthorizationParams {
20
+ authorizationObjects: AuthorizationObject[];
21
+ }
22
+
23
+ type BasicObject = { [key: string]: unknown };
24
+
25
+ export type BaseParameters = BasicObject;
26
+ export type BaseResponseBody = BasicObject;
27
+ export type BaseBodyParameters = BasicObject;
28
+ export type BaseQueryParameters = BasicObject;
29
+ export type BaseRequest = Request<BaseParameters, BaseResponseBody, BaseBodyParameters, BaseQueryParameters>;
30
+ export type BaseResponse = Response<BaseResponseBody>;
31
+ export type ResourceGetter = (request: BaseRequest) => Resource[];
32
+ export type ContextGetter = (request: BaseRequest) => Context;
@@ -0,0 +1,19 @@
1
+ // Graph API related types and interfaces
2
+
3
+ export type ResourceType = string;
4
+ export type ResourceId = number;
5
+ export type ActionName = string;
6
+
7
+ export type GraphIsAllowedDto = Record<ResourceType, Record<ResourceId, ActionName[]>>;
8
+
9
+ export type GraphPermissionResult = {
10
+ can: boolean;
11
+ reason: string;
12
+ };
13
+
14
+ // Permission to its result
15
+ export type GraphPermissionResults = Record<ActionName, GraphPermissionResult>;
16
+
17
+ // Resource type to map of resource ids to their permissions results
18
+ // Note: Resource IDs are string keys in the API response (JSON object keys are always strings)
19
+ export type GraphIsAllowedResponse = Record<ResourceType, Record<string, GraphPermissionResults>>;
@@ -0,0 +1,42 @@
1
+ export enum RoleType {
2
+ CUSTOM = 'custom_role',
3
+ BASIC = 'basic_role',
4
+ }
5
+
6
+ export interface CustomRole {
7
+ id?: number;
8
+ name: string;
9
+ resourceType: string;
10
+ resourceId: number;
11
+ basicRoleId: number;
12
+ basicRoleType: RoleType;
13
+ }
14
+
15
+ export interface BasicRole {
16
+ id: number;
17
+ resourceType: string;
18
+ roleType: string;
19
+ name: string;
20
+ }
21
+
22
+ export interface RolesResponse {
23
+ customRoles: CustomRole[];
24
+ basicRoles?: BasicRole[];
25
+ }
26
+
27
+ export interface RoleCreateRequest {
28
+ name: string;
29
+ resourceType: string;
30
+ resourceId: number;
31
+ sourceRole: {
32
+ id: number;
33
+ type: RoleType;
34
+ };
35
+ }
36
+
37
+ export interface RoleUpdateRequest {
38
+ id: number;
39
+ updateAttributes: {
40
+ name: string;
41
+ };
42
+ }
@@ -0,0 +1,48 @@
1
+ export interface WorkspaceScope {
2
+ workspaceId: number;
3
+ }
4
+
5
+ export interface BoardScope {
6
+ boardId: number;
7
+ }
8
+
9
+ export interface PulseScope {
10
+ pulseId: number;
11
+ }
12
+
13
+ export interface AccountProductScope {
14
+ accountProductId: number;
15
+ }
16
+
17
+ export interface AccountScope {
18
+ accountId: number;
19
+ }
20
+
21
+ export type ScopeOptions = WorkspaceScope | BoardScope | PulseScope | AccountProductScope | AccountScope;
22
+
23
+ export interface Translation {
24
+ key: string;
25
+ [option: string]: string;
26
+ }
27
+
28
+ export enum PermitTechnicalReason {
29
+ NO_REASON = 0,
30
+ NOT_ELIGIBLE = 1,
31
+ BY_ROLE_IN_SCOPE = 2,
32
+ }
33
+
34
+ export interface ScopedActionPermit {
35
+ can: boolean;
36
+ reason: Translation;
37
+ technicalReason: PermitTechnicalReason;
38
+ }
39
+
40
+ export interface ScopedAction {
41
+ action: string;
42
+ scope: ScopeOptions;
43
+ }
44
+
45
+ export interface ScopedActionResponseObject {
46
+ scopedAction: ScopedAction;
47
+ permit: ScopedActionPermit;
48
+ }
@@ -0,0 +1,66 @@
1
+ import snakeCase from 'lodash/snakeCase.js';
2
+ import camelCase from 'lodash/camelCase.js';
3
+ import mapKeys from 'lodash/mapKeys.js';
4
+ import { ScopeOptions } from '../types/scoped-actions-contracts';
5
+ import { ResourceType, ResourceId } from '../types/graph-api.types';
6
+ import { logger } from '../authorization-internal-service';
7
+
8
+ export type CamelCase<S extends string> = S extends `${infer F}_${infer R}` ? `${F}${Capitalize<CamelCase<R>>}` : S;
9
+ export type CamelCaseKeys<T> = T extends object
10
+ ? { [K in keyof T as K extends string ? CamelCase<K> : K]: CamelCaseKeys<T[K]> }
11
+ : T;
12
+
13
+ /**
14
+ * Converts a scope object to resource type and resource ID
15
+ */
16
+ export function scopeToResource(scope: ScopeOptions): { resourceType: ResourceType; resourceId: ResourceId } {
17
+ logger.debug(
18
+ {
19
+ tag: 'authorization-utils',
20
+ scopeKeys: Object.keys(scope),
21
+ scopeValues: Object.values(scope),
22
+ },
23
+ '🔍 Utils Debug: Converting scope to resource'
24
+ );
25
+
26
+ if ('workspaceId' in scope) {
27
+ logger.debug({ tag: 'authorization-utils', resourceId: scope.workspaceId }, '🔍 Utils Debug: Mapped to workspace');
28
+ return { resourceType: 'workspace', resourceId: scope.workspaceId };
29
+ }
30
+ if ('boardId' in scope) {
31
+ logger.debug({ tag: 'authorization-utils', resourceId: scope.boardId }, '🔍 Utils Debug: Mapped to board');
32
+ return { resourceType: 'board', resourceId: scope.boardId };
33
+ }
34
+ if ('pulseId' in scope) {
35
+ logger.debug({ tag: 'authorization-utils', resourceId: scope.pulseId }, '🔍 Utils Debug: Mapped to pulse');
36
+ return { resourceType: 'pulse', resourceId: scope.pulseId };
37
+ }
38
+ if ('accountProductId' in scope) {
39
+ logger.debug(
40
+ { tag: 'authorization-utils', resourceId: scope.accountProductId },
41
+ '🔍 Utils Debug: Mapped to account_product'
42
+ );
43
+ return { resourceType: 'account_product', resourceId: scope.accountProductId };
44
+ }
45
+ if ('accountId' in scope) {
46
+ logger.debug({ tag: 'authorization-utils', resourceId: scope.accountId }, '🔍 Utils Debug: Mapped to account');
47
+ return { resourceType: 'account', resourceId: scope.accountId };
48
+ }
49
+
50
+ logger.debug({ tag: 'authorization-utils', scope }, '❌ Utils Debug: Unsupported scope provided');
51
+ throw new Error('Unsupported scope provided');
52
+ }
53
+
54
+ /**
55
+ * Converts object keys from snake_case to camelCase
56
+ */
57
+ export function toCamelCase<T extends object>(obj: T): CamelCaseKeys<T> {
58
+ return mapKeys(obj, (_, key) => camelCase(key)) as CamelCaseKeys<T>;
59
+ }
60
+
61
+ /**
62
+ * Converts object keys from camelCase to snake_case
63
+ */
64
+ export function toSnakeCase<T extends object>(obj: T): Record<string, any> {
65
+ return mapKeys(obj, (_, key) => snakeCase(key));
66
+ }