@mondaydotcomorg/monday-authorization 3.6.0-feat-shaime-support-entity-attributes-1-f58d933 → 3.6.0-feat-shaime-support-entity-attributes-3-0d092e0

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 (96) hide show
  1. package/dist/authorization-attributes-ms-service.d.ts +68 -0
  2. package/dist/authorization-attributes-ms-service.d.ts.map +1 -0
  3. package/dist/authorization-attributes-ms-service.js +263 -0
  4. package/dist/authorization-attributes-service.d.ts +25 -47
  5. package/dist/authorization-attributes-service.d.ts.map +1 -1
  6. package/dist/authorization-attributes-service.js +32 -171
  7. package/dist/authorization-attributes-sns-service.d.ts +84 -0
  8. package/dist/authorization-attributes-sns-service.d.ts.map +1 -0
  9. package/dist/authorization-attributes-sns-service.js +196 -0
  10. package/dist/constants/sns.d.ts +12 -2
  11. package/dist/constants/sns.d.ts.map +1 -1
  12. package/dist/constants/sns.js +22 -2
  13. package/dist/entity-attribute-assignment.d.ts.map +1 -1
  14. package/dist/entity-attribute-assignment.js +0 -2
  15. package/dist/esm/authorization-attributes-ms-service.d.ts +68 -0
  16. package/dist/esm/authorization-attributes-ms-service.d.ts.map +1 -0
  17. package/dist/esm/authorization-attributes-ms-service.mjs +261 -0
  18. package/dist/esm/authorization-attributes-service.d.ts +25 -47
  19. package/dist/esm/authorization-attributes-service.d.ts.map +1 -1
  20. package/dist/esm/authorization-attributes-service.mjs +32 -167
  21. package/dist/esm/authorization-attributes-sns-service.d.ts +84 -0
  22. package/dist/esm/authorization-attributes-sns-service.d.ts.map +1 -0
  23. package/dist/esm/authorization-attributes-sns-service.mjs +190 -0
  24. package/dist/esm/constants/sns.d.ts +12 -2
  25. package/dist/esm/constants/sns.d.ts.map +1 -1
  26. package/dist/esm/constants/sns.mjs +17 -3
  27. package/dist/esm/entity-attribute-assignment.d.ts.map +1 -1
  28. package/dist/esm/entity-attribute-assignment.mjs +0 -2
  29. package/dist/esm/index.d.ts +6 -0
  30. package/dist/esm/index.d.ts.map +1 -1
  31. package/dist/esm/index.mjs +5 -0
  32. package/dist/esm/resource-attribute-assignment.d.ts.map +1 -1
  33. package/dist/esm/resource-attribute-assignment.mjs +0 -2
  34. package/dist/esm/resource-attributes-constants.d.ts +2 -1
  35. package/dist/esm/resource-attributes-constants.d.ts.map +1 -1
  36. package/dist/esm/resource-attributes-constants.mjs +1 -0
  37. package/dist/esm/types/authorization-attributes-contracts.d.ts +2 -17
  38. package/dist/esm/types/authorization-attributes-contracts.d.ts.map +1 -1
  39. package/dist/esm/types/authorization-attributes-service.interface.d.ts +14 -25
  40. package/dist/esm/types/authorization-attributes-service.interface.d.ts.map +1 -1
  41. package/dist/esm/types/general.d.ts +4 -3
  42. package/dist/esm/types/general.d.ts.map +1 -1
  43. package/dist/esm/utils/assignment-schema.d.ts +51 -0
  44. package/dist/esm/utils/assignment-schema.d.ts.map +1 -0
  45. package/dist/esm/utils/assignment-schema.mjs +49 -0
  46. package/dist/esm/utils/resource-schema.d.ts +9 -0
  47. package/dist/esm/utils/resource-schema.d.ts.map +1 -0
  48. package/dist/esm/utils/resource-schema.mjs +16 -0
  49. package/dist/esm/utils/validation.d.ts +11 -3
  50. package/dist/esm/utils/validation.d.ts.map +1 -1
  51. package/dist/esm/utils/validation.mjs +50 -13
  52. package/dist/index.d.ts +6 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +22 -0
  55. package/dist/resource-attribute-assignment.d.ts.map +1 -1
  56. package/dist/resource-attribute-assignment.js +0 -2
  57. package/dist/resource-attributes-constants.d.ts +2 -1
  58. package/dist/resource-attributes-constants.d.ts.map +1 -1
  59. package/dist/resource-attributes-constants.js +1 -0
  60. package/dist/types/authorization-attributes-contracts.d.ts +2 -17
  61. package/dist/types/authorization-attributes-contracts.d.ts.map +1 -1
  62. package/dist/types/authorization-attributes-service.interface.d.ts +14 -25
  63. package/dist/types/authorization-attributes-service.interface.d.ts.map +1 -1
  64. package/dist/types/general.d.ts +4 -3
  65. package/dist/types/general.d.ts.map +1 -1
  66. package/dist/utils/assignment-schema.d.ts +51 -0
  67. package/dist/utils/assignment-schema.d.ts.map +1 -0
  68. package/dist/utils/assignment-schema.js +58 -0
  69. package/dist/utils/resource-schema.d.ts +9 -0
  70. package/dist/utils/resource-schema.d.ts.map +1 -0
  71. package/dist/utils/resource-schema.js +22 -0
  72. package/dist/utils/validation.d.ts +11 -3
  73. package/dist/utils/validation.d.ts.map +1 -1
  74. package/dist/utils/validation.js +50 -13
  75. package/package.json +1 -1
  76. package/src/authorization-attributes-ms-service.ts +397 -0
  77. package/src/authorization-attributes-service.ts +34 -222
  78. package/src/authorization-attributes-sns-service.ts +321 -0
  79. package/src/constants/sns.ts +19 -2
  80. package/src/entity-attribute-assignment.ts +0 -2
  81. package/src/index.ts +17 -0
  82. package/src/resource-attribute-assignment.ts +0 -2
  83. package/src/resource-attributes-constants.ts +1 -0
  84. package/src/types/authorization-attributes-contracts.ts +2 -24
  85. package/src/types/authorization-attributes-service.interface.ts +19 -31
  86. package/src/types/general.ts +4 -3
  87. package/src/utils/assignment-schema.ts +51 -0
  88. package/src/utils/resource-schema.ts +16 -0
  89. package/src/utils/validation.ts +76 -15
  90. package/dist/esm/utils/assigment-schema.d.ts +0 -29
  91. package/dist/esm/utils/assigment-schema.d.ts.map +0 -1
  92. package/dist/esm/utils/assigment-schema.mjs +0 -29
  93. package/dist/utils/assigment-schema.d.ts +0 -29
  94. package/dist/utils/assigment-schema.d.ts.map +0 -1
  95. package/dist/utils/assigment-schema.js +0 -36
  96. package/src/utils/assigment-schema.ts +0 -29
