@mondaydotcomorg/monday-authorization 1.2.10 → 1.2.12

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 (77) hide show
  1. package/README.md +25 -0
  2. package/dist/{lib/attributions-service.js → attributions-service.js} +11 -10
  3. package/dist/authorization-attributes-service.js +144 -0
  4. package/dist/{lib/authorization-internal-service.d.ts → authorization-internal-service.d.ts} +1 -1
  5. package/dist/authorization-internal-service.js +80 -0
  6. package/dist/{lib/authorization-middleware.d.ts → authorization-middleware.d.ts} +1 -1
  7. package/dist/authorization-middleware.js +48 -0
  8. package/dist/authorization-service.js +176 -0
  9. package/dist/constants/sns.js +9 -0
  10. package/dist/esm/attributions-service.d.ts +3 -0
  11. package/dist/esm/attributions-service.mjs +53 -0
  12. package/dist/esm/authorization-attributes-service.d.ts +44 -0
  13. package/dist/esm/authorization-attributes-service.mjs +138 -0
  14. package/dist/esm/authorization-internal-service.d.ts +13 -0
  15. package/dist/esm/authorization-internal-service.mjs +57 -0
  16. package/dist/esm/authorization-middleware.d.ts +6 -0
  17. package/dist/esm/authorization-middleware.mjs +39 -0
  18. package/dist/esm/authorization-service.d.ts +29 -0
  19. package/dist/esm/authorization-service.mjs +172 -0
  20. package/dist/esm/constants/sns.d.ts +3 -0
  21. package/dist/esm/constants/sns.mjs +5 -0
  22. package/dist/esm/index.d.ts +13 -0
  23. package/dist/esm/index.mjs +21 -0
  24. package/dist/esm/prometheus-service.mjs +49 -0
  25. package/dist/{lib → esm}/testKit/index.d.ts +2 -2
  26. package/dist/esm/testKit/index.mjs +44 -0
  27. package/dist/esm/types/authorization-attributes-contracts.mjs +7 -0
  28. package/dist/esm/types/express.mjs +1 -0
  29. package/dist/{lib → esm}/types/general.d.ts +6 -4
  30. package/dist/esm/types/general.mjs +1 -0
  31. package/dist/esm/types/scoped-actions-contracts.mjs +8 -0
  32. package/dist/index.d.ts +4 -4
  33. package/dist/index.js +19 -43
  34. package/dist/prometheus-service.d.ts +10 -0
  35. package/dist/{lib/prometheus-service.js → prometheus-service.js} +18 -14
  36. package/dist/testKit/index.d.ts +11 -0
  37. package/dist/testKit/index.js +48 -0
  38. package/dist/types/authorization-attributes-contracts.d.ts +27 -0
  39. package/dist/types/authorization-attributes-contracts.js +7 -0
  40. package/dist/types/express.d.ts +10 -0
  41. package/dist/types/express.js +1 -0
  42. package/dist/types/general.d.ts +32 -0
  43. package/dist/types/general.js +1 -0
  44. package/dist/types/scoped-actions-contracts.d.ts +38 -0
  45. package/dist/{lib/types → types}/scoped-actions-contracts.js +3 -5
  46. package/package.json +25 -28
  47. package/dist/index.js.map +0 -1
  48. package/dist/lib/attributions-service.js.map +0 -1
  49. package/dist/lib/authorization-attributes-service.js +0 -155
  50. package/dist/lib/authorization-attributes-service.js.map +0 -1
  51. package/dist/lib/authorization-internal-service.js +0 -79
  52. package/dist/lib/authorization-internal-service.js.map +0 -1
  53. package/dist/lib/authorization-middleware.js +0 -57
  54. package/dist/lib/authorization-middleware.js.map +0 -1
  55. package/dist/lib/authorization-service.js +0 -186
  56. package/dist/lib/authorization-service.js.map +0 -1
  57. package/dist/lib/constants/sns.js +0 -7
  58. package/dist/lib/constants/sns.js.map +0 -1
  59. package/dist/lib/prometheus-service.js.map +0 -1
  60. package/dist/lib/testKit/index.js +0 -59
  61. package/dist/lib/testKit/index.js.map +0 -1
  62. package/dist/lib/types/authorization-attributes-contracts.js +0 -9
  63. package/dist/lib/types/authorization-attributes-contracts.js.map +0 -1
  64. package/dist/lib/types/express.js +0 -2
  65. package/dist/lib/types/express.js.map +0 -1
  66. package/dist/lib/types/general.js +0 -3
  67. package/dist/lib/types/general.js.map +0 -1
  68. package/dist/lib/types/scoped-actions-contracts.js.map +0 -1
  69. package/dist/tsconfig.tsbuildinfo +0 -1
  70. package/dist/{lib/attributions-service.d.ts → attributions-service.d.ts} +0 -0
  71. package/dist/{lib/authorization-attributes-service.d.ts → authorization-attributes-service.d.ts} +0 -0
  72. package/dist/{lib/authorization-service.d.ts → authorization-service.d.ts} +1 -1
  73. /package/dist/{lib/constants → constants}/sns.d.ts +0 -0
  74. /package/dist/{lib → esm}/prometheus-service.d.ts +0 -0
  75. /package/dist/{lib → esm}/types/authorization-attributes-contracts.d.ts +0 -0
  76. /package/dist/{lib → esm}/types/express.d.ts +0 -0
  77. /package/dist/{lib → esm}/types/scoped-actions-contracts.d.ts +0 -0
