@mondaydotcomorg/monday-authorization 3.5.1 → 3.5.3-feat-shaime-support-entity-attributes-in-authorization-sdk-127d99a

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 (124) hide show
  1. package/dist/authorization-attributes-ms-service.d.ts +90 -0
  2. package/dist/authorization-attributes-ms-service.d.ts.map +1 -0
  3. package/dist/authorization-attributes-ms-service.js +351 -0
  4. package/dist/authorization-attributes-service.d.ts +26 -47
  5. package/dist/authorization-attributes-service.d.ts.map +1 -1
  6. package/dist/authorization-attributes-service.js +33 -171
  7. package/dist/authorization-attributes-sns-service.d.ts +90 -0
  8. package/dist/authorization-attributes-sns-service.d.ts.map +1 -0
  9. package/dist/authorization-attributes-sns-service.js +217 -0
  10. package/dist/authorization-middleware.d.ts +2 -2
  11. package/dist/authorization-middleware.d.ts.map +1 -1
  12. package/dist/authorization-service.d.ts +3 -3
  13. package/dist/authorization-service.d.ts.map +1 -1
  14. package/dist/base-attribute-assignment.d.ts +18 -0
  15. package/dist/base-attribute-assignment.d.ts.map +1 -0
  16. package/dist/base-attribute-assignment.js +43 -0
  17. package/dist/constants/sns.d.ts +12 -2
  18. package/dist/constants/sns.d.ts.map +1 -1
  19. package/dist/constants/sns.js +22 -2
  20. package/dist/entity-attribute-assignment.d.ts +14 -0
  21. package/dist/entity-attribute-assignment.d.ts.map +1 -0
  22. package/dist/entity-attribute-assignment.js +24 -0
  23. package/dist/entity-attributes-constants.d.ts +7 -0
  24. package/dist/entity-attributes-constants.d.ts.map +1 -0
  25. package/dist/entity-attributes-constants.js +9 -0
  26. package/dist/errors/argument-error.d.ts +4 -0
  27. package/dist/errors/argument-error.d.ts.map +1 -0
  28. package/dist/errors/argument-error.js +11 -0
  29. package/dist/esm/authorization-attributes-ms-service.d.ts +90 -0
  30. package/dist/esm/authorization-attributes-ms-service.d.ts.map +1 -0
  31. package/dist/esm/authorization-attributes-ms-service.mjs +349 -0
  32. package/dist/esm/authorization-attributes-service.d.ts +26 -47
  33. package/dist/esm/authorization-attributes-service.d.ts.map +1 -1
  34. package/dist/esm/authorization-attributes-service.mjs +33 -167
  35. package/dist/esm/authorization-attributes-sns-service.d.ts +90 -0
  36. package/dist/esm/authorization-attributes-sns-service.d.ts.map +1 -0
  37. package/dist/esm/authorization-attributes-sns-service.mjs +211 -0
  38. package/dist/esm/authorization-middleware.d.ts +2 -2
  39. package/dist/esm/authorization-middleware.d.ts.map +1 -1
  40. package/dist/esm/authorization-service.d.ts +3 -3
  41. package/dist/esm/authorization-service.d.ts.map +1 -1
  42. package/dist/esm/base-attribute-assignment.d.ts +18 -0
  43. package/dist/esm/base-attribute-assignment.d.ts.map +1 -0
  44. package/dist/esm/base-attribute-assignment.mjs +41 -0
  45. package/dist/esm/constants/sns.d.ts +12 -2
  46. package/dist/esm/constants/sns.d.ts.map +1 -1
  47. package/dist/esm/constants/sns.mjs +17 -3
  48. package/dist/esm/entity-attribute-assignment.d.ts +14 -0
  49. package/dist/esm/entity-attribute-assignment.d.ts.map +1 -0
  50. package/dist/esm/entity-attribute-assignment.mjs +22 -0
  51. package/dist/esm/entity-attributes-constants.d.ts +7 -0
  52. package/dist/esm/entity-attributes-constants.d.ts.map +1 -0
  53. package/dist/esm/entity-attributes-constants.mjs +7 -0
  54. package/dist/esm/errors/argument-error.d.ts +4 -0
  55. package/dist/esm/errors/argument-error.d.ts.map +1 -0
  56. package/dist/esm/errors/argument-error.mjs +9 -0
  57. package/dist/esm/index.d.ts +9 -0
  58. package/dist/esm/index.d.ts.map +1 -1
  59. package/dist/esm/index.mjs +7 -0
  60. package/dist/esm/prometheus-service.d.ts +1 -2
  61. package/dist/esm/prometheus-service.d.ts.map +1 -1
  62. package/dist/esm/resource-attribute-assignment.d.ts +24 -0
  63. package/dist/esm/resource-attribute-assignment.d.ts.map +1 -0
  64. package/dist/esm/resource-attribute-assignment.mjs +34 -0
  65. package/dist/esm/resource-attributes-constants.d.ts +15 -0
  66. package/dist/esm/resource-attributes-constants.d.ts.map +1 -0
  67. package/dist/esm/resource-attributes-constants.mjs +25 -0
  68. package/dist/esm/testKit/index.d.ts +4 -4
  69. package/dist/esm/testKit/index.d.ts.map +1 -1
  70. package/dist/esm/types/authorization-attributes-contracts.d.ts +27 -12
  71. package/dist/esm/types/authorization-attributes-contracts.d.ts.map +1 -1
  72. package/dist/esm/types/authorization-attributes-contracts.mjs +6 -6
  73. package/dist/esm/types/authorization-attributes-service.interface.d.ts +56 -0
  74. package/dist/esm/types/authorization-attributes-service.interface.d.ts.map +1 -0
  75. package/dist/esm/types/authorization-attributes-service.interface.mjs +1 -0
  76. package/dist/esm/types/general.d.ts +1 -2
  77. package/dist/esm/types/general.d.ts.map +1 -1
  78. package/dist/esm/utils/validation.d.ts +45 -0
  79. package/dist/esm/utils/validation.d.ts.map +1 -0
  80. package/dist/esm/utils/validation.mjs +117 -0
  81. package/dist/index.d.ts +9 -0
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +15 -0
  84. package/dist/prometheus-service.d.ts +1 -2
  85. package/dist/prometheus-service.d.ts.map +1 -1
  86. package/dist/resource-attribute-assignment.d.ts +24 -0
  87. package/dist/resource-attribute-assignment.d.ts.map +1 -0
  88. package/dist/resource-attribute-assignment.js +36 -0
  89. package/dist/resource-attributes-constants.d.ts +15 -0
  90. package/dist/resource-attributes-constants.d.ts.map +1 -0
  91. package/dist/resource-attributes-constants.js +28 -0
  92. package/dist/testKit/index.d.ts +4 -4
  93. package/dist/testKit/index.d.ts.map +1 -1
  94. package/dist/types/authorization-attributes-contracts.d.ts +27 -12
  95. package/dist/types/authorization-attributes-contracts.d.ts.map +1 -1
  96. package/dist/types/authorization-attributes-contracts.js +5 -5
  97. package/dist/types/authorization-attributes-service.interface.d.ts +56 -0
  98. package/dist/types/authorization-attributes-service.interface.d.ts.map +1 -0
  99. package/dist/types/authorization-attributes-service.interface.js +1 -0
  100. package/dist/types/general.d.ts +1 -2
  101. package/dist/types/general.d.ts.map +1 -1
  102. package/dist/utils/validation.d.ts +45 -0
  103. package/dist/utils/validation.d.ts.map +1 -0
  104. package/dist/utils/validation.js +119 -0
  105. package/package.json +3 -2
  106. package/src/authorization-attributes-ms-service.ts +513 -0
  107. package/src/authorization-attributes-service.ts +35 -222
  108. package/src/authorization-attributes-sns-service.ts +312 -0
  109. package/src/authorization-middleware.ts +2 -2
  110. package/src/authorization-service.ts +4 -4
  111. package/src/base-attribute-assignment.ts +55 -0
  112. package/src/constants/sns.ts +19 -2
  113. package/src/entity-attribute-assignment.ts +21 -0
  114. package/src/entity-attributes-constants.ts +7 -0
  115. package/src/errors/argument-error.ts +7 -0
  116. package/src/index.ts +9 -0
  117. package/src/prometheus-service.ts +1 -3
  118. package/src/resource-attribute-assignment.ts +43 -0
  119. package/src/resource-attributes-constants.ts +35 -0
  120. package/src/testKit/index.ts +5 -5
  121. package/src/types/authorization-attributes-contracts.ts +36 -11
  122. package/src/types/authorization-attributes-service.interface.ts +101 -0
  123. package/src/types/general.ts +3 -2
  124. package/src/utils/validation.ts +114 -0