@@ -1,234 +1,46 @@
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
- ResourceAttributeUpsertOperation,
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 { AuthorizationAttributesService as 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
+ * 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
+ */
22
19
  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
- }
20
+ private _directService: AuthorizationAttributesMsService | null = null;
21
+ private _snsService: AuthorizationAttributesSnsService | null = null;
96
22
 
97
23
  /**
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.
24
+ * Gets the direct (MS) service instance.
25
+ * Initializes the service on first access (lazy initialization).
26
+ * @returns IAuthorizationAttributesService instance
103
27
  */
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: ResourceAttributeUpsertOperation[]
155
- ): Promise<ResourceAttributeUpsertOperation[]> {
156
- const topicArn: string = this.snsArn;
157
- const sendToSnsPromises: Promise<ResourceAttributeAssignment[]>[] = [];
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() as ResourceAttributeUpsertOperation[];
165
- }
166
-
167
- private async sendSingleSnsMessage(
168
- topicArn: string,
169
- accountId: number,
170
- appName: string,
171
- callerActionIdentifier: string,
172
- operations: ResourceAttributeAssignment[]
173
- ): Promise<ResourceAttributeAssignment[]> {
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;
28
+ direct(): IAuthorizationAttributesService {
29
+ if (this._directService === null) {
30
+ this._directService = new AuthorizationAttributesMsService();
202
31
  }
203
- throw new Error('Unable to get sns topic arn from env variable');
32
+ return this._directService;
204
33
  }
205
34
 
206
35
  /**
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
36
+ * Gets the SNS service instance.
37
+ * Initializes the service on first access (lazy initialization).
38
+ * @returns IAuthorizationAttributesService instance
213
39
  */
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;
40
+ sns(): IAuthorizationAttributesService {
41
+ if (this._snsService === null) {
42
+ this._snsService = new AuthorizationAttributesSnsService();
232
43
  }
44
+ return this._snsService;
233
45
  }
234
46
  }
