@mondaydotcomorg/monday-authorization 3.5.1-fix-authorize-profile-picker-7481de0 → 3.5.3-feat-shaime-support-entity-attributes-in-authorization-sdk-e355942

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