@mondaydotcomorg/monday-authorization 3.5.3-feat-shaime-support-entity-attributes-in-authorization-sdk-ade64f6 → 3.6.0-feat-shaime-support-entity-attributes-1-4c8e283

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 (125) hide show
  1. package/dist/authorization-attributes-service.d.ts +47 -26
  2. package/dist/authorization-attributes-service.d.ts.map +1 -1
  3. package/dist/authorization-attributes-service.js +172 -33
  4. package/dist/authorization-middleware.d.ts +2 -2
  5. package/dist/authorization-middleware.d.ts.map +1 -1
  6. package/dist/authorization-service.d.ts +3 -3
  7. package/dist/authorization-service.d.ts.map +1 -1
  8. package/dist/base-attribute-assignment.d.ts +6 -5
  9. package/dist/base-attribute-assignment.d.ts.map +1 -1
  10. package/dist/base-attribute-assignment.js +8 -17
  11. package/dist/constants/sns.d.ts +2 -12
  12. package/dist/constants/sns.d.ts.map +1 -1
  13. package/dist/constants/sns.js +2 -22
  14. package/dist/entity-attribute-assignment.d.ts +4 -2
  15. package/dist/entity-attribute-assignment.d.ts.map +1 -1
  16. package/dist/entity-attribute-assignment.js +13 -4
  17. package/dist/entity-attributes-constants.d.ts +6 -6
  18. package/dist/entity-attributes-constants.d.ts.map +1 -1
  19. package/dist/entity-attributes-constants.js +7 -5
  20. package/dist/errors/argument-error.d.ts.map +1 -1
  21. package/dist/errors/argument-error.js +0 -1
  22. package/dist/esm/authorization-attributes-service.d.ts +47 -26
  23. package/dist/esm/authorization-attributes-service.d.ts.map +1 -1
  24. package/dist/esm/authorization-attributes-service.mjs +168 -33
  25. package/dist/esm/authorization-middleware.d.ts +2 -2
  26. package/dist/esm/authorization-middleware.d.ts.map +1 -1
  27. package/dist/esm/authorization-service.d.ts +3 -3
  28. package/dist/esm/authorization-service.d.ts.map +1 -1
  29. package/dist/esm/base-attribute-assignment.d.ts +6 -5
  30. package/dist/esm/base-attribute-assignment.d.ts.map +1 -1
  31. package/dist/esm/base-attribute-assignment.mjs +4 -17
  32. package/dist/esm/constants/sns.d.ts +2 -12
  33. package/dist/esm/constants/sns.d.ts.map +1 -1
  34. package/dist/esm/constants/sns.mjs +3 -17
  35. package/dist/esm/entity-attribute-assignment.d.ts +4 -2
  36. package/dist/esm/entity-attribute-assignment.d.ts.map +1 -1
  37. package/dist/esm/entity-attribute-assignment.mjs +13 -4
  38. package/dist/esm/entity-attributes-constants.d.ts +6 -6
  39. package/dist/esm/entity-attributes-constants.d.ts.map +1 -1
  40. package/dist/esm/entity-attributes-constants.mjs +8 -6
  41. package/dist/esm/errors/argument-error.d.ts.map +1 -1
  42. package/dist/esm/errors/argument-error.mjs +0 -1
  43. package/dist/esm/index.d.ts +0 -9
  44. package/dist/esm/index.d.ts.map +1 -1
  45. package/dist/esm/index.mjs +0 -7
  46. package/dist/esm/prometheus-service.d.ts +2 -1
  47. package/dist/esm/prometheus-service.d.ts.map +1 -1
  48. package/dist/esm/resource-attribute-assignment.d.ts +4 -2
  49. package/dist/esm/resource-attribute-assignment.d.ts.map +1 -1
  50. package/dist/esm/resource-attribute-assignment.mjs +11 -2
  51. package/dist/esm/resource-attributes-constants.d.ts +21 -11
  52. package/dist/esm/resource-attributes-constants.d.ts.map +1 -1
  53. package/dist/esm/resource-attributes-constants.mjs +17 -14
  54. package/dist/esm/testKit/index.d.ts +4 -4
  55. package/dist/esm/testKit/index.d.ts.map +1 -1
  56. package/dist/esm/types/authorization-attributes-contracts.d.ts +5 -4
  57. package/dist/esm/types/authorization-attributes-contracts.d.ts.map +1 -1
  58. package/dist/esm/types/authorization-attributes-service.interface.d.ts +7 -20
  59. package/dist/esm/types/authorization-attributes-service.interface.d.ts.map +1 -1
  60. package/dist/esm/types/general.d.ts +2 -1
  61. package/dist/esm/types/general.d.ts.map +1 -1
  62. package/dist/esm/utils/assigment-schema.d.ts +29 -0
  63. package/dist/esm/utils/assigment-schema.d.ts.map +1 -0
  64. package/dist/esm/utils/assigment-schema.mjs +29 -0
  65. package/dist/esm/utils/validation.d.ts +13 -38
  66. package/dist/esm/utils/validation.d.ts.map +1 -1
  67. package/dist/esm/utils/validation.mjs +38 -97
  68. package/dist/index.d.ts +0 -9
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +0 -15
  71. package/dist/prometheus-service.d.ts +2 -1
  72. package/dist/prometheus-service.d.ts.map +1 -1
  73. package/dist/resource-attribute-assignment.d.ts +4 -2
  74. package/dist/resource-attribute-assignment.d.ts.map +1 -1
  75. package/dist/resource-attribute-assignment.js +11 -2
  76. package/dist/resource-attributes-constants.d.ts +21 -11
  77. package/dist/resource-attributes-constants.d.ts.map +1 -1
  78. package/dist/resource-attributes-constants.js +16 -13
  79. package/dist/testKit/index.d.ts +4 -4
  80. package/dist/testKit/index.d.ts.map +1 -1
  81. package/dist/types/authorization-attributes-contracts.d.ts +5 -4
  82. package/dist/types/authorization-attributes-contracts.d.ts.map +1 -1
  83. package/dist/types/authorization-attributes-service.interface.d.ts +7 -20
  84. package/dist/types/authorization-attributes-service.interface.d.ts.map +1 -1
  85. package/dist/types/general.d.ts +2 -1
  86. package/dist/types/general.d.ts.map +1 -1
  87. package/dist/utils/assigment-schema.d.ts +29 -0
  88. package/dist/utils/assigment-schema.d.ts.map +1 -0
  89. package/dist/utils/assigment-schema.js +36 -0
  90. package/dist/utils/validation.d.ts +13 -38
  91. package/dist/utils/validation.d.ts.map +1 -1
  92. package/dist/utils/validation.js +42 -97
  93. package/package.json +3 -3
  94. package/src/authorization-attributes-service.ts +223 -35
  95. package/src/authorization-middleware.ts +2 -2
  96. package/src/authorization-service.ts +4 -4
  97. package/src/base-attribute-assignment.ts +10 -35
  98. package/src/constants/sns.ts +2 -19
  99. package/src/entity-attribute-assignment.ts +17 -5
  100. package/src/entity-attributes-constants.ts +6 -6
  101. package/src/errors/argument-error.ts +0 -1
  102. package/src/index.ts +0 -9
  103. package/src/prometheus-service.ts +3 -1
  104. package/src/resource-attribute-assignment.ts +19 -12
  105. package/src/resource-attributes-constants.ts +15 -23
  106. package/src/testKit/index.ts +5 -5
  107. package/src/types/authorization-attributes-contracts.ts +5 -5
  108. package/src/types/authorization-attributes-service.interface.ts +12 -38
  109. package/src/types/general.ts +2 -3
  110. package/src/utils/assigment-schema.ts +29 -0
  111. package/src/utils/validation.ts +41 -92
  112. package/dist/authorization-attributes-ms-service.d.ts +0 -90
  113. package/dist/authorization-attributes-ms-service.d.ts.map +0 -1
  114. package/dist/authorization-attributes-ms-service.js +0 -369
  115. package/dist/authorization-attributes-sns-service.d.ts +0 -90
  116. package/dist/authorization-attributes-sns-service.d.ts.map +0 -1
  117. package/dist/authorization-attributes-sns-service.js +0 -217
  118. package/dist/esm/authorization-attributes-ms-service.d.ts +0 -90
  119. package/dist/esm/authorization-attributes-ms-service.d.ts.map +0 -1
  120. package/dist/esm/authorization-attributes-ms-service.mjs +0 -367
  121. package/dist/esm/authorization-attributes-sns-service.d.ts +0 -90
  122. package/dist/esm/authorization-attributes-sns-service.d.ts.map +0 -1
  123. package/dist/esm/authorization-attributes-sns-service.mjs +0 -211
  124. package/src/authorization-attributes-ms-service.ts +0 -531
  125. package/src/authorization-attributes-sns-service.ts +0 -312