@@ -0,0 +1,321 @@
1
+ import chunk from 'lodash/chunk.js';
2
+ import { getTopicAttributes, sendToSns } from '@mondaydotcomorg/monday-sns';
3
+ import {
4
+ AttributeOperation,
5
+ ResourceAttributeUpsertOperation,
6
+ EntityAttributeUpsertOperation,
7
+ EntityAttributeDeleteOperation,
8
+ ResourceAttributeDeleteOperation,
9
+ } from './types/authorization-attributes-contracts';
10
+ import { Resource } from './types/general';
11
+ import { logger } from './authorization-internal-service';
12
+ import {
13
+ ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
14
+ ASYNC_ENTITY_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
15
+ RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
16
+ ENTITY_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
17
+ RESOURCE_SNS_ARN_ENV_VAR_NAME,
18
+ ENTITY_SNS_ARN_ENV_VAR_NAME,
19
+ RESOURCE_SNS_DEV_TEST_NAME,
20
+ ENTITY_SNS_DEV_TEST_NAME,
21
+ SnsTopicType,
22
+ } from './constants/sns';
23
+ import { AuthorizationAttributesService } from './types/authorization-attributes-service.interface';
24
+ import { EntityType } from './entity-attributes-constants';
25
+ import { ValidationUtils } from './utils/validation';
26
+ import type { TopicAttributesMap } from 'aws-sdk/clients/sns';
27
+
28
+ /**
29
+ * Service class for managing resource attributes asynchronously via SNS.
30
+ * Provides asynchronous operations to create/update and delete attributes on resources.
31
+ */
32
+ export class AuthorizationAttributesSnsService implements AuthorizationAttributesService {
33
+ private static LOG_TAG = 'authorization_attributes';
34
+ private resourceSnsArn: string;
35
+ private entitySnsArn: string;
36
+
37
+ /**
38
+ * Public constructor to create the AuthorizationAttributesSnsService instance.
39
+ */
40
+ constructor() {
41
+ this.resourceSnsArn = AuthorizationAttributesSnsService.getSnsTopicArn(SnsTopicType.RESOURCE);
42
+ this.entitySnsArn = AuthorizationAttributesSnsService.getSnsTopicArn(SnsTopicType.ENTITY);
43
+ }
44
+
45
+ /**
46
+ * Async function to delete a resource attribute using SNS.
47
+ * Sends the delete request to SNS and returns before the change actually took place.
48
+ * @param accountId The account ID
49
+ * @param resource The resource (resourceType, resourceId)
50
+ * @param attributeKey Attribute key to delete
51
+ * @param appName App name of the calling app
52
+ * @param callerActionIdentifier Action identifier
53
+ * @return Promise with sent operation
54
+ */
55
+ async deleteResourceAttributes(
56
+ accountId: number,
57
+ resource: Resource,
58
+ attributeKey: string,
59
+ appName?: string,
60
+ callerActionIdentifier?: string
61
+ ): Promise<ResourceAttributeDeleteOperation> {
62
+ if (!appName || !callerActionIdentifier) {
63
+ throw new Error('appName and callerActionIdentifier are required for SNS service');
64
+ }
65
+ ValidationUtils.validatDeleteResourceAssignment({
66
+ resourceType: resource.type,
67
+ resourceId: resource.id,
68
+ key: attributeKey,
69
+ });
70
+ const operation: ResourceAttributeDeleteOperation = {
71
+ resourceType: resource.type,
72
+ resourceId: resource.id,
73
+ key: attributeKey,
74
+ operationType: AttributeOperation.DELETE,
75
+ };
76
+ const [result] = await this.sendOperationsToSns(
77
+ this.resourceSnsArn,
78
+ accountId,
79
+ appName,
80
+ callerActionIdentifier,
81
+ [operation],
82
+ ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
83
+ RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
84
+ 'Authorization resource attributes async delete: failed to send operations to SNS'
85
+ );
86
+ return result;
87
+ }
88
+
89
+ /**
90
+ * Async function to delete an entity attribute using SNS.
91
+ * Sends the delete request to SNS and returns before the change actually took place.
92
+ * @param accountId The account ID
93
+ * @param entityType The entity type
94
+ * @param entityId The entity ID
95
+ * @param attributeKey Attribute key to delete
96
+ * @param appName App name of the calling app
97
+ * @param callerActionIdentifier Action identifier
98
+ * @return Promise with sent operation
99
+ */
100
+ async deleteEntityAttributes(
101
+ accountId: number,
102
+ entityType: EntityType,
103
+ entityId: number,
104
+ attributeKey: string,
105
+ appName?: string,
106
+ callerActionIdentifier?: string
107
+ ): Promise<EntityAttributeDeleteOperation> {
108
+ if (!appName || !callerActionIdentifier) {
109
+ throw new Error('appName and callerActionIdentifier are required for SNS service');
110
+ }
111
+ ValidationUtils.validatDeleteEntityAssignment({ entityId, entityType, key: attributeKey });
112
+ const operation: EntityAttributeDeleteOperation = {
113
+ entityType: entityType,
114
+ entityId,
115
+ key: attributeKey,
116
+ operationType: AttributeOperation.DELETE,
117
+ };
118
+ const [result] = await this.sendOperationsToSns(
119
+ this.entitySnsArn,
120
+ accountId,
121
+ appName,
122
+ callerActionIdentifier,
123
+ [operation],
124
+ ASYNC_ENTITY_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
125
+ ENTITY_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
126
+ 'Authorization entity attributes async delete: failed to send operations to SNS'
127
+ );
128
+ return result;
129
+ }
130
+
131
+ /**
132
+ * Async function, this function only send the update request to SNS and return before the change actually took place
133
+ * @param accountId
134
+ * @param appName - App name of the calling app
135
+ * @param callerActionIdentifier - action identifier
136
+ * @param resourceAttributeOperation - Operation to do on resource attribute.
137
+ * @return {Promise<ResourceAttributeUpsertOperation>} Sent operation
138
+ * */
139
+ async updateResourceAttributes(
140
+ accountId: number,
141
+ appName: string,
142
+ callerActionIdentifier: string,
143
+ resourceAttributeOperation: ResourceAttributeUpsertOperation
144
+ ): Promise<ResourceAttributeUpsertOperation> {
145
+ ValidationUtils.validatUpsertResourceAssignment(resourceAttributeOperation);
146
+ const [result] = await this.sendOperationsToSns(
147
+ this.resourceSnsArn,
148
+ accountId,
149
+ appName,
150
+ callerActionIdentifier,
151
+ [resourceAttributeOperation],
152
+ ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
153
+ RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
154
+ 'Authorization resource attributes async update: failed to send operations to SNS'
155
+ );
156
+ return result;
157
+ }
158
+
159
+ /**
160
+ * Async function, this function only send the update request to SNS and return before the change actually took place
161
+ * @param accountId
162
+ * @param appName - App name of the calling app
163
+ * @param callerActionIdentifier - action identifier
164
+ * @param entityAttributeOperation - Operation to do on entity attribute.
165
+ * @return {Promise<EntityAttributeUpsertOperation>} Sent operation
166
+ * */
167
+ async updateEntityAttributes(
168
+ accountId: number,
169
+ appName: string,
170
+ callerActionIdentifier: string,
171
+ entityAttributeOperation: EntityAttributeUpsertOperation
172
+ ): Promise<EntityAttributeUpsertOperation> {
173
+ ValidationUtils.validatUpsertEntityAssignment(entityAttributeOperation);
174
+ const [result] = await this.sendOperationsToSns(
175
+ this.entitySnsArn,
176
+ accountId,
177
+ appName,
178
+ callerActionIdentifier,
179
+ [entityAttributeOperation],
180
+ ASYNC_ENTITY_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
181
+ ENTITY_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
182
+ 'Authorization entity attributes async update: failed to send operations to SNS'
183
+ );
184
+ return result;
185
+ }
186
+
187
+ /**
188
+ * Base function to send attribute operations to SNS.
189
+ * Chunks operations and sends them in parallel.
190
+ * @param topicArn The SNS topic ARN to send messages to
191
+ * @param accountId The account ID
192
+ * @param appName App name of the calling app
193
+ * @param callerActionIdentifier Action identifier
194
+ * @param operations Array of operations to send
195
+ * @param chunkSize Maximum number of operations per message
196
+ * @param messageKind The kind of message being sent
197
+ * @param errorLogMessage Error message to log if sending fails
198
+ * @return Promise with array of sent operations
199
+ */
200
+ private async sendOperationsToSns<
201
+ T extends
202
+ | ResourceAttributeUpsertOperation
203
+ | ResourceAttributeDeleteOperation
204
+ | EntityAttributeUpsertOperation
205
+ | EntityAttributeDeleteOperation
206
+ >(
207
+ topicArn: string,
208
+ accountId: number,
209
+ appName: string,
210
+ callerActionIdentifier: string,
211
+ operations: T[],
212
+ chunkSize: number,
213
+ messageKind: string,
214
+ errorLogMessage: string
215
+ ): Promise<T[]> {
216
+ const sendToSnsPromises: Promise<T[]>[] = [];
217
+ const operationChunks = chunk(operations, chunkSize);
218
+ for (const operationsChunk of operationChunks) {
219
+ sendToSnsPromises.push(
220
+ this.sendSingleSnsMessage(
221
+ topicArn,
222
+ accountId,
223
+ appName,
224
+ callerActionIdentifier,
225
+ operationsChunk,
226
+ messageKind,
227
+ errorLogMessage
228
+ )
229
+ );
230
+ }
231
+ return (await Promise.all(sendToSnsPromises)).flat();
232
+ }
233
+
234
+ private async sendSingleSnsMessage<
235
+ T extends
236
+ | ResourceAttributeUpsertOperation
237
+ | ResourceAttributeDeleteOperation
238
+ | EntityAttributeUpsertOperation
239
+ | EntityAttributeDeleteOperation
240
+ >(
241
+ topicArn: string,
242
+ accountId: number,
243
+ appName: string,
244
+ callerActionIdentifier: string,
245
+ operations: T[],
246
+ kind: string,
247
+ errorLogMessage: string
248
+ ): Promise<T[]> {
249
+ const payload = {
250
+ kind,
251
+ payload: {
252
+ accountId: accountId,
253
+ callerAppName: appName,
254
+ callerActionIdentifier: callerActionIdentifier,
255
+ operations: operations,
256
+ },
257
+ };
258
+ try {
259
+ await sendToSns(payload, topicArn);
260
+ return operations;
261
+ } catch (error) {
262
+ logger.error({ error, tag: AuthorizationAttributesSnsService.LOG_TAG }, errorLogMessage);
263
+ return [];
264
+ }
265
+ }
266
+
267
+ private static getSnsTopicArn(type: SnsTopicType): string {
268
+ let envVarName: string;
269
+ let devTestName: string;
270
+
271
+ switch (type) {
272
+ case SnsTopicType.ENTITY:
273
+ envVarName = ENTITY_SNS_ARN_ENV_VAR_NAME;
274
+ devTestName = ENTITY_SNS_DEV_TEST_NAME;
275
+ break;
276
+ default:
277
+ // Default to resource SNS constants
278
+ envVarName = RESOURCE_SNS_ARN_ENV_VAR_NAME;
279
+ devTestName = RESOURCE_SNS_DEV_TEST_NAME;
280
+ break;
281
+ }
282
+
283
+ const arnFromEnv: string | undefined = process.env[envVarName];
284
+ if (arnFromEnv) {
285
+ return arnFromEnv;
286
+ }
287
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
288
+ return devTestName;
289
+ }
290
+ throw new Error(`Unable to get ${type} sns topic arn from env variable`);
291
+ }
292
+
293
+ /**
294
+ * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
295
+ * This function can be used as health check for services that updating resource attributes in async is crucial.
296
+ * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
297
+ * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
298
+ * However, this is the best we can do without actually push dummy messages to the SNS.
299
+ * @return {Promise<boolean>} - true if succeeded
300
+ */
301
+ async asyncResourceAttributesHealthCheck(): Promise<boolean> {
302
+ try {
303
+ const requestedTopicArn: string = this.resourceSnsArn;
304
+ const attributes: TopicAttributesMap = await getTopicAttributes(requestedTopicArn);
305
+ const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
306
+ if (!isHealthy) {
307
+ logger.error(
308
+ { requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesSnsService.LOG_TAG },
309
+ 'authorization-attributes-service failed in health check'
310
+ );
311
+ }
312
+ return isHealthy;
313
+ } catch (error) {
314
+ logger.error(
315
+ { error, tag: AuthorizationAttributesSnsService.LOG_TAG },
316
+ 'authorization-attributes-service got error during health check'
317
+ );
318
+ return false;
319
+ }
320
+ }
321
+ }
@@ -1,5 +1,22 @@
1
- export const SNS_ARN_ENV_VAR_NAME = 'SHARED_AUTHORIZATION_SNS_ENDPOINT_RESOURCE_ATTRIBUTES';
2
- export const SNS_DEV_TEST_NAME =
1
+ export enum SnsTopicType {
2
+ RESOURCE = 'resource',
3
+ ENTITY = 'entity',
4
+ }
5
+
6
+ // Resource SNS constants
7
+ export const RESOURCE_SNS_ARN_ENV_VAR_NAME = 'SHARED_AUTHORIZATION_SNS_ENDPOINT_RESOURCE_ATTRIBUTES';
8
+ export const RESOURCE_SNS_DEV_TEST_NAME =
3
9
  'arn:aws:sns:us-east-1:000000000000:monday-authorization-resource-attributes-sns-local';