@@ -0,0 +1,44 @@
1
+ import { ResourceAttributeAssignment, ResourceAttributeResponse, ResourceAttributesOperation } from './types/authorization-attributes-contracts';
2
+ import { Resource } from './types/general';
3
+ export declare class AuthorizationAttributesService {
4
+ private static LOG_TAG;
5
+ /**
6
+ * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
7
+ * @param accountId
8
+ * @param userId
9
+ * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
10
+ * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
11
+ * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
12
+ */
13
+ static upsertResourceAttributes(accountId: number, userId: number, resourceAttributeAssignments: ResourceAttributeAssignment[]): Promise<ResourceAttributeResponse>;
14
+ /**
15
+ * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
16
+ * @param accountId
17
+ * @param userId
18
+ * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
19
+ * @param attributeKeys - Array of attribute keys to delete for the resource.
20
+ * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
21
+ */
22
+ static deleteResourceAttributes(accountId: number, userId: number, resource: Resource, attributeKeys: string[]): Promise<ResourceAttributeResponse>;
23
+ /**
24
+ * Async function, this function only send the updates request to SNS and return before the change actually took place
25
+ * @param accountId
26
+ * @param appName - App name of the calling app
27
+ * @param callerActionIdentifier - action identifier
28
+ * @param resourceAttributeOperations - Array of operations to do on resource attributes.
29
+ * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
30
+ * */
31
+ static updateResourceAttributesAsync(accountId: number, appName: string, callerActionIdentifier: string, resourceAttributeOperations: ResourceAttributesOperation[]): Promise<ResourceAttributesOperation[]>;
32
+ private static sendSingleSnsMessage;
33
+ private static getSnsTopicArn;
34
+ private static getResourceAttributesUrl;
35
+ /**
36
+ * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
37
+ * This function can be used as health check for services that updating resource attributes in async is crucial.
38
+ * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
39
+ * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
40
+ * However, this is the best we can do without actually push dummy messages to the SNS.
41
+ * @return {Promise<boolean>} - true if succeeded
42
+ */
43
+ static asyncResourceAttributesHealthCheck(): Promise<boolean>;
44
+ }
@@ -0,0 +1,138 @@
1
+ import chunk from 'lodash/chunk';
2
+ import { fetch } from '@mondaydotcomorg/monday-fetch';
3
+ import { Api } from '@mondaydotcomorg/trident-backend-api';
4
+ import { sendToSns, getTopicAttributes } from '@mondaydotcomorg/monday-sns';
5
+ import { AuthorizationInternalService, logger } from './authorization-internal-service.mjs';
6
+ import { getAttributionsFromApi } from './attributions-service.mjs';
7
+ import { ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE, RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME, RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND } from './constants/sns.mjs';
8
+
9
+ class AuthorizationAttributesService {
10
+ static LOG_TAG = 'authorization_attributes';
11
+ /**
12
+ * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
13
+ * @param accountId
14
+ * @param userId
15
+ * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
16
+ * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
17
+ * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
18
+ */
19
+ static async upsertResourceAttributes(accountId, userId, resourceAttributeAssignments) {
20
+ const internalAuthToken = AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
21
+ const attributionHeaders = getAttributionsFromApi();
22
+ const response = await fetch(this.getResourceAttributesUrl(accountId), {
23
+ method: 'POST',
24
+ headers: {
25
+ Authorization: internalAuthToken,
26
+ 'Content-Type': 'application/json',
27
+ ...attributionHeaders,
28
+ },
29
+ timeout: AuthorizationInternalService.getRequestTimeout(),
30
+ body: JSON.stringify({ resourceAttributeAssignments }),
31
+ }, AuthorizationInternalService.getRequestFetchOptions());
32
+ const responseBody = await response.json();
33
+ AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'upsertResourceAttributesSync');
34
+ return { attributes: responseBody['attributes'] };
35
+ }
36
+ /**
37
+ * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
38
+ * @param accountId
39
+ * @param userId
40
+ * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
41
+ * @param attributeKeys - Array of attribute keys to delete for the resource.
42
+ * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
43
+ */
44
+ static async deleteResourceAttributes(accountId, userId, resource, attributeKeys) {
45
+ const internalAuthToken = AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
46
+ const url = `${this.getResourceAttributesUrl(accountId)}/${resource.type}/${resource.id}`;
47
+ const attributionHeaders = getAttributionsFromApi();
48
+ const response = await fetch(url, {
49
+ method: 'DELETE',
50
+ headers: {
51
+ Authorization: internalAuthToken,
52
+ 'Content-Type': 'application/json',
53
+ ...attributionHeaders,
54
+ },
55
+ timeout: AuthorizationInternalService.getRequestTimeout(),
56
+ body: JSON.stringify({ keys: attributeKeys }),
57
+ }, AuthorizationInternalService.getRequestFetchOptions());
58
+ const responseBody = await response.json();
59
+ AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'deleteResourceAttributesSync');
60
+ return { attributes: responseBody['attributes'] };
61
+ }
62
+ /**
63
+ * Async function, this function only send the updates request to SNS and return before the change actually took place
64
+ * @param accountId
65
+ * @param appName - App name of the calling app
66
+ * @param callerActionIdentifier - action identifier
67
+ * @param resourceAttributeOperations - Array of operations to do on resource attributes.
68
+ * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
69
+ * */
70
+ static async updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations) {
71
+ const topicArn = this.getSnsTopicArn();
72
+ const sendToSnsPromises = [];
73
+ const operationChucks = chunk(resourceAttributeOperations, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
74
+ for (const operationsChunk of operationChucks) {
75
+ sendToSnsPromises.push(this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk));
76
+ }
77
+ return (await Promise.all(sendToSnsPromises)).flat();
78
+ }
79
+ static async sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operations) {
80
+ const payload = {
81
+ kind: RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
82
+ payload: {
83
+ accountId: accountId,
84
+ callerAppName: appName,
85
+ callerActionIdentifier: callerActionIdentifier,
86
+ operations: operations,
87
+ },
88
+ };
89
+ try {
90
+ await sendToSns(payload, topicArn);
91
+ return operations;
92
+ }
93
+ catch (error) {
94
+ logger.error({ error, tag: this.LOG_TAG }, 'Authorization resource attributes async update: failed to send operations to SNS');
95
+ return [];
96
+ }
97
+ }
98
+ static getSnsTopicArn() {
99
+ const arnFromApi = Api.getPart('configurationVariables')?.get(RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME).arn;
100
+ if (arnFromApi) {
101
+ return arnFromApi;
102
+ }
103
+ const jsonArnFromEnv = process.env[RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME];
104
+ const arnFromEnv = JSON.parse(jsonArnFromEnv).arn;
105
+ if (arnFromEnv) {
106
+ return arnFromEnv;
107
+ }
108
+ throw new Error('Unable to get sns topic arn from env variable');
109
+ }
110
+ static getResourceAttributesUrl(accountId) {
111
+ return `${process.env.AUTHORIZATION_URL}/attributes/${accountId}/resource`;
112
+ }
113
+ /**
114
+ * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
115
+ * This function can be used as health check for services that updating resource attributes in async is crucial.
116
+ * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
117
+ * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
118
+ * However, this is the best we can do without actually push dummy messages to the SNS.
119
+ * @return {Promise<boolean>} - true if succeeded
120
+ */
121
+ static async asyncResourceAttributesHealthCheck() {
122
+ try {
123
+ const requestedTopicArn = this.getSnsTopicArn();
124
+ const attributes = await getTopicAttributes(requestedTopicArn);
125
+ const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
126
+ if (!isHealthy) {
127
+ logger.error({ requestedTopicArn, snsReturnedAttributes: attributes, tag: this.LOG_TAG }, 'authorization-attributes-service failed in health check');
128
+ }
129
+ return isHealthy;
130
+ }
131
+ catch (error) {
132
+ logger.error({ error, tag: this.LOG_TAG }, 'authorization-attributes-service got error during health check');
133
+ return false;
134
+ }
135
+ }
136
+ }
137
+
138
+ export { AuthorizationAttributesService };
@@ -0,0 +1,13 @@
1
+ import { fetch, MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
2
+ import type { Request } from 'express';
3
+ export declare const logger: import("bunyan");
4
+ export declare class AuthorizationInternalService {
5
+ static skipAuthorization(requset: Request): void;
6
+ static markAuthorized(request: Request): void;
7
+ static failIfNotCoveredByAuthorization(request: Request): void;
8
+ static throwOnHttpErrorIfNeeded(response: Awaited<ReturnType<typeof fetch>>, placement: string): void;
9
+ static generateInternalAuthToken(accountId: number, userId: number): string;
10
+ static setRequestFetchOptions(customMondayFetchOptions: MondayFetchOptions): void;
11
+ static getRequestFetchOptions(): MondayFetchOptions;
12
+ static getRequestTimeout(): 60000 | 2000;
13
+ }
@@ -0,0 +1,57 @@
1
+ import { signAuthorizationHeader } from '@mondaydotcomorg/monday-jwt';
2
+ import * as MondayLogger from '@mondaydotcomorg/monday-logger';
3
+
4
+ const INTERNAL_APP_NAME = 'internal_ms';
5
+ const defaultMondayFetchOptions = {
6
+ retries: 3,
7
+ callback: logOnFetchFail,
8
+ };
9
+ const logger = MondayLogger.getLogger();
10
+ function logOnFetchFail(retriesLeft, error) {
11
+ if (retriesLeft == 0) {
12
+ logger.error({ retriesLeft, error }, 'Authorization attempt failed due to network issues');
13
+ }
14
+ else {
15
+ logger.info({ retriesLeft, error }, 'Authorization attempt failed due to network issues, trying again');
16
+ }
17
+ }
18
+ let mondayFetchOptions = defaultMondayFetchOptions;
19
+ class AuthorizationInternalService {
20
+ static skipAuthorization(requset) {
21
+ requset.authorizationSkipPerformed = true;
22
+ }
23
+ static markAuthorized(request) {
24
+ request.authorizationCheckPerformed = true;
25
+ }
26
+ static failIfNotCoveredByAuthorization(request) {
27
+ if (!request.authorizationCheckPerformed && !request.authorizationSkipPerformed) {
28
+ throw 'Endpoint is not covered by authorization check';
29
+ }
30
+ }
31
+ static throwOnHttpErrorIfNeeded(response, placement) {
32
+ if (response.ok) {
33
+ return;
34
+ }
35
+ const status = response.status;
36
+ logger.error({ tag: 'authorization-service', placement, status }, 'AuthorizationService: authorization request failed');
37
+ throw new Error(`AuthorizationService: [${placement}] authorization request failed with status ${status}`);
38
+ }
39
+ static generateInternalAuthToken(accountId, userId) {
40
+ return signAuthorizationHeader({ appName: INTERNAL_APP_NAME, accountId, userId });
41
+ }
42
+ static setRequestFetchOptions(customMondayFetchOptions) {
43
+ mondayFetchOptions = {
44
+ ...defaultMondayFetchOptions,
45
+ ...customMondayFetchOptions,
46
+ };
47
+ }
48
+ static getRequestFetchOptions() {
49
+ return mondayFetchOptions;
50
+ }
51
+ static getRequestTimeout() {
52
+ const isDevEnv = process.env.NODE_ENV === 'development';
53
+ return isDevEnv ? 60000 : 2000;
54
+ }
55
+ }
56
+
57
+ export { AuthorizationInternalService, logger };
@@ -0,0 +1,6 @@
1
+ import { Action, BaseRequest, BaseResponse, Context, ContextGetter, ResourceGetter } from './types/general';
2
+ import type { NextFunction } from 'express';
3
+ export declare function getAuthorizationMiddleware(action: Action, resourceGetter: ResourceGetter, contextGetter?: ContextGetter): (request: BaseRequest, response: BaseResponse, next: NextFunction) => Promise<void>;
4
+ export declare function skipAuthorizationMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
5
+ export declare function authorizationCheckMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
6
+ export declare function defaultContextGetter(request: BaseRequest): Context;
@@ -0,0 +1,39 @@
1
+ import onHeaders from 'on-headers';
2
+ import { AuthorizationInternalService } from './authorization-internal-service.mjs';
3
+ import { AuthorizationService } from './authorization-service.mjs';
4
+
5
+ // getAuthorizationMiddleware is duplicated in testKit/index.ts
6
+ // If you are making changes to this function, please make sure to update the other file as well
7
+ function getAuthorizationMiddleware(action, resourceGetter, contextGetter) {
8
+ return async function authorizationMiddleware(request, response, next) {
9
+ contextGetter ||= defaultContextGetter;
10
+ const { userId, accountId } = contextGetter(request);
11
+ const resources = resourceGetter(request);
12
+ const { isAuthorized } = await AuthorizationService.isAuthorized(accountId, userId, resources, action);
13
+ AuthorizationInternalService.markAuthorized(request);
14
+ if (!isAuthorized) {
15
+ response.status(403).json({ message: 'Access denied' });
16
+ return;
17
+ }
18
+ next();
19
+ };
20
+ }
21
+ function skipAuthorizationMiddleware(request, response, next) {
22
+ AuthorizationInternalService.skipAuthorization(request);
23
+ next();
24
+ }
25
+ function authorizationCheckMiddleware(request, response, next) {
26
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
27
+ onHeaders(response, function () {
28
+ if (response.statusCode < 400) {
29
+ AuthorizationInternalService.failIfNotCoveredByAuthorization(request);
30
+ }
31
+ });
32
+ }
33
+ next();
34
+ }
35
+ function defaultContextGetter(request) {
36
+ return request.payload;
37
+ }
38
+
39
+ export { authorizationCheckMiddleware, defaultContextGetter, getAuthorizationMiddleware, skipAuthorizationMiddleware };
@@ -0,0 +1,29 @@
1
+ import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
2
+ import { Action, AuthorizationObject, Resource } from './types/general';
3
+ import { ScopedAction, ScopedActionPermit, ScopedActionResponseObject, ScopeOptions } from './types/scoped-actions-contracts';
4
+ export interface AuthorizeResponse {
5
+ isAuthorized: boolean;
6
+ unauthorizedIds?: number[];
7
+ unauthorizedObjects?: AuthorizationObject[];
8
+ }
9
+ export declare function setRequestFetchOptions(customMondayFetchOptions: MondayFetchOptions): void;
10
+ export declare class AuthorizationService {
11
+ static redisClient?: any;
12
+ static grantedFeatureRedisExpirationInSeconds?: number;
13
+ /**
14
+ * @deprecated use the second form with authorizationRequestObjects instead,
15
+ * support of this function will be dropped gradually
16
+ */
17
+ static isAuthorized(accountId: number, userId: number, resources: Resource[], action: Action): Promise<AuthorizeResponse>;
18
+ static isAuthorized(accountId: number, userId: number, authorizationRequestObjects: AuthorizationObject[]): Promise<AuthorizeResponse>;
19
+ static isUserGrantedWithFeature(accountId: number, userId: number, featureName: string, options?: {
20
+ shouldSkipCache?: boolean;
21
+ }): Promise<boolean>;
22
+ private static fetchIsUserGrantedWithFeature;
23
+ private static getCachedKeyName;
24
+ static canActionInScope(accountId: number, userId: number, action: string, scope: ScopeOptions): Promise<ScopedActionPermit>;
25
+ static canActionInScopeMultiple(accountId: number, userId: number, scopedActions: ScopedAction[]): Promise<ScopedActionResponseObject[]>;
26
+ private static isAuthorizedSingular;
27
+ private static isAuthorizedMultiple;
28
+ }
29
+ export declare function setRedisClient(client: any, grantedFeatureRedisExpirationInSeconds?: number): void;
@@ -0,0 +1,172 @@
1
+ import { performance } from 'perf_hooks';
2
+ import { mapKeys, snakeCase, camelCase } from 'lodash';
3
+ import { fetch } from '@mondaydotcomorg/monday-fetch';
4
+ import { sendAuthorizationChecksPerRequestMetric, sendAuthorizationCheckResponseTimeMetric } from './prometheus-service.mjs';
5
+ import { AuthorizationInternalService, logger } from './authorization-internal-service.mjs';
6
+ import { getAttributionsFromApi } from './attributions-service.mjs';
7
+
8
+ const GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS = 5 * 60;
9
+ function setRequestFetchOptions(customMondayFetchOptions) {
10
+ AuthorizationInternalService.setRequestFetchOptions(customMondayFetchOptions);
11
+ }
12
+ class AuthorizationService {
13
+ static redisClient;
14
+ static grantedFeatureRedisExpirationInSeconds;
15
+ static async isAuthorized(...args) {
16
+ if (args.length === 3) {
17
+ return this.isAuthorizedMultiple(args[0], args[1], args[2]);
18
+ }
19
+ else if (args.length == 4) {
20
+ return this.isAuthorizedSingular(args[0], args[1], args[2], args[3]);
21
+ }
22
+ else {
23
+ throw new Error('isAuthorized accepts either 3 or 4 arguments');
24
+ }
25
+ }
26
+ static async isUserGrantedWithFeature(accountId, userId, featureName, options = {}) {
27
+ const cachedKey = this.getCachedKeyName(userId, featureName);
28
+ const shouldSkipCache = options.shouldSkipCache ?? false;
29
+ if (this.redisClient && !shouldSkipCache) {
30
+ const grantedFeatureValue = await this.redisClient.get(cachedKey);
31
+ if (!(grantedFeatureValue === undefined || grantedFeatureValue === null)) {
32
+ // redis returns the value as string
33
+ return grantedFeatureValue === 'true';
34
+ }
35
+ }
36
+ const grantedFeatureValue = await this.fetchIsUserGrantedWithFeature(featureName, accountId, userId);
37
+ if (this.redisClient) {
38
+ await this.redisClient.set(cachedKey, grantedFeatureValue, 'EX', this.grantedFeatureRedisExpirationInSeconds);
39
+ }
40
+ return grantedFeatureValue;
41
+ }
42
+ static async fetchIsUserGrantedWithFeature(featureName, accountId, userId) {
43
+ const authorizationObject = {
44
+ action: featureName,
45
+ resource_type: 'feature',
46
+ };
47
+ const authorizeResponsePromise = await this.isAuthorized(accountId, userId, [authorizationObject]);
48
+ return authorizeResponsePromise.isAuthorized;
49
+ }
50
+ static getCachedKeyName(userId, featureName) {
51
+ return `granted-feature-${featureName}-${userId}`;
52
+ }
53
+ static async canActionInScope(accountId, userId, action, scope) {
54
+ const scopedActions = [{ action, scope }];
55
+ const scopedActionResponseObjects = await this.canActionInScopeMultiple(accountId, userId, scopedActions);
56
+ return scopedActionResponseObjects[0].permit;
57
+ }
58
+ static async canActionInScopeMultiple(accountId, userId, scopedActions) {
59
+ const internalAuthToken = AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
60
+ const scopedActionsPayload = scopedActions.map(scopedAction => {
61
+ return { ...scopedAction, scope: mapKeys(scopedAction.scope, (_, key) => snakeCase(key)) }; // for example: { workspaceId: 1 } => { workspace_id: 1 }
62
+ });
63
+ const attributionHeaders = getAttributionsFromApi();
64
+ const response = await fetch(getCanActionsInScopesUrl(), {
65
+ method: 'POST',
66
+ headers: {
67
+ Authorization: internalAuthToken,
68
+ 'Content-Type': 'application/json',
69
+ ...attributionHeaders,
70
+ },
71
+ timeout: AuthorizationInternalService.getRequestTimeout(),
72
+ body: JSON.stringify({
73
+ user_id: userId,
74
+ scoped_actions: scopedActionsPayload,
75
+ }),
76
+ }, AuthorizationInternalService.getRequestFetchOptions());
77
+ AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'canActionInScopeMultiple');
78
+ const responseBody = await response.json();
79
+ const camelCaseKeys = obj => Object.fromEntries(Object.entries(obj).map(([key, value]) => [camelCase(key), value]));
80
+ const scopedActionsResponseObjects = responseBody.result.map(responseObject => {
81
+ const { scopedAction, permit } = responseObject;
82
+ const { scope } = scopedAction;
83
+ const transformKeys = obj => camelCaseKeys(obj);
84
+ return {
85
+ ...responseObject,
86
+ scopedAction: { ...scopedAction, scope: transformKeys(scope) },
87
+ permit: transformKeys(permit),
88
+ };
89
+ });
90
+ return scopedActionsResponseObjects;
91
+ }
92
+ static async isAuthorizedSingular(accountId, userId, resources, action) {
93
+ const { authorizationObjects } = createAuthorizationParams(resources, action);
94
+ return this.isAuthorizedMultiple(accountId, userId, authorizationObjects);
95
+ }
96
+ static async isAuthorizedMultiple(accountId, userId, authorizationRequestObjects) {
97
+ const internalAuthToken = AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
98
+ const startTime = performance.now();
99
+ const attributionHeaders = getAttributionsFromApi();
100
+ const response = await fetch(getAuthorizeUrl(), {
101
+ method: 'POST',
102
+ headers: {
103
+ Authorization: internalAuthToken,
104
+ 'Content-Type': 'application/json',
105
+ ...attributionHeaders,
106
+ },
107
+ timeout: AuthorizationInternalService.getRequestTimeout(),
108
+ body: JSON.stringify({
109
+ user_id: userId,
110
+ authorize_request_objects: authorizationRequestObjects,
111
+ }),
112
+ }, AuthorizationInternalService.getRequestFetchOptions());
113
+ const endTime = performance.now();
114
+ const time = endTime - startTime;
115
+ const responseStatus = response.status;
116
+ sendAuthorizationChecksPerRequestMetric(responseStatus, authorizationRequestObjects.length);
117
+ AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'isAuthorizedMultiple');
118
+ const responseBody = await response.json();
119
+ const unauthorizedObjects = [];
120
+ responseBody.result.forEach(function (isAuthorized, index) {
121
+ const authorizationObject = authorizationRequestObjects[index];
122
+ if (!isAuthorized) {
123
+ unauthorizedObjects.push(authorizationObject);
124
+ }
125
+ sendAuthorizationCheckResponseTimeMetric(authorizationObject.resource_type, authorizationObject.action, isAuthorized, responseStatus, time);
126
+ });
127
+ if (unauthorizedObjects.length > 0) {
128
+ logger.info({
129
+ resources: JSON.stringify(unauthorizedObjects),
130
+ }, 'AuthorizationService: resource is unauthorized');
131
+ const unauthorizedIds = unauthorizedObjects
132
+ .filter(obj => !!obj.resource_id)
133
+ .map(obj => obj.resource_id);
134
+ return { isAuthorized: false, unauthorizedIds, unauthorizedObjects };
135
+ }
136
+ return { isAuthorized: true };
137
+ }
138
+ }
139
+ function setRedisClient(client, grantedFeatureRedisExpirationInSeconds = GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS) {
140
+ AuthorizationService.redisClient = client;
141
+ if (grantedFeatureRedisExpirationInSeconds && grantedFeatureRedisExpirationInSeconds > 0) {
142
+ AuthorizationService.grantedFeatureRedisExpirationInSeconds = grantedFeatureRedisExpirationInSeconds;
143
+ }
144
+ else {
145
+ logger.warn({ grantedFeatureRedisExpirationInSeconds }, 'Invalid input for grantedFeatureRedisExpirationInSeconds, must be positive number. using default ttl.');
146
+ AuthorizationService.grantedFeatureRedisExpirationInSeconds = GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS;
147
+ }
148
+ }
149
+ function createAuthorizationParams(resources, action) {
150
+ const params = {
151
+ authorizationObjects: resources.map((resource) => {
152
+ const authorizationObject = {
153
+ resource_id: resource.id,
154
+ resource_type: resource.type,
155
+ action,
156
+ };
157
+ if (resource.wrapperData) {
158
+ authorizationObject.wrapper_data = resource.wrapperData;
159
+ }
160
+ return authorizationObject;
161
+ }),
162
+ };
163
+ return params;
164
+ }
165
+ function getAuthorizeUrl() {
166
+ return `${process.env.MONDAY_INTERNAL_URL}/internal_ms/authorization/authorize`;
167
+ }
168
+ function getCanActionsInScopesUrl() {
169
+ return `${process.env.MONDAY_INTERNAL_URL}/internal_ms/authorization/can_actions_in_scopes`;
170
+ }
171
+
172
+ export { AuthorizationService, setRedisClient, setRequestFetchOptions };
@@ -0,0 +1,3 @@
1
+ export declare const RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME = "AUTHORIZATION_RESOURCE_ATTRIBUTES_SNS_TOPIC";
2
+ export declare const RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND = "resourceAttributeModification";
3
+ export declare const ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE = 100;
@@ -0,0 +1,5 @@
1
+ const RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME = 'AUTHORIZATION_RESOURCE_ATTRIBUTES_SNS_TOPIC';
2
+ const RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND = 'resourceAttributeModification';
3
+ const ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE = 100;
4
+
5
+ export { ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE, RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME, RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND };
@@ -0,0 +1,13 @@
1
+ import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
2
+ import * as TestKit from './testKit';
3
+ export interface InitOptions {
4
+ prometheus?: any;
5
+ mondayFetchOptions?: MondayFetchOptions;
6
+ redisClient?: any;
7
+ grantedFeatureRedisExpirationInSeconds?: number;
8
+ }
9
+ export declare function init(options?: InitOptions): void;
10
+ export { authorizationCheckMiddleware, getAuthorizationMiddleware, skipAuthorizationMiddleware, } from './authorization-middleware';
11
+ export { AuthorizationService } from './authorization-service';
12
+ export { AuthorizationAttributesService } from './authorization-attributes-service';
13
+ export { TestKit };
@@ -0,0 +1,21 @@
1
+ import { setPrometheus } from './prometheus-service.mjs';
2
+ import { setRequestFetchOptions, setRedisClient } from './authorization-service.mjs';
3
+ export { AuthorizationService } from './authorization-service.mjs';
4
+ import * as testKit_index from './testKit/index.mjs';
5
+ export { testKit_index as TestKit };
6
+ export { authorizationCheckMiddleware, getAuthorizationMiddleware, skipAuthorizationMiddleware } from './authorization-middleware.mjs';
7
+ export { AuthorizationAttributesService } from './authorization-attributes-service.mjs';
8
+
9
+ function init(options = {}) {
10
+ if (options.prometheus) {
11
+ setPrometheus(options.prometheus);
12
+ }
13
+ if (options.mondayFetchOptions) {
14
+ setRequestFetchOptions(options.mondayFetchOptions);
15
+ }
16
+ if (options.redisClient) {
17
+ setRedisClient(options.redisClient, options.grantedFeatureRedisExpirationInSeconds);
18
+ }
19
+ }
20
+
21
+ export { init };
@@ -0,0 +1,49 @@
1
+ let prometheus = null;
2
+ let authorizationChecksPerRequestMetric = null;
3
+ let authorizationCheckResponseTimeMetric = null;
4
+ const METRICS = {
5
+ AUTHORIZATION_CHECK: 'authorization_check',
6
+ AUTHORIZATION_CHECKS_PER_REQUEST: 'authorization_checks_per_request',
7
+ AUTHORIZATION_CHECK_RESPONSE_TIME: 'authorization_check_response_time',
8
+ };
9
+ const authorizationChecksPerRequestMetricConfig = {
10
+ name: METRICS.AUTHORIZATION_CHECKS_PER_REQUEST,
11
+ labels: ['responseStatus'],
12
+ description: 'Authorization checks per request summary',
13
+ };
14
+ const authorizationCheckResponseTimeMetricConfig = {
15
+ name: METRICS.AUTHORIZATION_CHECK_RESPONSE_TIME,
16
+ labels: ['resourceType', 'action', 'isAuthorized', 'responseStatus'],
17
+ description: 'Authorization check response time summary',
18
+ };
19
+ function setPrometheus(customPrometheus) {
20
+ prometheus = customPrometheus;
21
+ const { METRICS_TYPES } = prometheus;
22
+ authorizationChecksPerRequestMetric = getMetricsManager().addMetric(METRICS_TYPES.SUMMARY, authorizationChecksPerRequestMetricConfig.name, authorizationChecksPerRequestMetricConfig.labels, authorizationChecksPerRequestMetricConfig.description);
23
+ authorizationCheckResponseTimeMetric = getMetricsManager().addMetric(METRICS_TYPES.SUMMARY, authorizationCheckResponseTimeMetricConfig.name, authorizationCheckResponseTimeMetricConfig.labels, authorizationCheckResponseTimeMetricConfig.description);
24
+ }
25
+ function getMetricsManager() {
26
+ return prometheus?.metricsManager;
27
+ }
28
+ function sendAuthorizationChecksPerRequestMetric(responseStatus, amountOfAuthorizationObjects) {
29
+ try {
30
+ if (authorizationChecksPerRequestMetric) {
31
+ authorizationChecksPerRequestMetric.labels(responseStatus).observe(amountOfAuthorizationObjects);
32
+ }
33
+ }
34
+ catch (e) {
35
+ // ignore
36
+ }
37
+ }
38
+ function sendAuthorizationCheckResponseTimeMetric(resourceType, action, isAuthorized, responseStatus, time) {
39
+ try {
40
+ if (authorizationCheckResponseTimeMetric) {
41
+ authorizationCheckResponseTimeMetric.labels(resourceType, action, isAuthorized, responseStatus).observe(time);
42
+ }
43
+ }
44
+ catch (e) {
45
+ // ignore
46
+ }
47
+ }
48
+
49
+ export { METRICS, getMetricsManager, sendAuthorizationCheckResponseTimeMetric, sendAuthorizationChecksPerRequestMetric, setPrometheus };
@@ -1,5 +1,5 @@
1
- import { NextFunction } from "express";
2
- import { Action, BaseRequest, BaseResponse, ContextGetter, Resource, ResourceGetter } from "../types/general";
1
+ import { Action, BaseRequest, BaseResponse, ContextGetter, Resource, ResourceGetter } from '../types/general';
2
+ import type { NextFunction } from 'express';
3
3
  export type TestPermittedAction = {
4
4
  accountId: number;
5
5
  userId: number;
@@ -0,0 +1,44 @@
1
+ import { defaultContextGetter } from '../authorization-middleware.mjs';
2
+ import { AuthorizationInternalService } from '../authorization-internal-service.mjs';
3
+
4
+ let testPermittedActions = [];
5
+ const addTestPermittedAction = (accountId, userId, resources, action) => {
6
+ testPermittedActions.push({ accountId, userId, resources, action });
7
+ };
8
+ const clearTestPermittedActions = () => {
9
+ testPermittedActions = [];
10
+ };
11
+ const isActionAuthorized = (accountId, userId, resources, action) => {
12
+ return {
13
+ isAuthorized: resources.every(_ => {
14
+ return testPermittedActions.some(combination => {
15
+ return (combination.accountId === accountId &&
16
+ combination.userId === userId &&
17
+ combination.action === action &&
18
+ combination.resources.some(combinationResource => {
19
+ return resources.some(resource => {
20
+ return (combinationResource.id === resource.id &&
21
+ combinationResource.type === resource.type &&
22
+ JSON.stringify(combinationResource.wrapperData) === JSON.stringify(resource.wrapperData));
23
+ });
24
+ }));
25
+ });
26
+ }),
27
+ };
28
+ };
29
+ const getTestAuthorizationMiddleware = (action, resourceGetter, contextGetter) => {
30
+ return async function authorizationMiddleware(request, response, next) {
31
+ contextGetter ||= defaultContextGetter;
32
+ const { userId, accountId } = contextGetter(request);
33
+ const resources = resourceGetter(request);
34
+ const { isAuthorized } = isActionAuthorized(accountId, userId, resources, action);
35
+ AuthorizationInternalService.markAuthorized(request);
36
+ if (!isAuthorized) {
37
+ response.status(403).json({ message: 'Access denied' });
38
+ return;
39
+ }
40
+ next();
41
+ };
42
+ };
43
+
44
+ export { addTestPermittedAction, clearTestPermittedActions, getTestAuthorizationMiddleware };