@@ -1,234 +1,47 @@
1
- import chunk from 'lodash/chunk.js';
2
- import { Api, FetcherConfig, HttpClient } from '@mondaydotcomorg/trident-backend-api';
3
- import { getTopicAttributes, sendToSns } from '@mondaydotcomorg/monday-sns';
4
- import { HttpFetcherError, RecursivePartial } from '@mondaydotcomorg/monday-fetch-api';
5
- import {
6
- ResourceAttributeAssignment,
7
- ResourceAttributeResponse,
8
- ResourceAttributesOperation,
9
- } from './types/authorization-attributes-contracts';
10
- import { Resource } from './types/general';
11
- import { logger } from './authorization-internal-service';
12
- import { getAttributionsFromApi } from './attributions-service';
13
- import {
14
- ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
15
- RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
16
- SNS_ARN_ENV_VAR_NAME,
17
- SNS_DEV_TEST_NAME,
18
- } from './constants/sns';
19
- import { APP_NAME, DEFAULT_FETCH_OPTIONS, ERROR_MESSAGES } from './constants';
20
- import type { TopicAttributesMap } from 'aws-sdk/clients/sns';
21
-
1
+ import { AuthorizationAttributesMsService } from './authorization-attributes-ms-service';
2
+ import { AuthorizationAttributesSnsService } from './authorization-attributes-sns-service';
3
+ import { IAuthorizationAttributesService } from './types/authorization-attributes-service.interface';
4
+
5
+ /**
6
+ * Main service class for managing resource and entity attributes.
7
+ * Provides access to both direct (MS) and SNS operations.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const service = new AuthorizationAttributesService();
12
+ *
13
+ * // Use direct operations
14
+ * await service.direct().upsertResourceAttributes(accountId, assignments);
15
+ *
16
+ * // Use SNS operations
17
+ * await service.sns().upsertResourceAttributes(accountId, assignments, appName, actionId);
18
+ * ```
19
+ */
22
20
  export class AuthorizationAttributesService {
23
- private static LOG_TAG = 'authorization_attributes';
24
- private static API_PATHS = {
25
- UPSERT_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource',
26
- DELETE_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource/{resourceType}/{resourceId}',
27
- } as const;
28
- private httpClient: HttpClient;
29
- private fetchOptions: RecursivePartial<FetcherConfig>;
30
- private snsArn: string;
31
-
32
- /**
33
- * Public constructor to create the AuthorizationAttributesService instance.
34
- * @param httpClient The HTTP client to use for API requests, if not provided, the default HTTP client from Api will be used.
35
- * @param fetchOptions The fetch options to use for API requests, if not provided, the default fetch options will be used.
36
- */
37
- constructor(httpClient?: HttpClient, fetchOptions?: RecursivePartial<FetcherConfig>) {
38
- if (!httpClient) {
39
- httpClient = Api.getPart('httpClient');
40
- if (!httpClient) {
41
- throw new Error(ERROR_MESSAGES.HTTP_CLIENT_NOT_INITIALIZED);
42
- }
43
- }
44
-
45
- if (!fetchOptions) {
46
- fetchOptions = DEFAULT_FETCH_OPTIONS;
47
- } else {
48
- fetchOptions = {
49
- ...DEFAULT_FETCH_OPTIONS,
50
- ...fetchOptions,
51
- };
52
- }
53
- this.httpClient = httpClient;
54
- this.fetchOptions = fetchOptions;
55
- this.snsArn = AuthorizationAttributesService.getSnsTopicArn();
56
- }
57
-
58
- /**
59
- * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
60
- * @param accountId
61
- * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
62
- * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
63
- * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
64
- */
65
- async upsertResourceAttributes(
66
- accountId: number,
67
- resourceAttributeAssignments: ResourceAttributeAssignment[]
68
- ): Promise<ResourceAttributeResponse> {
69
- const attributionHeaders = getAttributionsFromApi();
70
- try {
71
- return await this.httpClient.fetch<ResourceAttributeResponse>(
72
- {
73
- url: {
74
- appName: APP_NAME,
75
- path: AuthorizationAttributesService.API_PATHS.UPSERT_RESOURCE_ATTRIBUTES.replace(
76
- '{accountId}',
77
- accountId.toString()
78
- ),
79
- },
80
- method: 'POST',
81
- headers: {
82
- 'Content-Type': 'application/json',
83
- ...attributionHeaders,
84
- },
85
- body: JSON.stringify({ resourceAttributeAssignments }),
86
- },
87
- this.fetchOptions
88
- );
89
- } catch (err) {
90
- if (err instanceof HttpFetcherError) {
91
- throw new Error(ERROR_MESSAGES.REQUEST_FAILED('upsertResourceAttributes', err.status, err.message));
92
- }
93
- throw err;
94
- }
95
- }
21
+ private _directService: AuthorizationAttributesMsService | null = null;
22
+ private _snsService: AuthorizationAttributesSnsService | null = null;
96
23
 
97
24
  /**
98
- * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
99
- * @param accountId
100
- * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
101
- * @param attributeKeys - Array of attribute keys to delete for the resource.
102
- * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
25
+ * Gets the direct (MS) service instance.
26
+ * Initializes the service on first access (lazy initialization).
27
+ * @returns IAuthorizationAttributesService instance
103
28
  */
104
- async deleteResourceAttributes(
105
- accountId: number,
106
- resource: Resource,
107
- attributeKeys: string[]
108
- ): Promise<ResourceAttributeResponse> {
109
- const attributionHeaders = getAttributionsFromApi();
110
- if (!resource.id) {
111
- throw new Error('Resource ID is required');
112
- }
113
- try {
114
- return await this.httpClient.fetch<ResourceAttributeResponse>(
115
- {
116
- url: {
117
- appName: APP_NAME,
118
- path: AuthorizationAttributesService.API_PATHS.DELETE_RESOURCE_ATTRIBUTES.replace(
119
- '{accountId}',
120
- accountId.toString()
121
- )
122
- .replace('{resourceType}', resource.type)
123
- .replace('{resourceId}', resource.id.toString()),
124
- },
125
- method: 'DELETE',
126
- headers: {
127
- 'Content-Type': 'application/json',
128
- ...attributionHeaders,
129
- },
130
- body: JSON.stringify({ keys: attributeKeys }),
131
- },
132
- this.fetchOptions
133
- );
134
- } catch (err) {
135
- if (err instanceof HttpFetcherError) {
136
- throw new Error(ERROR_MESSAGES.REQUEST_FAILED('deleteResourceAttributes', err.status, err.message));
137
- }
138
- throw err;
139
- }
140
- }
141
-
142
- /**
143
- * Async function, this function only send the updates request to SNS and return before the change actually took place
144
- * @param accountId
145
- * @param appName - App name of the calling app
146
- * @param callerActionIdentifier - action identifier
147
- * @param resourceAttributeOperations - Array of operations to do on resource attributes.
148
- * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
149
- * */
150
- async updateResourceAttributesAsync(
151
- accountId: number,
152
- appName: string,
153
- callerActionIdentifier: string,
154
- resourceAttributeOperations: ResourceAttributesOperation[]
155
- ): Promise<ResourceAttributesOperation[]> {
156
- const topicArn: string = this.snsArn;
157
- const sendToSnsPromises: Promise<ResourceAttributesOperation[]>[] = [];
158
- const operationChucks = chunk(resourceAttributeOperations, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
159
- for (const operationsChunk of operationChucks) {
160
- sendToSnsPromises.push(
161
- this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk)
162
- );
163
- }
164
- return (await Promise.all(sendToSnsPromises)).flat();
165
- }
166
-
167
- private async sendSingleSnsMessage(
168
- topicArn: string,
169
- accountId: number,
170
- appName: string,
171
- callerActionIdentifier: string,
172
- operations: ResourceAttributesOperation[]
173
- ): Promise<ResourceAttributesOperation[]> {
174
- const payload = {
175
- kind: RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
176
- payload: {
177
- accountId: accountId,
178
- callerAppName: appName,
179
- callerActionIdentifier: callerActionIdentifier,
180
- operations: operations,
181
- },
182
- };
183
- try {
184
- await sendToSns(payload, topicArn);
185
- return operations;
186
- } catch (error) {
187
- logger.error(
188
- { error, tag: AuthorizationAttributesService.LOG_TAG },
189
- 'Authorization resource attributes async update: failed to send operations to SNS'
190
- );
191
- return [];
192
- }
193
- }
194
-
195
- private static getSnsTopicArn(): string {
196
- const arnFromEnv: string | undefined = process.env[SNS_ARN_ENV_VAR_NAME];
197
- if (arnFromEnv) {
198
- return arnFromEnv;
199
- }
200
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
201
- return SNS_DEV_TEST_NAME;
29
+ direct(): IAuthorizationAttributesService {
30
+ if (this._directService === null) {
31
+ this._directService = new AuthorizationAttributesMsService();
202
32
  }
203
- throw new Error('Unable to get sns topic arn from env variable');
33
+ return this._directService;
204
34
  }
205
35
 
206
36
  /**
207
- * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
208
- * This function can be used as health check for services that updating resource attributes in async is crucial.
209
- * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
210
- * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
211
- * However, this is the best we can do without actually push dummy messages to the SNS.
212
- * @return {Promise<boolean>} - true if succeeded
37
+ * Gets the SNS service instance.
38
+ * Initializes the service on first access (lazy initialization).
39
+ * @returns IAuthorizationAttributesService instance
213
40
  */
214
- async asyncResourceAttributesHealthCheck(): Promise<boolean> {
215
- try {
216
- const requestedTopicArn: string = this.snsArn;
217
- const attributes: TopicAttributesMap = await getTopicAttributes(requestedTopicArn);
218
- const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
219
- if (!isHealthy) {
220
- logger.error(
221
- { requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesService.LOG_TAG },
222
- 'authorization-attributes-service failed in health check'
223
- );
224
- }
225
- return isHealthy;
226
- } catch (error) {
227
- logger.error(
228
- { error, tag: AuthorizationAttributesService.LOG_TAG },
229
- 'authorization-attributes-service got error during health check'
230
- );
231
- return false;
41
+ sns(): IAuthorizationAttributesService {
42
+ if (this._snsService === null) {
43
+ this._snsService = new AuthorizationAttributesSnsService();
232
44
  }
45
+ return this._snsService;
233
46
  }
234
47
  }
@@ -0,0 +1,312 @@
1
+ import chunk from 'lodash/chunk.js';
2
+ import { getTopicAttributes, sendToSns } from '@mondaydotcomorg/monday-sns';
3
+ import {
4
+ ResourceAttributeAssignment,
5
+ ResourceAttributeOperation,
6
+ EntityAttributeOperation,
7
+ AttributeOperation,
8
+ EntityType,
9
+ } from './types/authorization-attributes-contracts';
10
+ import { EntityAttributeAssignment } from './entity-attribute-assignment';
11
+ import { Resource } from './types/general';
12
+ import { logger } from './authorization-internal-service';
13
+ import {
14
+ ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
15
+ ASYNC_ENTITY_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
16
+ RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
17
+ ENTITY_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
18
+ RESOURCE_SNS_ARN_ENV_VAR_NAME,
19
+ ENTITY_SNS_ARN_ENV_VAR_NAME,
20
+ RESOURCE_SNS_DEV_TEST_NAME,
21
+ ENTITY_SNS_DEV_TEST_NAME,
22
+ SnsTopicType,
23
+ } from './constants/sns';
24
+ import type { TopicAttributesMap } from 'aws-sdk/clients/sns';
25
+ import { IAuthorizationAttributesService } from './types/authorization-attributes-service.interface';
26
+
27
+ /**
28
+ * Service class for managing resource attributes asynchronously via SNS.
29
+ * Provides asynchronous operations to create/update and delete attributes on resources.
30
+ */
31
+ export class AuthorizationAttributesSnsService implements IAuthorizationAttributesService {
32
+ private static LOG_TAG = 'authorization_attributes';
33
+ private resourceSnsArn: string;
34
+ private entitySnsArn: string;
35
+
36
+ /**
37
+ * Public constructor to create the AuthorizationAttributesSnsService instance.
38
+ */
39
+ constructor() {
40
+ this.resourceSnsArn = AuthorizationAttributesSnsService.getSnsTopicArn(SnsTopicType.RESOURCE);
41
+ this.entitySnsArn = AuthorizationAttributesSnsService.getSnsTopicArn(SnsTopicType.ENTITY);
42
+ }
43
+
44
+ /**
45
+ * Async function to upsert resource attributes using SNS.
46
+ * Sends the updates request to SNS and returns before the change actually took place.
47
+ * @param accountId The account ID
48
+ * @param appName App name of the calling app
49
+ * @param callerActionIdentifier Action identifier
50
+ * @param resourceAttributeAssignments Array of resource attribute assignments to upsert
51
+ * @return Promise with array of sent operations
52
+ */
53
+ async upsertResourceAttributes(
54
+ accountId: number,
55
+ resourceAttributeAssignments: ResourceAttributeAssignment[],
56
+ appName?: string,
57
+ callerActionIdentifier?: string
58
+ ): Promise<ResourceAttributeOperation[]> {
59
+ if (!appName || !callerActionIdentifier) {
60
+ throw new Error('appName and callerActionIdentifier are required for SNS service');
61
+ }
62
+ const operations: ResourceAttributeOperation[] = resourceAttributeAssignments.map(assignment => ({
63
+ ...assignment,
64
+ operationType: AttributeOperation.UPSERT,
65
+ }));
66
+ return this.updateResourceAttributes(accountId, appName, callerActionIdentifier, operations);
67
+ }
68
+
69
+ /**
70
+ * Async function to delete resource attributes using SNS.
71
+ * Sends the updates request to SNS and returns before the change actually took place.
72
+ * @param accountId The account ID
73
+ * @param appName App name of the calling app
74
+ * @param callerActionIdentifier Action identifier
75
+ * @param resource The resource (resourceType, resourceId)
76
+ * @param attributeKeys Array of attribute keys to delete
77
+ * @return Promise with array of sent operations
78
+ */
79
+ async deleteResourceAttributes(
80
+ accountId: number,
81
+ resource: Resource,
82
+ attributeKeys: string[],
83
+ appName?: string,
84
+ callerActionIdentifier?: string
85
+ ): Promise<ResourceAttributeOperation[]> {
86
+ if (!appName || !callerActionIdentifier) {
87
+ throw new Error('appName and callerActionIdentifier are required for SNS service');
88
+ }
89
+ const operations: ResourceAttributeOperation[] = attributeKeys.map(
90
+ key =>
91
+ ({
92
+ resourceType: resource.type,
93
+ resourceId: resource.id!,
94
+ key,
95
+ operationType: AttributeOperation.DELETE,
96
+ } as ResourceAttributeOperation)
97
+ );
98
+ return this.updateResourceAttributes(accountId, appName, callerActionIdentifier, operations);
99
+ }
100
+
101
+ /**
102
+ * Async function to upsert entity attributes using SNS.
103
+ * Sends the updates request to SNS and returns before the change actually took place.
104
+ * @param accountId The account ID
105
+ * @param appName App name of the calling app
106
+ * @param callerActionIdentifier Action identifier
107
+ * @param entityAttributeAssignments Array of entity attribute assignments to upsert
108
+ * @return Promise with array of sent operations
109
+ */
110
+ async upsertEntityAttributes(
111
+ accountId: number,
112
+ entityAttributeAssignments: EntityAttributeAssignment[],
113
+ appName?: string,
114
+ callerActionIdentifier?: string
115
+ ): Promise<EntityAttributeOperation[]> {
116
+ if (!appName || !callerActionIdentifier) {
117
+ throw new Error('appName and callerActionIdentifier are required for SNS service');
118
+ }
119
+ const operations: EntityAttributeOperation[] = entityAttributeAssignments.map(assignment => {
120
+ return {
121
+ entityId: assignment.entityId,
122
+ entityType: assignment.entityType,
123
+ key: assignment.attributeKey,
124
+ value: assignment.attributeValue,
125
+ operationType: AttributeOperation.UPSERT,
126
+ };
127
+ });
128
+ return this.updateEntityAttributes(accountId, appName, callerActionIdentifier, operations);
129
+ }
130
+
131
+ /**
132
+ * Async function to delete entity attributes using SNS.
133
+ * Sends the updates request to SNS and returns before the change actually took place.
134
+ * @param accountId The account ID
135
+ * @param appName App name of the calling app
136
+ * @param callerActionIdentifier Action identifier
137
+ * @param entityType The entity type
138
+ * @param entityId The entity ID
139
+ * @param attributeKeys Array of attribute keys to delete
140
+ * @return Promise with array of sent operations
141
+ */
142
+ async deleteEntityAttributes(
143
+ accountId: number,
144
+ entityType: EntityType | string,
145
+ entityId: number,
146
+ attributeKeys: string[],
147
+ appName?: string,
148
+ callerActionIdentifier?: string
149
+ ): Promise<EntityAttributeOperation[]> {
150
+ if (!appName || !callerActionIdentifier) {
151
+ throw new Error('appName and callerActionIdentifier are required for SNS service');
152
+ }
153
+ const operations: EntityAttributeOperation[] = attributeKeys.map(
154
+ key =>
155
+ ({
156
+ entityType: entityType,
157
+ entityId,
158
+ key,
159
+ operationType: AttributeOperation.DELETE,
160
+ } as EntityAttributeOperation)
161
+ );
162
+ return this.updateEntityAttributes(accountId, appName, callerActionIdentifier, operations);
163
+ }
164
+
165
+ /**
166
+ * Async function, this function only send the updates request to SNS and return before the change actually took place
167
+ * @param accountId
168
+ * @param appName - App name of the calling app
169
+ * @param callerActionIdentifier - action identifier
170
+ * @param resourceAttributeOperations - Array of operations to do on resource attributes.
171
+ * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
172
+ * */
173
+ async updateResourceAttributes(
174
+ accountId: number,
175
+ appName: string,
176
+ callerActionIdentifier: string,
177
+ resourceAttributeOperations: ResourceAttributeOperation[]
178
+ ): Promise<ResourceAttributeOperation[]> {
179
+ const topicArn: string = this.resourceSnsArn;
180
+ const sendToSnsPromises: Promise<ResourceAttributeOperation[]>[] = [];
181
+ const operationChucks = chunk(resourceAttributeOperations, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
182
+ for (const operationsChunk of operationChucks) {
183
+ sendToSnsPromises.push(
184
+ this.sendSingleSnsMessage(
185
+ topicArn,
186
+ accountId,
187
+ appName,
188
+ callerActionIdentifier,
189
+ operationsChunk,
190
+ RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
191
+ 'Authorization resource attributes async update: failed to send operations to SNS'
192
+ )
193
+ );
194
+ }
195
+ return (await Promise.all(sendToSnsPromises)).flat();
196
+ }
197
+
198
+ /**
199
+ * Async function, this function only send the updates request to SNS and return before the change actually took place
200
+ * @param accountId
201
+ * @param appName - App name of the calling app
202
+ * @param callerActionIdentifier - action identifier
203
+ * @param entityAttributeOperations - Array of operations to do on entity attributes.
204
+ * @return {Promise<EntityAttributeOperation[]>} Array of sent operations
205
+ * */
206
+ async updateEntityAttributes(
207
+ accountId: number,
208
+ appName: string,
209
+ callerActionIdentifier: string,
210
+ entityAttributeOperations: EntityAttributeOperation[]
211
+ ): Promise<EntityAttributeOperation[]> {
212
+ const topicArn: string = this.entitySnsArn;
213
+ const sendToSnsPromises: Promise<EntityAttributeOperation[]>[] = [];
214
+ const operationChucks = chunk(entityAttributeOperations, ASYNC_ENTITY_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
215
+ for (const operationsChunk of operationChucks) {
216
+ sendToSnsPromises.push(
217
+ this.sendSingleSnsMessage(
218
+ topicArn,
219
+ accountId,
220
+ appName,
221
+ callerActionIdentifier,
222
+ operationsChunk,
223
+ ENTITY_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
224
+ 'Authorization entity attributes async update: failed to send operations to SNS'
225
+ )
226
+ );
227
+ }
228
+ return (await Promise.all(sendToSnsPromises)).flat();
229
+ }
230
+
231
+ private async sendSingleSnsMessage<T extends ResourceAttributeOperation | EntityAttributeOperation>(
232
+ topicArn: string,
233
+ accountId: number,
234
+ appName: string,
235
+ callerActionIdentifier: string,
236
+ operations: T[],
237
+ kind: string,
238
+ errorLogMessage: string
239
+ ): Promise<T[]> {
240
+ const payload = {
241
+ kind,
242
+ payload: {
243
+ accountId: accountId,
244
+ callerAppName: appName,
245
+ callerActionIdentifier: callerActionIdentifier,
246
+ operations: operations,
247
+ },
248
+ };
249
+ try {
250
+ await sendToSns(payload, topicArn);
251
+ return operations;
252
+ } catch (error) {
253
+ logger.error({ error, tag: AuthorizationAttributesSnsService.LOG_TAG }, errorLogMessage);
254
+ return [];
255
+ }
256
+ }
257
+
258
+ private static getSnsTopicArn(type: SnsTopicType): string {
259
+ let envVarName: string;
260
+ let devTestName: string;
261
+
262
+ switch (type) {
263
+ case SnsTopicType.ENTITY:
264
+ envVarName = ENTITY_SNS_ARN_ENV_VAR_NAME;
265
+ devTestName = ENTITY_SNS_DEV_TEST_NAME;
266
+ break;
267
+ default:
268
+ // Default to resource SNS constants
269
+ envVarName = RESOURCE_SNS_ARN_ENV_VAR_NAME;
270
+ devTestName = RESOURCE_SNS_DEV_TEST_NAME;
271
+ break;
272
+ }
273
+
274
+ const arnFromEnv: string | undefined = process.env[envVarName];
275
+ if (arnFromEnv) {
276
+ return arnFromEnv;
277
+ }
278
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
279
+ return devTestName;
280
+ }
281
+ throw new Error(`Unable to get ${type} sns topic arn from env variable`);
282
+ }
283
+
284
+ /**
285
+ * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
286
+ * This function can be used as health check for services that updating resource attributes in async is crucial.
287
+ * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
288
+ * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
289
+ * However, this is the best we can do without actually push dummy messages to the SNS.
290
+ * @return {Promise<boolean>} - true if succeeded
291
+ */
292
+ async asyncResourceAttributesHealthCheck(): Promise<boolean> {
293
+ try {
294
+ const requestedTopicArn: string = this.resourceSnsArn;
295
+ const attributes: TopicAttributesMap = await getTopicAttributes(requestedTopicArn);
296
+ const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
297
+ if (!isHealthy) {
298
+ logger.error(
299
+ { requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesSnsService.LOG_TAG },
300
+ 'authorization-attributes-service failed in health check'
301
+ );
302
+ }
303
+ return isHealthy;
304
+ } catch (error) {
305
+ logger.error(
306
+ { error, tag: AuthorizationAttributesSnsService.LOG_TAG },
307
+ 'authorization-attributes-service got error during health check'
308
+ );
309
+ return false;
310
+ }
311
+ }
312
+ }
@@ -1,13 +1,13 @@
1
1
  import onHeaders from 'on-headers';
2
2
  import { AuthorizationInternalService } from './authorization-internal-service';
3
3
  import { AuthorizationService, createAuthorizationParams } from './authorization-service';
4
- import { Action, BaseRequest, BaseResponse, Context, ContextGetter, ResourceGetter } from './types/general';
4
+ import { BaseRequest, BaseResponse, Context, ContextGetter, ResourceGetter } from './types/general';
5
5
  import type { NextFunction } from 'express';
6
6
 
7
7
  // getAuthorizationMiddleware is duplicated in testKit/index.ts
8
8
  // If you are making changes to this function, please make sure to update the other file as well
9
9
  export function getAuthorizationMiddleware(
10
- action: Action,
10
+ action: string,
11
11
  resourceGetter: ResourceGetter,
12
12
  contextGetter?: ContextGetter
13
13
  ) {
@@ -3,7 +3,7 @@ import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
3
3
  import { Api } from '@mondaydotcomorg/trident-backend-api';
4
4
  import { HttpFetcherError } from '@mondaydotcomorg/monday-fetch-api';
5
5
  import { getIgniteClient, IgniteClient } from '@mondaydotcomorg/ignite-sdk';
6
- import { Action, AuthorizationObject, AuthorizationParams, Resource } from './types/general';
6
+ import { AuthorizationObject, AuthorizationParams, Resource } from './types/general';
7
7
  import { sendAuthorizationCheckResponseTimeMetric } from './prometheus-service';
8
8
  import { recordAuthorizationTiming } from './metrics-service';
9
9
  import {
@@ -74,7 +74,7 @@ export class AuthorizationService {
74
74
  accountId: number,
75
75
  userId: number,
76
76
  resources: Resource[],
77
- action: Action
77
+ action: string
78
78
  ): Promise<AuthorizeResponse>;
79
79
 
80
80
  static async isAuthorized(
@@ -223,7 +223,7 @@ export class AuthorizationService {
223
223
  accountId: number,
224
224
  userId: number,
225
225
  resources: Resource[],
226
- action: Action
226
+ action: string
227
227
  ): Promise<AuthorizeResponse> {
228
228
  const { authorizationObjects } = createAuthorizationParams(resources, action);
229
229
  return this.isAuthorizedMultiple(accountId, userId, authorizationObjects);
@@ -338,7 +338,7 @@ export async function setIgniteClient() {
338
338
  AuthorizationInternalService.setIgniteClient(igniteClient);
339
339
  }
340
340
 
341
- export function createAuthorizationParams(resources: Resource[], action: Action): AuthorizationParams {
341
+ export function createAuthorizationParams(resources: Resource[], action: string): AuthorizationParams {
342
342
  const params = {
343
343
  authorizationObjects: resources.map((resource: Resource) => {
344
344
  const authorizationObject: AuthorizationObject = {