10
+
11
+ // Entity SNS constants
12
+ export const ENTITY_SNS_ARN_ENV_VAR_NAME = 'SHARED_AUTHORIZATION_SNS_ENDPOINT_ENTITY_ATTRIBUTES';
13
+ export const ENTITY_SNS_DEV_TEST_NAME =
14
+ 'arn:aws:sns:us-east-1:000000000000:monday-authorization-entity-attributes-sns-local';
4
15
  export const RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND = 'resourceAttributeModification';
16
+ export const ENTITY_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND = 'entityAttributeModification';
5
17
  export const ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE = 100;
18
+ export const ASYNC_ENTITY_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE = 100;
19
+
20
+ // Legacy exports for backward compatibility
21
+ export const SNS_ARN_ENV_VAR_NAME = RESOURCE_SNS_ARN_ENV_VAR_NAME;
22
+ export const SNS_DEV_TEST_NAME = RESOURCE_SNS_DEV_TEST_NAME;
@@ -1,14 +1,12 @@
1
1
  import { EntityType } from './entity-attributes-constants';
2
2
  import { BaseAttributeAssignment } from './base-attribute-assignment';
3
3
  import { EntityAttributeAssignment as EntityAttributeAssignmentContract } from './types/authorization-attributes-contracts';
4
- import { ValidationUtils } from './utils/validation';
5
4
 
