@mondaydotcomorg/monday-authorization 1.1.9-featureliorshonehourjwttoken.465 → 1.1.9-featuremosheauthorizationesm.3695

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 (61) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +57 -0
  3. package/dist/attributions-service.d.ts +3 -0
  4. package/dist/attributions-service.js +55 -0
  5. package/dist/authorization-attributes-service.d.ts +44 -0
  6. package/dist/authorization-attributes-service.js +144 -0
  7. package/dist/authorization-internal-service.d.ts +13 -0
  8. package/dist/authorization-internal-service.js +80 -0
  9. package/dist/{lib/authorization-middleware.d.ts → authorization-middleware.d.ts} +2 -1
  10. package/dist/authorization-middleware.js +48 -0
  11. package/dist/{lib/authorization-service.d.ts → authorization-service.d.ts} +2 -1
  12. package/dist/authorization-service.js +176 -0
  13. package/dist/constants/sns.d.ts +3 -0
  14. package/dist/constants/sns.js +9 -0
  15. package/dist/esm/attributions-service.d.ts +3 -0
  16. package/dist/esm/attributions-service.mjs +53 -0
  17. package/dist/esm/authorization-attributes-service.d.ts +44 -0
  18. package/dist/esm/authorization-attributes-service.mjs +138 -0
  19. package/dist/esm/authorization-internal-service.d.ts +13 -0
  20. package/dist/esm/authorization-internal-service.mjs +57 -0
  21. package/dist/esm/authorization-middleware.d.ts +6 -0
  22. package/dist/esm/authorization-middleware.mjs +39 -0
  23. package/dist/esm/authorization-service.d.ts +29 -0
  24. package/dist/esm/authorization-service.mjs +172 -0
  25. package/dist/esm/constants/sns.d.ts +3 -0
  26. package/dist/esm/constants/sns.mjs +5 -0
  27. package/dist/esm/index.d.ts +13 -0
  28. package/dist/esm/index.mjs +21 -0
  29. package/dist/esm/prometheus-service.mjs +45 -0
  30. package/dist/esm/testKit/index.d.ts +11 -0
  31. package/dist/esm/testKit/index.mjs +44 -0
  32. package/dist/esm/types/authorization-attributes-contracts.d.ts +27 -0
  33. package/dist/esm/types/authorization-attributes-contracts.mjs +7 -0
  34. package/dist/esm/types/express.mjs +1 -0
  35. package/dist/esm/types/general.mjs +1 -0
  36. package/dist/esm/types/scoped-actions-contracts.mjs +8 -0
  37. package/dist/index.d.ts +5 -2
  38. package/dist/index.js +18 -14
  39. package/dist/prometheus-service.d.ts +10 -0
  40. package/dist/{lib/prometheus-service.js → prometheus-service.js} +11 -10
  41. package/dist/testKit/index.d.ts +11 -0
  42. package/dist/testKit/index.js +48 -0
  43. package/dist/types/authorization-attributes-contracts.d.ts +27 -0
  44. package/dist/types/authorization-attributes-contracts.js +7 -0
  45. package/dist/types/express.d.ts +10 -0
  46. package/dist/types/express.js +1 -0
  47. package/dist/types/general.d.ts +30 -0
  48. package/dist/types/general.js +1 -0
  49. package/dist/types/scoped-actions-contracts.d.ts +38 -0
  50. package/dist/{lib/types → types}/scoped-actions-contracts.js +3 -4
  51. package/package.json +30 -7
  52. package/dist/lib/authorization-internal-service.d.ts +0 -6
  53. package/dist/lib/authorization-internal-service.js +0 -17
  54. package/dist/lib/authorization-middleware.js +0 -54
  55. package/dist/lib/authorization-service.js +0 -233
  56. package/dist/lib/types/express.js +0 -1
  57. package/dist/lib/types/general.js +0 -2
  58. /package/dist/{lib → esm}/prometheus-service.d.ts +0 -0
  59. /package/dist/{lib → esm}/types/express.d.ts +0 -0
  60. /package/dist/{lib → esm}/types/general.d.ts +0 -0
  61. /package/dist/{lib → esm}/types/scoped-actions-contracts.d.ts +0 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,21 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](http://keepachangelog.com/)
6
6
  and this project adheres to [Semantic Versioning](http://semver.org/).
7
7
 
8
+ ## [1.2.9] - 2024-10-06
9
+ ### Added
10
+ - [`authz/bashanye/add-async-resource-attributes-support`](https://github.com/DaPulse/monday-npm-packages/pull/6859)
11
+ - `AuthorizationAttributesService` - now supports async upsert and delete - requests sent through SNS-SQS).
12
+
13
+ ## [1.2.3] - 2024-06-10
14
+ ### Added
15
+
16
+ - [`feature/yarden/resource-attributes-api-support-authz-sdk (#5826)`](https://github.com/DaPulse/monday-npm-packages/pull/5826)
17
+ - `AuthorizationAttributesService` - now supports upsert (`upsertResourceAttributesSync`) and delete (`deleteResourceAttributesSync`) resource attributes in the authorization MS
18
+
19
+ ## [1.2.0] - 2024-01-05
20
+ ### Added
21
+ - `isAuthorized` now return the unauthorized objects - regardless to the unauthorized ids (which may be missing resource ids if resource has no id, like `feature` e.g.)
22
+
8
23
  ## [1.1.0] - 2023-08-09
9
24
 
10
25
  ### ⚠ BREAKING CHANGES
package/README.md CHANGED
@@ -136,3 +136,60 @@ const canActionInScopeMultipleResponse: ScopedActionResponseObject[] =
136
136
  * ]
137
137
  * /
138
138
  ```
139
+
140
+ ### Authorization Attributes API
141
+ Authorization attributes have 2 options to get called: sync (http request) and async (send to SNS and consumed asynchronously).
142
+ When you have to make sure the change in the attributes applied before the function return, please use the sync method, otherwise use the async
143
+
144
+ #### Sync method
145
+ Use `AuthorizationAttributesService.upsertResourceAttributesSync` to upsert multiple resource attributes in the authorization MS synchronously.
146
+
147
+ ```ts
148
+ import { AuthorizationAttributesService, ResourceAttributeAssignment, ResourceAttributeResponse } from '@mondaydotcomorg/monday-authorization';
149
+
150
+ const accountId = 739630;
151
+ const userId = 4;
152
+ const resourceAttributesAssignments: ResourceAttributeAssignment[] = [
153
+ { resourceId: 18, resourceType: 'workspace', key: 'is_default_workspace', value: 'true' },
154
+ { resourceId: 23, resourceType: 'board', key: 'board_kind', value: 'private' }
155
+ ];
156
+
157
+ const response: ResourceAttributeResponse = await AuthorizationAttributesService.upsertResourceAttributesSync(accountId, userId, resourceAttributesAssignments);
158
+ ```
159
+
160
+ Use `AuthorizationAttributesService.deleteResourceAttributesSync` to delete single resource's attributes in the authorization MS synchronously.
161
+
162
+
163
+ ```ts
164
+ import { AuthorizationAttributesService, ResourceAttributeResponse, Resource } from '@mondaydotcomorg/monday-authorization';
165
+
166
+ const accountId = 739630;
167
+ const userId = 4;
168
+ const resource: Resource = { type: 'workspace', id: 18 };
169
+ const attributeKeys: string[] = ['is_default_workspace', 'workspace_kind'];
170
+
171
+ const response: ResourceAttributeResponse = await AuthorizationAttributesService.deleteResourceAttributesSync(accountId, userId, resource, attributeKeys);
172
+ ```
173
+
174
+ #### Async method
175
+ use `AuthorizationAttributesService.updateResourceAttributesAsync` to upsert or delete multiple resource attributes at once.
176
+
177
+ ```ts
178
+ import { AuthorizationAttributesService, ResourceAttributeAssignment, ResourceAttributeResponse } from '@mondaydotcomorg/monday-authorization';
179
+
180
+ const accountId = 739630;
181
+ const appName = process.env.APP_NAME;
182
+ const callerActionIdentifier = "actions_v2";
183
+ const resourceAttributeOperations: ResourceAttributesOperation[] = [
184
+ { operationType: 'upsert', resourceId: 18, resourceType: 'workspace', key: 'is_default_workspace', value: 'true' },
185
+ { operationType: 'delete', resourceId: 23, resourceType: 'board', key: 'board_kind' }
186
+ ];
187
+
188
+ const response: ResourceAttributeResponse = await AuthorizationAttributesService.updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations);
189
+ ```
190
+
191
+ Special notes for asynchronous operations:
192
+ 1. There is no guarantee about the order of the updates, so don't do multiple operations on the same key in the same resource.
193
+ 2. To update an existing key, just use upsert operation, it'll override previous value.
194
+ 3. Requests with a lot of operations might split to chunks that will be consumed either sequence or in parallel, so there might be a timeframe where some of the operations already applied and some not. Eventually all of them will be applied.
195
+ 4. If your MS depends on the access to the asynchronous operation, you can use a health check operation `asyncResourceAttributesHealthCheck` that will return false if it can't reach to SNS or can't find the required topic. Note it doesn't check write permissions so make sure your MS have permissions to write to the SNS topic.
@@ -0,0 +1,3 @@
1
+ export declare function getAttributionsFromApi(): {
2
+ [key: string]: string;
3
+ };
@@ -0,0 +1,55 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const tridentBackendApi = require('@mondaydotcomorg/trident-backend-api');
4
+ const authorizationInternalService = require('./authorization-internal-service.js');
5
+
6
+ const APP_NAME_VARIABLE_KEY = 'APP_NAME';
7
+ const APP_NAME_HEADER_NAME = 'x-caller-app-name-from-sdk';
8
+ const FROM_SDK_HEADER_SUFFIX = `-from-sdk`;
9
+ let didSendFailureLogOnce = false;
10
+ function getAttributionsFromApi() {
11
+ let callerAppNameFromSdk = {
12
+ [APP_NAME_HEADER_NAME]: tryJsonParse(getEnvVariable(APP_NAME_VARIABLE_KEY)),
13
+ };
14
+ try {
15
+ const tridentContext = tridentBackendApi.Api.getPart('context');
16
+ if (!tridentContext) {
17
+ return callerAppNameFromSdk;
18
+ }
19
+ const { runtimeAttributions } = tridentContext;
20
+ let runtimeAttributionsOutgoingHeaders = runtimeAttributions?.buildOutgoingHeaders('HTTP_INTERNAL');
21
+ if (!runtimeAttributionsOutgoingHeaders) {
22
+ return callerAppNameFromSdk;
23
+ }
24
+ const attributionsHeaders = Object.fromEntries(runtimeAttributionsOutgoingHeaders);
25
+ const attributionHeadersFromSdk = {};
26
+ Object.keys(attributionsHeaders).forEach(function (key) {
27
+ attributionHeadersFromSdk[`${key}${FROM_SDK_HEADER_SUFFIX}`] = attributionsHeaders[key];
28
+ });
29
+ return attributionHeadersFromSdk;
30
+ }
31
+ catch (error) {
32
+ if (!didSendFailureLogOnce) {
33
+ authorizationInternalService.logger.warn({ tag: 'authorization-service', error }, 'Failed to generate attributions headers from the API. Unexpected error while extracting headers. It may be caused by out of date Trident version.');
34
+ didSendFailureLogOnce = true;
35
+ }
36
+ return callerAppNameFromSdk;
37
+ }
38
+ }
39
+ function getEnvVariable(key) {
40
+ const envVar = process.env[key] || process.env[key.toUpperCase()] || process.env[key.toLowerCase()];
41
+ return envVar;
42
+ }
43
+ function tryJsonParse(value) {
44
+ if (!value) {
45
+ return value;
46
+ }
47
+ try {
48
+ return JSON.parse(value);
49
+ }
50
+ catch (_err) {
51
+ return value;
52
+ }
53
+ }
54
+
55
+ exports.getAttributionsFromApi = getAttributionsFromApi;
@@ -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,144 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const chunk = require('lodash/chunk');
4
+ const mondayFetch = require('@mondaydotcomorg/monday-fetch');
5
+ const authorizationInternalService = require('./authorization-internal-service.js');
6
+ const attributionsService = require('./attributions-service.js');
7
+ const tridentBackendApi = require('@mondaydotcomorg/trident-backend-api');
8
+ const mondaySns = require('@mondaydotcomorg/monday-sns');
9
+ const constants_sns = require('./constants/sns.js');
10
+
11
+ const _interopDefault = e => e && e.__esModule ? e : { default: e };
12
+
13
+ const chunk__default = /*#__PURE__*/_interopDefault(chunk);
14
+
15
+ class AuthorizationAttributesService {
16
+ static LOG_TAG = "authorization_attributes";
17
+ /**
18
+ * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
19
+ * @param accountId
20
+ * @param userId
21
+ * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
22
+ * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
23
+ * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
24
+ */
25
+ static async upsertResourceAttributes(accountId, userId, resourceAttributeAssignments) {
26
+ const internalAuthToken = authorizationInternalService.AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
27
+ const attributionHeaders = attributionsService.getAttributionsFromApi();
28
+ const response = await mondayFetch.fetch(this.getResourceAttributesUrl(accountId), {
29
+ method: 'POST',
30
+ headers: {
31
+ Authorization: internalAuthToken,
32
+ 'Content-Type': 'application/json',
33
+ ...attributionHeaders,
34
+ },
35
+ timeout: authorizationInternalService.AuthorizationInternalService.getRequestTimeout(),
36
+ body: JSON.stringify({ resourceAttributeAssignments }),
37
+ }, authorizationInternalService.AuthorizationInternalService.getRequestFetchOptions());
38
+ const responseBody = await response.json();
39
+ authorizationInternalService.AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'upsertResourceAttributesSync');
40
+ return { attributes: responseBody['attributes'] };
41
+ }
42
+ /**
43
+ * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
44
+ * @param accountId
45
+ * @param userId
46
+ * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
47
+ * @param attributeKeys - Array of attribute keys to delete for the resource.
48
+ * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
49
+ */
50
+ static async deleteResourceAttributes(accountId, userId, resource, attributeKeys) {
51
+ const internalAuthToken = authorizationInternalService.AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
52
+ const url = `${this.getResourceAttributesUrl(accountId)}/${resource.type}/${resource.id}`;
53
+ const attributionHeaders = attributionsService.getAttributionsFromApi();
54
+ const response = await mondayFetch.fetch(url, {
55
+ method: 'DELETE',
56
+ headers: {
57
+ Authorization: internalAuthToken,
58
+ 'Content-Type': 'application/json',
59
+ ...attributionHeaders,
60
+ },
61
+ timeout: authorizationInternalService.AuthorizationInternalService.getRequestTimeout(),
62
+ body: JSON.stringify({ keys: attributeKeys }),
63
+ }, authorizationInternalService.AuthorizationInternalService.getRequestFetchOptions());
64
+ const responseBody = await response.json();
65
+ authorizationInternalService.AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'deleteResourceAttributesSync');
66
+ return { attributes: responseBody['attributes'] };
67
+ }
68
+ /**
69
+ * Async function, this function only send the updates request to SNS and return before the change actually took place
70
+ * @param accountId
71
+ * @param appName - App name of the calling app
72
+ * @param callerActionIdentifier - action identifier
73
+ * @param resourceAttributeOperations - Array of operations to do on resource attributes.
74
+ * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
75
+ * */
76
+ static async updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations) {
77
+ const topicArn = this.getSnsTopicArn();
78
+ const sendToSnsPromises = [];
79
+ const operationChucks = chunk__default.default(resourceAttributeOperations, constants_sns.ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
80
+ for (const operationsChunk of operationChucks) {
81
+ sendToSnsPromises.push(this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk));
82
+ }
83
+ return (await Promise.all(sendToSnsPromises)).flat();
84
+ }
85
+ static async sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operations) {
86
+ const payload = {
87
+ kind: constants_sns.RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
88
+ payload: {
89
+ accountId: accountId,
90
+ callerAppName: appName,
91
+ callerActionIdentifier: callerActionIdentifier,
92
+ operations: operations,
93
+ }
94
+ };
95
+ try {
96
+ await mondaySns.sendToSns(payload, topicArn);
97
+ return operations;
98
+ }
99
+ catch (error) {
100
+ authorizationInternalService.logger.error({ error, tag: this.LOG_TAG }, "Authorization resource attributes async update: failed to send operations to SNS");
101
+ return [];
102
+ }
103
+ }
104
+ static getSnsTopicArn() {
105
+ const arnFromApi = tridentBackendApi.Api.getPart('configurationVariables')?.get(constants_sns.RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME).arn;
106
+ if (arnFromApi) {
107
+ return arnFromApi;
108
+ }
109
+ const jsonArnFromEnv = process.env[constants_sns.RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME];
110
+ const arnFromEnv = JSON.parse(jsonArnFromEnv).arn;
111
+ if (arnFromEnv) {
112
+ return arnFromEnv;
113
+ }
114
+ throw new Error('Unable to get sns topic arn from env variable');
115
+ }
116
+ static getResourceAttributesUrl(accountId) {
117
+ return `${process.env.AUTHORIZATION_URL}/attributes/${accountId}/resource`;
118
+ }
119
+ /**
120
+ * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
121
+ * This function can be used as health check for services that updating resource attributes in async is crucial.
122
+ * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
123
+ * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
124
+ * However, this is the best we can do without actually push dummy messages to the SNS.
125
+ * @return {Promise<boolean>} - true if succeeded
126
+ */
127
+ static async asyncResourceAttributesHealthCheck() {
128
+ try {
129
+ const requestedTopicArn = this.getSnsTopicArn();
130
+ const attributes = await mondaySns.getTopicAttributes(requestedTopicArn);
131
+ const isHealthy = !(!attributes || !("TopicArn" in attributes) || attributes.TopicArn !== requestedTopicArn);
132
+ if (!isHealthy) {
133
+ authorizationInternalService.logger.error({ requestedTopicArn, snsReturnedAttributes: attributes, tag: this.LOG_TAG }, "authorization-attributes-service failed in health check");
134
+ }
135
+ return isHealthy;
136
+ }
137
+ catch (error) {
138
+ authorizationInternalService.logger.error({ error, tag: this.LOG_TAG }, "authorization-attributes-service got error during health check");
139
+ return false;
140
+ }
141
+ }
142
+ }
143
+
144
+ exports.AuthorizationAttributesService = AuthorizationAttributesService;
@@ -0,0 +1,13 @@
1
+ import { Request } from 'express';
2
+ import { fetch, MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
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,80 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const mondayJwt = require('@mondaydotcomorg/monday-jwt');
4
+ const MondayLogger = require('@mondaydotcomorg/monday-logger');
5
+
6
+ function _interopNamespace(e) {
7
+ if (e && e.__esModule) return e;
8
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
9
+ if (e) {
10
+ for (const k in e) {
11
+ if (k !== 'default') {
12
+ const d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: () => e[k]
16
+ });
17
+ }
18
+ }
19
+ }
20
+ n.default = e;
21
+ return n;
22
+ }
23
+
24
+ const MondayLogger__namespace = /*#__PURE__*/_interopNamespace(MondayLogger);
25
+
26
+ const INTERNAL_APP_NAME = 'internal_ms';
27
+ const defaultMondayFetchOptions = {
28
+ retries: 3,
29
+ callback: logOnFetchFail,
30
+ };
31
+ function logOnFetchFail(retriesLeft, error) {
32
+ if (retriesLeft == 0) {
33
+ logger.error({ retriesLeft, error }, 'Authorization attempt failed due to network issues');
34
+ }
35
+ else {
36
+ logger.info({ retriesLeft, error }, 'Authorization attempt failed due to network issues, trying again');
37
+ }
38
+ }
39
+ let mondayFetchOptions = defaultMondayFetchOptions;
40
+ const logger = MondayLogger__namespace.getLogger();
41
+ class AuthorizationInternalService {
42
+ static skipAuthorization(requset) {
43
+ requset.authorizationSkipPerformed = true;
44
+ }
45
+ static markAuthorized(request) {
46
+ request.authorizationCheckPerformed = true;
47
+ }
48
+ static failIfNotCoveredByAuthorization(request) {
49
+ if (!request.authorizationCheckPerformed && !request.authorizationSkipPerformed) {
50
+ throw 'Endpoint is not covered by authorization check';
51
+ }
52
+ }
53
+ static throwOnHttpErrorIfNeeded(response, placement) {
54
+ if (response.ok) {
55
+ return;
56
+ }
57
+ const status = response.status;
58
+ logger.error({ tag: 'authorization-service', placement, status }, 'AuthorizationService: authorization request failed');
59
+ throw new Error(`AuthorizationService: [${placement}] authorization request failed with status ${status}`);
60
+ }
61
+ static generateInternalAuthToken(accountId, userId) {
62
+ return mondayJwt.signAuthorizationHeader({ appName: INTERNAL_APP_NAME, accountId, userId });
63
+ }
64
+ static setRequestFetchOptions(customMondayFetchOptions) {
65
+ mondayFetchOptions = {
66
+ ...defaultMondayFetchOptions,
67
+ ...customMondayFetchOptions,
68
+ };
69
+ }
70
+ static getRequestFetchOptions() {
71
+ return mondayFetchOptions;
72
+ }
73
+ static getRequestTimeout() {
74
+ const isDevEnv = process.env.NODE_ENV === 'development';
75
+ return isDevEnv ? 60000 : 2000;
76
+ }
77
+ }
78
+
79
+ exports.AuthorizationInternalService = AuthorizationInternalService;
80
+ exports.logger = logger;
@@ -1,5 +1,6 @@
1
1
  import { NextFunction } from 'express';
2
- import { Action, BaseRequest, BaseResponse, ContextGetter, ResourceGetter } from './types/general';
2
+ import { Action, BaseRequest, BaseResponse, Context, ContextGetter, ResourceGetter } from './types/general';
3
3
  export declare function getAuthorizationMiddleware(action: Action, resourceGetter: ResourceGetter, contextGetter?: ContextGetter): (request: BaseRequest, response: BaseResponse, next: NextFunction) => Promise<void>;
4
4
  export declare function skipAuthorizationMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
5
5
  export declare function authorizationCheckMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
6
+ export declare function defaultContextGetter(request: BaseRequest): Context;
@@ -0,0 +1,48 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const onHeaders = require('on-headers');
4
+ const authorizationInternalService = require('./authorization-internal-service.js');
5
+ const authorizationService = require('./authorization-service.js');
6
+
7
+ const _interopDefault = e => e && e.__esModule ? e : { default: e };
8
+
9
+ const onHeaders__default = /*#__PURE__*/_interopDefault(onHeaders);
10
+
11
+ // getAuthorizationMiddleware is duplicated in testKit/index.ts
12
+ // If you are making changes to this function, please make sure to update the other file as well
13
+ function getAuthorizationMiddleware(action, resourceGetter, contextGetter) {
14
+ return async function authorizationMiddleware(request, response, next) {
15
+ contextGetter ||= defaultContextGetter;
16
+ const { userId, accountId } = contextGetter(request);
17
+ const resources = resourceGetter(request);
18
+ const { isAuthorized } = await authorizationService.AuthorizationService.isAuthorized(accountId, userId, resources, action);
19
+ authorizationInternalService.AuthorizationInternalService.markAuthorized(request);
20
+ if (!isAuthorized) {
21
+ response.status(403).json({ message: 'Access denied' });
22
+ return;
23
+ }
24
+ next();
25
+ };
26
+ }
27
+ function skipAuthorizationMiddleware(request, response, next) {
28
+ authorizationInternalService.AuthorizationInternalService.skipAuthorization(request);
29
+ next();
30
+ }
31
+ function authorizationCheckMiddleware(request, response, next) {
32
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
33
+ onHeaders__default.default(response, function () {
34
+ if (response.statusCode < 400) {
35
+ authorizationInternalService.AuthorizationInternalService.failIfNotCoveredByAuthorization(request);
36
+ }
37
+ });
38
+ }
39
+ next();
40
+ }
41
+ function defaultContextGetter(request) {
42
+ return request.payload;
43
+ }
44
+
45
+ exports.authorizationCheckMiddleware = authorizationCheckMiddleware;
46
+ exports.defaultContextGetter = defaultContextGetter;
47
+ exports.getAuthorizationMiddleware = getAuthorizationMiddleware;
48
+ exports.skipAuthorizationMiddleware = skipAuthorizationMiddleware;
@@ -1,9 +1,10 @@
1
1
  import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
2
2
  import { Action, AuthorizationObject, Resource } from './types/general';
3
- import { ScopedAction, ScopedActionPermit, ScopedActionResponseObject, ScopeOptions } from 'lib/types/scoped-actions-contracts';
3
+ import { ScopedAction, ScopedActionPermit, ScopedActionResponseObject, ScopeOptions } from './types/scoped-actions-contracts';
4
4
  export interface AuthorizeResponse {
5
5
  isAuthorized: boolean;
6
6
  unauthorizedIds?: number[];
7
+ unauthorizedObjects?: AuthorizationObject[];
7
8
  }
8
9
  export declare function setRequestFetchOptions(customMondayFetchOptions: MondayFetchOptions): void;
9
10
  export declare function setRedisClient(client: any, grantedFeatureRedisExpirationInSeconds?: number): void;