@@ -1,367 +0,0 @@
1
- import { Api } from '@mondaydotcomorg/trident-backend-api';
2
- import { signAuthorizationHeader } from '@mondaydotcomorg/monday-jwt';
3
- import { z } from 'zod';
4
- import { ResourceAttributeAssignment } from './resource-attribute-assignment.mjs';
5
- import { EntityAttributeAssignment } from './entity-attribute-assignment.mjs';
6
- import { AttributeOperation } from './types/authorization-attributes-contracts.mjs';
7
- import { ArgumentError } from './errors/argument-error.mjs';
8
- import { logger, AuthorizationInternalService } from './authorization-internal-service.mjs';
9
- import { getAttributionsFromApi } from './attributions-service.mjs';
10
- import { APP_NAME } from './constants.mjs';
11
- import { ValidationUtils } from './utils/validation.mjs';
12
-
13
- const INTERNAL_APP_NAME = 'internal_ms';
14
- const UPSERT_RESOURCE_ATTRIBUTES_PATH = '/attributes/{accountId}/resource';
15
- const DELETE_RESOURCE_ATTRIBUTES_PATH = '/attributes/{accountId}/resource/{resourceType}/{resourceId}';
16
- const UPSERT_ENTITY_ATTRIBUTES_PATH = '/attributes/{accountId}/entity';
17
- const DELETE_ENTITY_ATTRIBUTES_PATH = '/attributes/{accountId}/entity/{entityType}/{entityId}';
18
- /**
19
- * Service class for managing resource attributes in the authorization microservice.
20
- * Provides synchronous HTTP operations to create/update and delete attributes on resources.
21
- */
22
- class AuthorizationAttributesMsService {
23
- static LOG_TAG = 'authorization_attributes_ms';
24
- static httpClient = Api.getPart('httpClient');
25
- /**
26
- * Creates or updates resource attributes synchronously.
27
- * @param accountId The account ID
28
- * @param resourceAttributeAssignments Array of ResourceAttributeAssignment objects
29
- * @returns Promise<void>
30
- */
31
- async upsertResourceAttributes(accountId, resourceAttributeAssignments, _appName, _callerActionIdentifier) {
32
- return AuthorizationAttributesMsService.executeUpsertRequest(accountId, resourceAttributeAssignments, UPSERT_RESOURCE_ATTRIBUTES_PATH, 'resourceAttributeAssignments', ResourceAttributeAssignment, 'resource', 'upsertResourceAttributes');
33
- }
34
- /**
35
- * Deletes specific attributes from a resource synchronously.
36
- * @param accountId The account ID
37
- * @param resource Object with resourceType (string) and resourceId (number)
38
- * @param attributeKeys Array of attribute key strings to delete
39
- * @returns Promise<void>
40
- */
41
- async deleteResourceAttributes(accountId, resource, attributeKeys, _appName, _callerActionIdentifier) {
42
- // Validate resource object
43
- if (!resource || typeof resource !== 'object') {
44
- throw new ArgumentError('resource must be an object');
45
- }
46
- if (!resource.id) {
47
- throw new ArgumentError('resource.id is required');
48
- }
49
- ValidationUtils.validateInteger(resource.id, 'resource.id');
50
- ValidationUtils.validateString(resource.type, 'resource.type');
51
- return AuthorizationAttributesMsService.executeDeleteRequest(accountId, DELETE_RESOURCE_ATTRIBUTES_PATH, {
52
- resourceType: resource.type,
53
- resourceId: resource.id,
54
- }, attributeKeys, 'resource', 'deleteResourceAttributesSync', { resource });
55
- }
56
- /**
57
- * Creates or updates entity attributes synchronously.
58
- * @param accountId The account ID
59
- * @param entityAttributeAssignments Array of EntityAttributeAssignment objects
60
- * @returns Promise<void>
61
- */
62
- async upsertEntityAttributes(accountId, entityAttributeAssignments, _appName, _callerActionIdentifier) {
63
- return AuthorizationAttributesMsService.executeUpsertRequest(accountId, entityAttributeAssignments, UPSERT_ENTITY_ATTRIBUTES_PATH, 'entityAttributeAssignments', EntityAttributeAssignment, 'entity', 'upsertEntityAttributesSync');
64
- }
65
- /**
66
- * Deletes specific attributes from an entity synchronously.
67
- * @param accountId The account ID
68
- * @param entityType The entity type
69
- * @param entityId The entity ID
70
- * @param attributeKeys Array of attribute key strings to delete
71
- * @returns Promise<void>
72
- */
73
- async deleteEntityAttributes(accountId, entityType, entityId, attributeKeys, _appName, _callerActionIdentifier) {
74
- if (!entityType || typeof entityType !== 'string' || entityType.trim() === '') {
75
- throw new ArgumentError(`entityType must be a non-empty string, got: ${entityType}`);
76
- }
77
- ValidationUtils.validateInteger(entityId, 'entityId');
78
- return AuthorizationAttributesMsService.executeDeleteRequest(accountId, DELETE_ENTITY_ATTRIBUTES_PATH, {
79
- entityType,
80
- entityId,
81
- }, attributeKeys, 'entity', 'deleteEntityAttributesSync', { entityType, entityId });
82
- }
83
- /**
84
- * Updates resource attributes (batch operations).
85
- * Note: MS service does not support batch operations directly.
86
- * This method processes operations sequentially using upsert/delete methods.
87
- * @param accountId The account ID
88
- * @param appName App name (required for interface compatibility, but not used in MS service)
89
- * @param callerActionIdentifier Action identifier (required for interface compatibility, but not used in MS service)
90
- * @param resourceAttributeOperations Array of operations to perform
91
- * @returns Promise<ResourceAttributesOperation[]> Array of processed operations
92
- */
93
- async updateResourceAttributes(accountId, _appName, _callerActionIdentifier, resourceAttributeOperations) {
94
- const processedOperations = [];
95
- for (const operation of resourceAttributeOperations) {
96
- if (operation.operationType === AttributeOperation.UPSERT) {
97
- if (!operation.resourceId) {
98
- throw new ArgumentError('resourceId is required for upsert operation');
99
- }
100
- await this.upsertResourceAttributes(accountId, [
101
- new ResourceAttributeAssignment(operation.resourceId, operation.resourceType, operation.key, operation.value || ''),
102
- ]);
103
- processedOperations.push(operation);
104
- }
105
- else if (operation.operationType === AttributeOperation.DELETE) {
106
- if (!operation.resourceId) {
107
- throw new ArgumentError('resourceId is required for delete operation');
108
- }
109
- await this.deleteResourceAttributes(accountId, {
110
- type: operation.resourceType,
111
- id: operation.resourceId,
112
- }, [operation.key]);
113
- processedOperations.push(operation);
114
- }
115
- }
116
- return processedOperations;
117
- }
118
- /**
119
- * Updates entity attributes (batch operations).
120
- * Note: MS service does not support batch operations directly.
121
- * This method processes operations sequentially using upsert/delete methods.
122
- * @param accountId The account ID
123
- * @param appName App name (required for interface compatibility, but not used in MS service)
124
- * @param callerActionIdentifier Action identifier (required for interface compatibility, but not used in MS service)
125
- * @param entityAttributeOperations Array of operations to perform
126
- * @returns Promise<EntityAttributesOperation[]> Array of processed operations
127
- */
128
- async updateEntityAttributes(accountId, _appName, _callerActionIdentifier, entityAttributeOperations) {
129
- const processedOperations = [];
130
- for (const operation of entityAttributeOperations) {
131
- if (operation.operationType === 'upsert') {
132
- await this.upsertEntityAttributes(accountId, [
133
- new EntityAttributeAssignment(operation.entityId, operation.entityType, operation.key, operation.value || ''),
134
- ]);
135
- processedOperations.push(operation);
136
- }
137
- else if (operation.operationType === 'delete') {
138
- await this.deleteEntityAttributes(accountId, operation.entityType, operation.entityId, [operation.key]);
139
- processedOperations.push(operation);
140
- }
141
- }
142
- return processedOperations;
143
- }
144
- /**
145
- * Replaces path template parameters with actual values
146
- * @param template Path template with placeholders like {accountId}
147
- * @param params Object with parameter names and values
148
- * @returns Path with all placeholders replaced
149
- */
150
- static replacePathParams(template, params) {
151
- let path = template;
152
- for (const [key, value] of Object.entries(params)) {
153
- path = path.replace(`{${key}}`, String(value));
154
- }
155
- return path;
156
- }
157
- /**
158
- * Generic helper for executing delete requests
159
- */
160
- static async executeDeleteRequest(accountId, pathTemplate, pathParams, keys, logPrefix, methodName, context = {}) {
161
- // Validate inputs
162
- ValidationUtils.validateInteger(accountId, 'accountId');
163
- ValidationUtils.validateArray(keys, 'attributeKeys');
164
- if (!keys.length) {
165
- logger.warn({ tag: this.LOG_TAG, accountId, ...pathParams }, `${methodName} called with empty keys array`);
166
- return;
167
- }
168
- // Validate all keys are strings
169
- ValidationUtils.validateStringArray(keys, 'attributeKeys');
170
- // Build request body
171
- const requestBody = {
172
- keys,
173
- };
174
- if (!AuthorizationAttributesMsService.httpClient) {
175
- throw new Error('AuthorizationAttributesMsService: HTTP client is not initialized');
176
- }
177
- const path = AuthorizationAttributesMsService.replacePathParams(pathTemplate, { accountId, ...pathParams });
178
- const headers = AuthorizationAttributesMsService.getRequestHeaders(accountId);
179
- try {
180
- logger.info({ tag: AuthorizationAttributesMsService.LOG_TAG, accountId, ...pathParams, keys }, `Deleting ${logPrefix} attributes`);
181
- await AuthorizationAttributesMsService.httpClient.fetch({
182
- url: {
183
- appName: APP_NAME,
184
- path,
185
- },
186
- method: 'DELETE',
187
- headers,
188
- body: JSON.stringify(requestBody),
189
- }, {
190
- timeout: AuthorizationInternalService.getRequestTimeout(),
191
- retryPolicy: AuthorizationInternalService.getRetriesPolicy(),
192
- });
193
- logger.info({ tag: AuthorizationAttributesMsService.LOG_TAG, accountId, ...pathParams, keys }, `Successfully deleted ${logPrefix} attributes`);
194
- }
195
- catch (err) {
196
- logger.error({
197
- tag: AuthorizationAttributesMsService.LOG_TAG,
198
- method: methodName,
199
- accountId,
200
- ...pathParams,
201
- ...context,
202
- error: err instanceof Error ? err.message : String(err),
203
- }, `Failed in ${methodName}`);
204
- throw err;
205
- }
206
- }
207
- /**
208
- * Gets request headers including Authorization, Content-Type, and optional attribution headers
209
- */
210
- static getRequestHeaders(accountId, userId) {
211
- const headers = {
212
- 'Content-Type': 'application/json',
213
- };
214
- // Generate Authorization token
215
- const authToken = signAuthorizationHeader({
216
- appName: INTERNAL_APP_NAME,
217
- accountId,
218
- userId,
219
- });
220
- headers.Authorization = authToken;
221
- // Add attribution headers if available
222
- const attributionHeaders = getAttributionsFromApi();
223
- for (const key in attributionHeaders) {
224
- if (Object.prototype.hasOwnProperty.call(attributionHeaders, key)) {
225
- headers[key] = attributionHeaders[key];
226
- }
227
- }
228
- // Add X-REQUEST-ID if available from context
229
- try {
230
- const tridentContext = Api.getPart('context');
231
- if (tridentContext?.runtimeAttributions) {
232
- const outgoingHeaders = tridentContext.runtimeAttributions.buildOutgoingHeaders('HTTP_INTERNAL');
233
- if (outgoingHeaders) {
234
- const attributionHeadersMap = {};
235
- for (const [key, value] of outgoingHeaders) {
236
- attributionHeadersMap[key] = value;
237
- }
238
- if (attributionHeadersMap['x-request-id']) {
239
- headers['X-REQUEST-ID'] = attributionHeadersMap['x-request-id'];
240
- }
241
- }
242
- }
243
- }
244
- catch (error) {
245
- // Silently fail if context is not available
246
- logger.debug({ tag: AuthorizationAttributesMsService.LOG_TAG, error }, 'Failed to get request ID from context');
247
- }
248
- // Add X-REQUEST-START timestamp
249
- headers['X-REQUEST-START'] = Math.floor(Date.now() / 1000).toString();
250
- return headers;
251
- }
252
- /**
253
- * Validates that all messages are instances of the specified message class
254
- */
255
- static validateMessages(attributesMessages, messageClass) {
256
- // Validate messageClass is a function using Zod
257
- const classSchema = z.custom(value => typeof value === 'function', {
258
- message: 'messageClass must be a class/constructor function',
259
- });
260
- try {
261
- classSchema.parse(messageClass);
262
- }
263
- catch (error) {
264
- if (error instanceof z.ZodError) {
265
- const firstError = error.issues[0];
266
- throw new ArgumentError(firstError.message);
267
- }
268
- throw error;
269
- }
270
- const className = messageClass.name || 'ResourceAttributeAssignment';
271
- // First validate it's an array
272
- ValidationUtils.validateArray(attributesMessages, 'attributesMessages');
273
- // Then use Zod to validate each item is an instance of the class
274
- const schema = z.array(z.any()).refine(items => {
275
- for (let i = 0; i < items.length; i++) {
276
- if (!(items[i] instanceof messageClass)) {
277
- return false;
278
- }
279
- }
280
- return true;
281
- }, {
282
- message: `All attributesMessages must be instances of ${className}`,
283
- });
284
- try {
285
- schema.parse(attributesMessages);
286
- }
287
- catch (error) {
288
- if (error instanceof z.ZodError) {
289
- // Find the first invalid index for a more specific error message
290
- const invalidIndex = attributesMessages.findIndex(item => !(item instanceof messageClass));
291
- if (invalidIndex !== -1) {
292
- throw new ArgumentError(`All attributesMessages must be instances of ${className}, but item at index ${invalidIndex} is not`);
293
- }
294
- const firstError = error.issues[0];
295
- throw new ArgumentError(firstError.message);
296
- }
297
- throw error;
298
- }
299
- }
300
- /**
301
- * Generic helper for executing upsert requests
302
- */
303
- static async executeUpsertRequest(accountId, assignments, pathTemplate, requestBodyKey, assignmentClass, logPrefix, methodName) {
304
- // Validate inputs
305
- ValidationUtils.validateInteger(accountId, 'accountId');
306
- ValidationUtils.validateArray(assignments, 'assignments');
307
- if (!assignments.length) {
308
- logger.warn({ tag: AuthorizationAttributesMsService.LOG_TAG, accountId }, `${methodName} called with empty array`);
309
- return;
310
- }
311
- // Validate all assignments are instances of the correct class
312
- AuthorizationAttributesMsService.validateMessages(assignments, assignmentClass);
313
- const compatibileAssignments = assignments.map(assignment => {
314
- if (assignment instanceof ResourceAttributeAssignment) {
315
- return {
316
- resourceId: assignment.resourceId,
317
- resourceType: assignment.resourceType,
318
- key: assignment.attributeKey,
319
- value: assignment.attributeValue,
320
- };
321
- }
322
- else {
323
- return {
324
- entityId: assignment.entityId,
325
- entityType: assignment.entityType,
326
- key: assignment.attributeKey,
327
- value: assignment.attributeValue,
328
- };
329
- }
330
- });
331
- const requestBody = requestBodyKey === 'resourceAttributeAssignments'
332
- ? { resourceAttributeAssignments: compatibileAssignments }
333
- : { entityAttributeAssignments: compatibileAssignments };
334
- if (!AuthorizationAttributesMsService.httpClient) {
335
- throw new Error('AuthorizationAttributesMsService: HTTP client is not initialized');
336
- }
337
- const path = AuthorizationAttributesMsService.replacePathParams(pathTemplate, { accountId });
338
- const headers = AuthorizationAttributesMsService.getRequestHeaders(accountId);
339
- try {
340
- logger.info({ tag: AuthorizationAttributesMsService.LOG_TAG, accountId, count: assignments.length }, `Upserting ${logPrefix} attributes`);
341
- await AuthorizationAttributesMsService.httpClient.fetch({
342
- url: {
343
- appName: APP_NAME,
344
- path,
345
- },
346
- method: 'POST',
347
- headers,
348
- body: JSON.stringify(requestBody),
349
- }, {
350
- timeout: AuthorizationInternalService.getRequestTimeout(),
351
- retryPolicy: AuthorizationInternalService.getRetriesPolicy(),
352
- });
353
- logger.debug({ tag: AuthorizationAttributesMsService.LOG_TAG, accountId, count: assignments.length }, `Successfully upserted ${logPrefix} attributes`);
354
- }
355
- catch (err) {
356
- logger.error({
357
- tag: AuthorizationAttributesMsService.LOG_TAG,
358
- method: methodName,
359
- accountId,
360
- error: err instanceof Error ? err.message : String(err),
361
- }, `Failed in ${methodName}`);
362
- throw err;
363
- }
364
- }
365
- }
366
-
367
- export { AuthorizationAttributesMsService };
@@ -1,90 +0,0 @@
1
- import { ResourceAttributeAssignment, ResourceAttributeOperation, EntityAttributeOperation, EntityType } from './types/authorization-attributes-contracts';
2
- import { EntityAttributeAssignment } from './entity-attribute-assignment';
3
- import { Resource } from './types/general';
4
- import { IAuthorizationAttributesService } from './types/authorization-attributes-service.interface';
5
- /**
6
- * Service class for managing resource attributes asynchronously via SNS.
7
- * Provides asynchronous operations to create/update and delete attributes on resources.
8
- */
9
- export declare class AuthorizationAttributesSnsService implements IAuthorizationAttributesService {
10
- private static LOG_TAG;
11
- private resourceSnsArn;
12
- private entitySnsArn;
13
- /**
14
- * Public constructor to create the AuthorizationAttributesSnsService instance.
15
- */
16
- constructor();
17
- /**
18
- * Async function to upsert resource attributes using SNS.
19
- * Sends the updates request to SNS and returns before the change actually took place.
20
- * @param accountId The account ID
21
- * @param appName App name of the calling app
22
- * @param callerActionIdentifier Action identifier
23
- * @param resourceAttributeAssignments Array of resource attribute assignments to upsert
24
- * @return Promise with array of sent operations
25
- */
26
- upsertResourceAttributes(accountId: number, resourceAttributeAssignments: ResourceAttributeAssignment[], appName?: string, callerActionIdentifier?: string): Promise<ResourceAttributeOperation[]>;
27
- /**
28
- * Async function to delete resource attributes using SNS.
29
- * Sends the updates request to SNS and returns before the change actually took place.
30
- * @param accountId The account ID
31
- * @param appName App name of the calling app
32
- * @param callerActionIdentifier Action identifier
33
- * @param resource The resource (resourceType, resourceId)
34
- * @param attributeKeys Array of attribute keys to delete
35
- * @return Promise with array of sent operations
36
- */
37
- deleteResourceAttributes(accountId: number, resource: Resource, attributeKeys: string[], appName?: string, callerActionIdentifier?: string): Promise<ResourceAttributeOperation[]>;
38
- /**
39
- * Async function to upsert entity attributes using SNS.
40
- * Sends the updates request to SNS and returns before the change actually took place.
41
- * @param accountId The account ID
42
- * @param appName App name of the calling app
43
- * @param callerActionIdentifier Action identifier
44
- * @param entityAttributeAssignments Array of entity attribute assignments to upsert
45
- * @return Promise with array of sent operations
46
- */
47
- upsertEntityAttributes(accountId: number, entityAttributeAssignments: EntityAttributeAssignment[], appName?: string, callerActionIdentifier?: string): Promise<EntityAttributeOperation[]>;
48
- /**
49
- * Async function to delete entity attributes using SNS.
50
- * Sends the updates request to SNS and returns before the change actually took place.
51
- * @param accountId The account ID
52
- * @param appName App name of the calling app
53
- * @param callerActionIdentifier Action identifier
54
- * @param entityType The entity type
55
- * @param entityId The entity ID
56
- * @param attributeKeys Array of attribute keys to delete
57
- * @return Promise with array of sent operations
58
- */
59
- deleteEntityAttributes(accountId: number, entityType: EntityType | string, entityId: number, attributeKeys: string[], appName?: string, callerActionIdentifier?: string): Promise<EntityAttributeOperation[]>;
60
- /**
61
- * Async function, this function only send the updates request to SNS and return before the change actually took place
62
- * @param accountId
63
- * @param appName - App name of the calling app
64
- * @param callerActionIdentifier - action identifier
65
- * @param resourceAttributeOperations - Array of operations to do on resource attributes.
66
- * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
67
- * */
68
- updateResourceAttributes(accountId: number, appName: string, callerActionIdentifier: string, resourceAttributeOperations: ResourceAttributeOperation[]): Promise<ResourceAttributeOperation[]>;
69
- /**
70
- * Async function, this function only send the updates request to SNS and return before the change actually took place
71
- * @param accountId
72
- * @param appName - App name of the calling app
73
- * @param callerActionIdentifier - action identifier
74
- * @param entityAttributeOperations - Array of operations to do on entity attributes.
75
- * @return {Promise<EntityAttributeOperation[]>} Array of sent operations
76
- * */
77
- updateEntityAttributes(accountId: number, appName: string, callerActionIdentifier: string, entityAttributeOperations: EntityAttributeOperation[]): Promise<EntityAttributeOperation[]>;
78
- private sendSingleSnsMessage;
79
- private static getSnsTopicArn;
80
- /**
81
- * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
82
- * This function can be used as health check for services that updating resource attributes in async is crucial.
83
- * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
84
- * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
85
- * However, this is the best we can do without actually push dummy messages to the SNS.
86
- * @return {Promise<boolean>} - true if succeeded
87
- */
88
- asyncResourceAttributesHealthCheck(): Promise<boolean>;
89
- }
90
- //# sourceMappingURL=authorization-attributes-sns-service.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"authorization-attributes-sns-service.d.ts","sourceRoot":"","sources":["../../src/authorization-attributes-sns-service.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,2BAA2B,EAC3B,0BAA0B,EAC1B,wBAAwB,EAExB,UAAU,EACX,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAc3C,OAAO,EAAE,+BAA+B,EAAE,MAAM,oDAAoD,CAAC;AAErG;;;GAGG;AACH,qBAAa,iCAAkC,YAAW,+BAA+B;IACvF,OAAO,CAAC,MAAM,CAAC,OAAO,CAA8B;IACpD,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,YAAY,CAAS;IAE7B;;OAEG;;IAMH;;;;;;;;OAQG;IACG,wBAAwB,CAC5B,SAAS,EAAE,MAAM,EACjB,4BAA4B,EAAE,2BAA2B,EAAE,EAC3D,OAAO,CAAC,EAAE,MAAM,EAChB,sBAAsB,CAAC,EAAE,MAAM,GAC9B,OAAO,CAAC,0BAA0B,EAAE,CAAC;IAWxC;;;;;;;;;OASG;IACG,wBAAwB,CAC5B,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,MAAM,EAAE,EACvB,OAAO,CAAC,EAAE,MAAM,EAChB,sBAAsB,CAAC,EAAE,MAAM,GAC9B,OAAO,CAAC,0BAA0B,EAAE,CAAC;IAgBxC;;;;;;;;OAQG;IACG,sBAAsB,CAC1B,SAAS,EAAE,MAAM,EACjB,0BAA0B,EAAE,yBAAyB,EAAE,EACvD,OAAO,CAAC,EAAE,MAAM,EAChB,sBAAsB,CAAC,EAAE,MAAM,GAC9B,OAAO,CAAC,wBAAwB,EAAE,CAAC;IAgBtC;;;;;;;;;;OAUG;IACG,sBAAsB,CAC1B,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,UAAU,GAAG,MAAM,EAC/B,QAAQ,EAAE,MAAM,EAChB,aAAa,EAAE,MAAM,EAAE,EACvB,OAAO,CAAC,EAAE,MAAM,EAChB,sBAAsB,CAAC,EAAE,MAAM,GAC9B,OAAO,CAAC,wBAAwB,EAAE,CAAC;IAgBtC;;;;;;;UAOM;IACA,wBAAwB,CAC5B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,sBAAsB,EAAE,MAAM,EAC9B,2BAA2B,EAAE,0BAA0B,EAAE,GACxD,OAAO,CAAC,0BAA0B,EAAE,CAAC;IAoBxC;;;;;;;UAOM;IACA,sBAAsB,CAC1B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,sBAAsB,EAAE,MAAM,EAC9B,yBAAyB,EAAE,wBAAwB,EAAE,GACpD,OAAO,CAAC,wBAAwB,EAAE,CAAC;YAoBxB,oBAAoB;IA2BlC,OAAO,CAAC,MAAM,CAAC,cAAc;IA0B7B;;;;;;;OAOG;IACG,kCAAkC,IAAI,OAAO,CAAC,OAAO,CAAC;CAoB7D"}
@@ -1,211 +0,0 @@
1
- import chunk from 'lodash/chunk.js';
2
- import { sendToSns, getTopicAttributes } from '@mondaydotcomorg/monday-sns';
3
- import { AttributeOperation } from './types/authorization-attributes-contracts.mjs';
4
- import { logger } from './authorization-internal-service.mjs';
5
- import { SnsTopicType, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE, RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND, ASYNC_ENTITY_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE, ENTITY_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND, RESOURCE_SNS_ARN_ENV_VAR_NAME, RESOURCE_SNS_DEV_TEST_NAME, ENTITY_SNS_ARN_ENV_VAR_NAME, ENTITY_SNS_DEV_TEST_NAME } from './constants/sns.mjs';
6
-
7
- /**
8
- * Service class for managing resource attributes asynchronously via SNS.
9
- * Provides asynchronous operations to create/update and delete attributes on resources.
10
- */
11
- class AuthorizationAttributesSnsService {
12
- static LOG_TAG = 'authorization_attributes';
13
- resourceSnsArn;
14
- entitySnsArn;
15
- /**
16
- * Public constructor to create the AuthorizationAttributesSnsService instance.
17
- */
18
- constructor() {
19
- this.resourceSnsArn = AuthorizationAttributesSnsService.getSnsTopicArn(SnsTopicType.RESOURCE);
20
- this.entitySnsArn = AuthorizationAttributesSnsService.getSnsTopicArn(SnsTopicType.ENTITY);
21
- }
22
- /**
23
- * Async function to upsert resource attributes using SNS.
24
- * Sends the updates request to SNS and returns before the change actually took place.
25
- * @param accountId The account ID
26
- * @param appName App name of the calling app
27
- * @param callerActionIdentifier Action identifier
28
- * @param resourceAttributeAssignments Array of resource attribute assignments to upsert
29
- * @return Promise with array of sent operations
30
- */
31
- async upsertResourceAttributes(accountId, resourceAttributeAssignments, appName, callerActionIdentifier) {
32
- if (!appName || !callerActionIdentifier) {
33
- throw new Error('appName and callerActionIdentifier are required for SNS service');
34
- }
35
- const operations = resourceAttributeAssignments.map(assignment => ({
36
- ...assignment,
37
- operationType: AttributeOperation.UPSERT,
38
- }));
39
- return this.updateResourceAttributes(accountId, appName, callerActionIdentifier, operations);
40
- }
41
- /**
42
- * Async function to delete resource attributes using SNS.
43
- * Sends the updates request to SNS and returns before the change actually took place.
44
- * @param accountId The account ID
45
- * @param appName App name of the calling app
46
- * @param callerActionIdentifier Action identifier
47
- * @param resource The resource (resourceType, resourceId)
48
- * @param attributeKeys Array of attribute keys to delete
49
- * @return Promise with array of sent operations
50
- */
51
- async deleteResourceAttributes(accountId, resource, attributeKeys, appName, callerActionIdentifier) {
52
- if (!appName || !callerActionIdentifier) {
53
- throw new Error('appName and callerActionIdentifier are required for SNS service');
54
- }
55
- const operations = attributeKeys.map(key => ({
56
- resourceType: resource.type,
57
- resourceId: resource.id,
58
- key,
59
- operationType: AttributeOperation.DELETE,
60
- }));
61
- return this.updateResourceAttributes(accountId, appName, callerActionIdentifier, operations);
62
- }
63
- /**
64
- * Async function to upsert entity attributes using SNS.
65
- * Sends the updates request to SNS and returns before the change actually took place.
66
- * @param accountId The account ID
67
- * @param appName App name of the calling app
68
- * @param callerActionIdentifier Action identifier
69
- * @param entityAttributeAssignments Array of entity attribute assignments to upsert
70
- * @return Promise with array of sent operations
71
- */
72
- async upsertEntityAttributes(accountId, entityAttributeAssignments, appName, callerActionIdentifier) {
73
- if (!appName || !callerActionIdentifier) {
74
- throw new Error('appName and callerActionIdentifier are required for SNS service');
75
- }
76
- const operations = entityAttributeAssignments.map(assignment => {
77
- return {
78
- entityId: assignment.entityId,
79
- entityType: assignment.entityType,
80
- key: assignment.attributeKey,
81
- value: assignment.attributeValue,
82
- operationType: AttributeOperation.UPSERT,
83
- };
84
- });
85
- return this.updateEntityAttributes(accountId, appName, callerActionIdentifier, operations);
86
- }
87
- /**
88
- * Async function to delete entity attributes using SNS.
89
- * Sends the updates request to SNS and returns before the change actually took place.
90
- * @param accountId The account ID
91
- * @param appName App name of the calling app
92
- * @param callerActionIdentifier Action identifier
93
- * @param entityType The entity type
94
- * @param entityId The entity ID
95
- * @param attributeKeys Array of attribute keys to delete
96
- * @return Promise with array of sent operations
97
- */
98
- async deleteEntityAttributes(accountId, entityType, entityId, attributeKeys, appName, callerActionIdentifier) {
99
- if (!appName || !callerActionIdentifier) {
100
- throw new Error('appName and callerActionIdentifier are required for SNS service');
101
- }
102
- const operations = attributeKeys.map(key => ({
103
- entityType: entityType,
104
- entityId,
105
- key,
106
- operationType: AttributeOperation.DELETE,
107
- }));
108
- return this.updateEntityAttributes(accountId, appName, callerActionIdentifier, operations);
109
- }
110
- /**
111
- * Async function, this function only send the updates request to SNS and return before the change actually took place
112
- * @param accountId
113
- * @param appName - App name of the calling app
114
- * @param callerActionIdentifier - action identifier
115
- * @param resourceAttributeOperations - Array of operations to do on resource attributes.
116
- * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
117
- * */
118
- async updateResourceAttributes(accountId, appName, callerActionIdentifier, resourceAttributeOperations) {
119
- const topicArn = this.resourceSnsArn;
120
- const sendToSnsPromises = [];
121
- const operationChucks = chunk(resourceAttributeOperations, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
122
- for (const operationsChunk of operationChucks) {
123
- sendToSnsPromises.push(this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk, RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND, 'Authorization resource attributes async update: failed to send operations to SNS'));
124
- }
125
- return (await Promise.all(sendToSnsPromises)).flat();
126
- }
127
- /**
128
- * Async function, this function only send the updates request to SNS and return before the change actually took place
129
- * @param accountId
130
- * @param appName - App name of the calling app
131
- * @param callerActionIdentifier - action identifier
132
- * @param entityAttributeOperations - Array of operations to do on entity attributes.
133
- * @return {Promise<EntityAttributeOperation[]>} Array of sent operations
134
- * */
135
- async updateEntityAttributes(accountId, appName, callerActionIdentifier, entityAttributeOperations) {
136
- const topicArn = this.entitySnsArn;
137
- const sendToSnsPromises = [];
138
- const operationChucks = chunk(entityAttributeOperations, ASYNC_ENTITY_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
139
- for (const operationsChunk of operationChucks) {
140
- sendToSnsPromises.push(this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk, ENTITY_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND, 'Authorization entity attributes async update: failed to send operations to SNS'));
141
- }
142
- return (await Promise.all(sendToSnsPromises)).flat();
143
- }
144
- async sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operations, kind, errorLogMessage) {
145
- const payload = {
146
- kind,
147
- payload: {
148
- accountId: accountId,
149
- callerAppName: appName,
150
- callerActionIdentifier: callerActionIdentifier,
151
- operations: operations,
152
- },
153
- };
154
- try {
155
- await sendToSns(payload, topicArn);
156
- return operations;
157
- }
158
- catch (error) {
159
- logger.error({ error, tag: AuthorizationAttributesSnsService.LOG_TAG }, errorLogMessage);
160
- return [];
161
- }
162
- }
163
- static getSnsTopicArn(type) {
164
- let envVarName;
165
- let devTestName;
166
- switch (type) {
167
- case SnsTopicType.ENTITY:
168
- envVarName = ENTITY_SNS_ARN_ENV_VAR_NAME;
169
- devTestName = ENTITY_SNS_DEV_TEST_NAME;
170
- break;
171
- default:
172
- // Default to resource SNS constants
173
- envVarName = RESOURCE_SNS_ARN_ENV_VAR_NAME;
174
- devTestName = RESOURCE_SNS_DEV_TEST_NAME;
175
- break;
176
- }
177
- const arnFromEnv = process.env[envVarName];
178
- if (arnFromEnv) {
179
- return arnFromEnv;
180
- }
181
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
182
- return devTestName;
183
- }
184
- throw new Error(`Unable to get ${type} sns topic arn from env variable`);
185
- }
186
- /**
187
- * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
188
- * This function can be used as health check for services that updating resource attributes in async is crucial.
189
- * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
190
- * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
191
- * However, this is the best we can do without actually push dummy messages to the SNS.
192
- * @return {Promise<boolean>} - true if succeeded
193
- */
194
- async asyncResourceAttributesHealthCheck() {
195
- try {
196
- const requestedTopicArn = this.resourceSnsArn;
197
- const attributes = await getTopicAttributes(requestedTopicArn);
198
- const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
199
- if (!isHealthy) {
200
- logger.error({ requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesSnsService.LOG_TAG }, 'authorization-attributes-service failed in health check');
201
- }
202
- return isHealthy;
203
- }
204
- catch (error) {
205
- logger.error({ error, tag: AuthorizationAttributesSnsService.LOG_TAG }, 'authorization-attributes-service got error during health check');
206
- return false;
207
- }
208
- }
209
- }
210
-
211
- export { AuthorizationAttributesSnsService };