6
5
  export class EntityAttributeAssignment extends BaseAttributeAssignment<EntityType, EntityAttributeAssignmentContract> {
7
6
  public readonly entityId: number;
8
7
  public readonly entityType: EntityType;
9
8
 
10
9
  constructor(entityId: number, entityType: EntityType, key: string, value: string) {
11
- ValidationUtils.validateEntityAssignment({ entityId, entityType, key, value });
12
10
  super(entityId, entityType, key, value);
13
11
  this.entityId = entityId;
14
12
  this.entityType = entityType;
package/src/index.ts CHANGED
@@ -58,6 +58,10 @@ export {
58
58
  } from './authorization-middleware';
59
59
  export { AuthorizationService, AuthorizeResponse } from './authorization-service';
60
60
  export { AuthorizationAttributesService } from './authorization-attributes-service';
61
+ export * from './resource-attributes-constants';
62
+ export * from './entity-attributes-constants';
63
+ export { ResourceAttributeAssignment } from './resource-attribute-assignment';
64
+ export { EntityAttributeAssignment } from './entity-attribute-assignment';
61
65
  export { RolesService } from './roles-service';
62
66
  export { MembershipsService } from './memberships';
63
67
  export { AuthorizationObject, Resource, BaseRequest, ResourceGetter, ContextGetter } from './types/general';
@@ -68,5 +72,18 @@ export {
68
72
  ScopedActionPermit,
69
73
  } from './types/scoped-actions-contracts';
70
74
  export { CustomRole, BasicRole, RoleType, RoleCreateRequest, RoleUpdateRequest, RolesResponse } from './types/roles';
75
+ export {
76
+ AttributeAssignment,
77
+ AttributeOperation,
78
+ ResourceAttributeDeleteAssignment,
79
+ ResourceAttributeUpsertOperation,
80
+ ResourceAttributeDeleteOperation,
81
+ EntityAttributeDeleteAssignment,
82
+ EntityAttributeUpsertOperation,
83
+ EntityAttributeDeleteOperation,
84
+ ResourceAttributeAssignment as ResourceAttributeAssignmentContract,
85
+ EntityAttributeAssignment as EntityAttributeAssignmentContract,
86
+ } from './types/authorization-attributes-contracts';
87
+ export { AuthorizationAttributesService as IAuthorizationAttributesService } from './types/authorization-attributes-service.interface';
71
88
 
72
89
  export { TestKit };
@@ -1,7 +1,6 @@
1
1
  import { ResourceType } from './resource-attributes-constants';
2
2
  import { BaseAttributeAssignment } from './base-attribute-assignment';
3
3
  import { ResourceAttributeAssignment as ResourceAttributeAssignmentContract } from './types/authorization-attributes-contracts';
4
- import { ValidationUtils } from './utils/validation';
5
4
 
6
5
  export class ResourceAttributeAssignment extends BaseAttributeAssignment<
7
6
  ResourceType,
@@ -11,7 +10,6 @@ export class ResourceAttributeAssignment extends BaseAttributeAssignment<
11
10
  public readonly resourceType: ResourceType;
12
11
 
13
12
  constructor(resourceId: number, resourceType: ResourceType, attributeKey: string, attributeValue: string) {
14
- ValidationUtils.validateResourceAssignment({ resourceId, resourceType, key: attributeKey, value: attributeValue });
15
13
  super(resourceId, resourceType, attributeKey, attributeValue);
16
14
  this.resourceId = resourceId;
17
15
  this.resourceType = this.type;