@mondaydotcomorg/monday-authorization 3.5.3-feat-shaime-support-entity-attributes-in-authorization-sdk-a77c130 → 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 -8
  15. package/dist/entity-attribute-assignment.d.ts.map +1 -1
  16. package/dist/entity-attribute-assignment.js +5 -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 -8
  36. package/dist/esm/entity-attribute-assignment.d.ts.map +1 -1
  37. package/dist/esm/entity-attribute-assignment.mjs +5 -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 -8
  49. package/dist/esm/resource-attribute-assignment.d.ts.map +1 -1
  50. package/dist/esm/resource-attribute-assignment.mjs +3 -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 -8
  74. package/dist/resource-attribute-assignment.d.ts.map +1 -1
  75. package/dist/resource-attribute-assignment.js +3 -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 +9 -6
  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 +11 -13
  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 -352
  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 -350
  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 -514
  125. package/src/authorization-attributes-sns-service.ts +0 -312
@@ -1,117 +1,62 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
- const zod = require('zod');
3
+ const Ajv = require('ajv');
4
4
  const errors_argumentError = require('../errors/argument-error.js');
5
+ const utils_assigmentSchema = require('./assigment-schema.js');
6
+
7
+ const _interopDefault = e => e && e.__esModule ? e : { default: e };
8
+
9
+ const Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
5
10
 
6
11
  /**
7
- * Utility class for common validation operations using Zod
12
+ * Utility class for common validation operations using AJV
8
13
  */
9
14
  class ValidationUtils {
10
- /**
11
- * Validates that a value is an integer
12
- * @param value The value to validate
13
- * @param fieldName The name of the field for error messages
14
- * @throws ArgumentError if value is not an integer
15
- */
16
- static validateInteger(value, fieldName) {
17
- const schema = zod.z.number().int();
18
- try {
19
- schema.parse(value);
20
- }
21
- catch (error) {
22
- if (error instanceof zod.z.ZodError) {
23
- throw new errors_argumentError.ArgumentError(`${fieldName} must be an integer, got: ${value}`);
24
- }
25
- throw error;
15
+ static ajv = new Ajv__default.default({ allErrors: true });
16
+ static integerValidator = this.ajv.compile({ type: 'number', multipleOf: 1 });
17
+ static stringValidator = this.ajv.compile({ type: 'string', minLength: 1 });
18
+ static stringArrayValidator = this.ajv.compile({
19
+ type: 'array',
20
+ items: { type: 'string' },
21
+ });
22
+ static validateInteger(value) {
23
+ const valid = this.integerValidator(value);
24
+ if (!valid) {
25
+ throw new errors_argumentError.ArgumentError('Invalid integer');
26
26
  }
27
27
  }
28
- /**
29
- * Validates that a value is a non-empty string
30
- * @param value The value to validate
31
- * @param fieldName The name of the field for error messages
32
- * @throws ArgumentError if value is not a string or is empty
33
- */
34
- static validateString(value, fieldName) {
35
- const schema = zod.z.string().min(1);
36
- try {
37
- schema.parse(value);
38
- }
39
- catch (error) {
40
- if (error instanceof zod.z.ZodError) {
41
- if (typeof value !== 'string') {
42
- throw new errors_argumentError.ArgumentError(`${fieldName} must be a string, got: ${typeof value}`);
43
- }
44
- throw new errors_argumentError.ArgumentError(`${fieldName} must be a non-empty string`);
45
- }
46
- throw error;
28
+ static validateString(value) {
29
+ const valid = this.stringValidator(value);
30
+ if (!valid) {
31
+ throw new errors_argumentError.ArgumentError('Invalid string');
47
32
  }
48
33
  }
49
- /**
50
- * Validates that a value is an array and optionally checks minimum length
51
- * @param value The value to validate
52
- * @param fieldName The name of the field for error messages
53
- * @param minLength Minimum required length (default: 0)
54
- * @returns The validated array
55
- * @throws ArgumentError if value is not an array or doesn't meet minimum length
56
- */
57
- static validateArray(value, fieldName, minLength = 0) {
58
- const schema = zod.z.array(zod.z.any()).min(minLength);
59
- try {
60
- return schema.parse(value);
61
- }
62
- catch (error) {
63
- if (error instanceof zod.z.ZodError) {
64
- if (!Array.isArray(value)) {
65
- throw new errors_argumentError.ArgumentError(`${fieldName} must be an array`);
66
- }
67
- throw new errors_argumentError.ArgumentError(`${fieldName} must have at least ${minLength} items`);
68
- }
69
- throw error;
34
+ static validateStringArray(value) {
35
+ const valid = this.stringArrayValidator(value);
36
+ if (!valid) {
37
+ throw new errors_argumentError.ArgumentError('Invalid string array');
70
38
  }
71
39
  }
72
40
  /**
73
- * Validates that a value is one of the allowed enum values
74
- * @param value The value to validate
75
- * @param validValues Array of valid values
76
- * @param fieldName The name of the field for error messages
77
- * @returns The validated value as the enum type
78
- * @throws ArgumentError if value is not in validValues
41
+ * Validates an attribute assignment object using a single AJV schema.
42
+ * Preserves legacy error messages for each field.
79
43
  */
80
- static validateEnum(value, validValues, fieldName) {
81
- const schema = zod.z.enum(validValues);
82
- try {
83
- return schema.parse(value);
84
- }
85
- catch (error) {
86
- if (error instanceof zod.z.ZodError) {
87
- throw new errors_argumentError.ArgumentError(`${fieldName} must be one of [${validValues.join(', ')}], got: ${value}`);
88
- }
89
- throw error;
44
+ static validateResourceAssignment(resource) {
45
+ const valid = utils_assigmentSchema.resourceAssignmentSchema(resource);
46
+ if (!valid) {
47
+ const errorMessages = (utils_assigmentSchema.resourceAssignmentSchema.errors || [])
48
+ .map(err => err.message || 'validation failed')
49
+ .join(', ');
50
+ throw new errors_argumentError.ArgumentError(`Invalid resource attribute assignment: ${errorMessages}`);
90
51
  }
91
52
  }
92
- /**
93
- * Validates that all items in an array are strings
94
- * @param value Array to validate
95
- * @param fieldName The name of the field for error messages
96
- * @throws ArgumentError if any item is not a string
97
- */
98
- static validateStringArray(value, fieldName) {
99
- const schema = zod.z.array(zod.z.string());
100
- try {
101
- schema.parse(value);
102
- }
103
- catch (error) {
104
- if (error instanceof zod.z.ZodError) {
105
- const zodError = error;
106
- const firstError = zodError.issues[0];
107
- // Check if it's an array item validation error
108
- if (firstError.path.length > 0 && typeof firstError.path[0] === 'number') {
109
- const index = firstError.path[0];
110
- throw new errors_argumentError.ArgumentError(`All ${fieldName} must be strings, but item at index ${index} is not`);
111
- }
112
- throw new errors_argumentError.ArgumentError(`${fieldName} must be an array`);
113
- }
114
- throw error;
53
+ static validateEntityAssignment(entity) {
54
+ const valid = utils_assigmentSchema.entityAssignmentSchema(entity);
55
+ if (!valid) {
56
+ const errorMessages = (utils_assigmentSchema.entityAssignmentSchema.errors || [])
57
+ .map(err => err.message || 'validation failed')
58
+ .join(', ');
59
+ throw new errors_argumentError.ArgumentError(`Invalid entity attribute assignment: ${errorMessages}`);
115
60
  }
116
61
  }
117
62
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mondaydotcomorg/monday-authorization",
3
- "version": "3.5.3-feat-shaime-support-entity-attributes-in-authorization-sdk-a77c130",
3
+ "version": "3.6.0-feat-shaime-support-entity-attributes-1-4c8e283",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "BSD-3-Clause",
@@ -28,11 +28,11 @@
28
28
  "@mondaydotcomorg/monday-observability-kit": "^1.5.3",
29
29
  "@mondaydotcomorg/monday-sns": "^1.2.1",
30
30
  "@mondaydotcomorg/trident-backend-api": "^0.24.3",
31
+ "ajv": "^8.12.0",
31
32
  "lodash": "^4.17.21",
32
33
  "node-fetch": "^2.6.7",
33
34
  "on-headers": "^1.0.2",
34
- "ts-node": "^10.0.0",
35
- "zod": "^4.1.13"
35
+ "ts-node": "^10.0.0"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@mondaydotcomorg/trident-library": "^1.1.44",
@@ -1,47 +1,235 @@
1
- import { AuthorizationAttributesMsService } from './authorization-attributes-ms-service';
2
- import { AuthorizationAttributesSnsService } from './authorization-attributes-sns-service';
3
- import { IAuthorizationAttributesService } from './types/authorization-attributes-service.interface';
4
-
5
- /**
6
- * Main service class for managing resource and entity attributes.
7
- * Provides access to both direct (MS) and SNS operations.
8
- *
9
- * @example
10
- * ```typescript
11
- * const service = new AuthorizationAttributesService();
12
- *
13
- * // Use direct operations
14
- * await service.direct().upsertResourceAttributes(accountId, assignments);
15
- *
16
- * // Use SNS operations
17
- * await service.sns().upsertResourceAttributes(accountId, assignments, appName, actionId);
18
- * ```
19
- */
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
+
20
22
  export class AuthorizationAttributesService {
21
- private _directService: AuthorizationAttributesMsService | null = null;
22
- private _snsService: AuthorizationAttributesSnsService | null = null;
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
+ console.log(1);
39
+ if (!httpClient) {
40
+ httpClient = Api.getPart('httpClient');
41
+ if (!httpClient) {
42
+ throw new Error(ERROR_MESSAGES.HTTP_CLIENT_NOT_INITIALIZED);
43
+ }
44
+ }
45
+
46
+ if (!fetchOptions) {
47
+ fetchOptions = DEFAULT_FETCH_OPTIONS;
48
+ } else {
49
+ fetchOptions = {
50
+ ...DEFAULT_FETCH_OPTIONS,
51
+ ...fetchOptions,
52
+ };
53
+ }
54
+ this.httpClient = httpClient;
55
+ this.fetchOptions = fetchOptions;
56
+ this.snsArn = AuthorizationAttributesService.getSnsTopicArn();
57
+ }
58
+
59
+ /**
60
+ * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
61
+ * @param accountId
62
+ * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
63
+ * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
64
+ * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
65
+ */
66
+ async upsertResourceAttributes(
67
+ accountId: number,
68
+ resourceAttributeAssignments: ResourceAttributeAssignment[]
69
+ ): Promise<ResourceAttributeResponse> {
70
+ const attributionHeaders = getAttributionsFromApi();
71
+ try {
72
+ return await this.httpClient.fetch<ResourceAttributeResponse>(
73
+ {
74
+ url: {
75
+ appName: APP_NAME,
76
+ path: AuthorizationAttributesService.API_PATHS.UPSERT_RESOURCE_ATTRIBUTES.replace(
77
+ '{accountId}',
78
+ accountId.toString()
79
+ ),
80
+ },
81
+ method: 'POST',
82
+ headers: {
83
+ 'Content-Type': 'application/json',
84
+ ...attributionHeaders,
85
+ },
86
+ body: JSON.stringify({ resourceAttributeAssignments }),
87
+ },
88
+ this.fetchOptions
89
+ );
90
+ } catch (err) {
91
+ if (err instanceof HttpFetcherError) {
92
+ throw new Error(ERROR_MESSAGES.REQUEST_FAILED('upsertResourceAttributes', err.status, err.message));
93
+ }
94
+ throw err;
95
+ }
96
+ }
23
97
 
24
98
  /**
25
- * Gets the direct (MS) service instance.
26
- * Initializes the service on first access (lazy initialization).
27
- * @returns IAuthorizationAttributesService instance
99
+ * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
100
+ * @param accountId
101
+ * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
102
+ * @param attributeKeys - Array of attribute keys to delete for the resource.
103
+ * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
28
104
  */
29
- direct(): IAuthorizationAttributesService {
30
- if (this._directService === null) {
31
- this._directService = new AuthorizationAttributesMsService();
105
+ async deleteResourceAttributes(
106
+ accountId: number,
107
+ resource: Resource,
108
+ attributeKeys: string[]
109
+ ): Promise<ResourceAttributeResponse> {
110
+ const attributionHeaders = getAttributionsFromApi();
111
+ if (!resource.id) {
112
+ throw new Error('Resource ID is required');
113
+ }
114
+ try {
115
+ return await this.httpClient.fetch<ResourceAttributeResponse>(
116
+ {
117
+ url: {
118
+ appName: APP_NAME,
119
+ path: AuthorizationAttributesService.API_PATHS.DELETE_RESOURCE_ATTRIBUTES.replace(
120
+ '{accountId}',
121
+ accountId.toString()
122
+ )
123
+ .replace('{resourceType}', resource.type)
124
+ .replace('{resourceId}', resource.id.toString()),
125
+ },
126
+ method: 'DELETE',
127
+ headers: {
128
+ 'Content-Type': 'application/json',
129
+ ...attributionHeaders,
130
+ },
131
+ body: JSON.stringify({ keys: attributeKeys }),
132
+ },
133
+ this.fetchOptions
134
+ );
135
+ } catch (err) {
136
+ if (err instanceof HttpFetcherError) {
137
+ throw new Error(ERROR_MESSAGES.REQUEST_FAILED('deleteResourceAttributes', err.status, err.message));
138
+ }
139
+ throw err;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Async function, this function only send the updates request to SNS and return before the change actually took place
145
+ * @param accountId
146
+ * @param appName - App name of the calling app
147
+ * @param callerActionIdentifier - action identifier
148
+ * @param resourceAttributeOperations - Array of operations to do on resource attributes.
149
+ * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
150
+ * */
151
+ async updateResourceAttributesAsync(
152
+ accountId: number,
153
+ appName: string,
154
+ callerActionIdentifier: string,
155
+ resourceAttributeOperations: ResourceAttributeUpsertOperation[]
156
+ ): Promise<ResourceAttributeUpsertOperation[]> {
157
+ const topicArn: string = this.snsArn;
158
+ const sendToSnsPromises: Promise<ResourceAttributeAssignment[]>[] = [];
159
+ const operationChucks = chunk(resourceAttributeOperations, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
160
+ for (const operationsChunk of operationChucks) {
161
+ sendToSnsPromises.push(
162
+ this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk)
163
+ );
164
+ }
165
+ return (await Promise.all(sendToSnsPromises)).flat() as ResourceAttributeUpsertOperation[];
166
+ }
167
+
168
+ private async sendSingleSnsMessage(
169
+ topicArn: string,
170
+ accountId: number,
171
+ appName: string,
172
+ callerActionIdentifier: string,
173
+ operations: ResourceAttributeAssignment[]
174
+ ): Promise<ResourceAttributeAssignment[]> {
175
+ const payload = {
176
+ kind: RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
177
+ payload: {
178
+ accountId: accountId,
179
+ callerAppName: appName,
180
+ callerActionIdentifier: callerActionIdentifier,
181
+ operations: operations,
182
+ },
183
+ };
184
+ try {
185
+ await sendToSns(payload, topicArn);
186
+ return operations;
187
+ } catch (error) {
188
+ logger.error(
189
+ { error, tag: AuthorizationAttributesService.LOG_TAG },
190
+ 'Authorization resource attributes async update: failed to send operations to SNS'
191
+ );
192
+ return [];
193
+ }
194
+ }
195
+
196
+ private static getSnsTopicArn(): string {
197
+ const arnFromEnv: string | undefined = process.env[SNS_ARN_ENV_VAR_NAME];
198
+ if (arnFromEnv) {
199
+ return arnFromEnv;
200
+ }
201
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
202
+ return SNS_DEV_TEST_NAME;
32
203
  }
33
- return this._directService;
204
+ throw new Error('Unable to get sns topic arn from env variable');
34
205
  }
35
206
 
36
207
  /**
37
- * Gets the SNS service instance.
38
- * Initializes the service on first access (lazy initialization).
39
- * @returns IAuthorizationAttributesService instance
208
+ * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
209
+ * This function can be used as health check for services that updating resource attributes in async is crucial.
210
+ * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
211
+ * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
212
+ * However, this is the best we can do without actually push dummy messages to the SNS.
213
+ * @return {Promise<boolean>} - true if succeeded
40
214
  */
41
- sns(): IAuthorizationAttributesService {
42
- if (this._snsService === null) {
43
- this._snsService = new AuthorizationAttributesSnsService();
215
+ async asyncResourceAttributesHealthCheck(): Promise<boolean> {
216
+ try {
217
+ const requestedTopicArn: string = this.snsArn;
218
+ const attributes: TopicAttributesMap = await getTopicAttributes(requestedTopicArn);
219
+ const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
220
+ if (!isHealthy) {
221
+ logger.error(
222
+ { requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesService.LOG_TAG },
223
+ 'authorization-attributes-service failed in health check'
224
+ );
225
+ }
226
+ return isHealthy;
227
+ } catch (error) {
228
+ logger.error(
229
+ { error, tag: AuthorizationAttributesService.LOG_TAG },
230
+ 'authorization-attributes-service got error during health check'
231
+ );
232
+ return false;
44
233
  }
45
- return this._snsService;
46
234
  }
47
235
  }
@@ -1,13 +1,13 @@
1
1
  import onHeaders from 'on-headers';
2
2
  import { AuthorizationInternalService } from './authorization-internal-service';
3
3
  import { AuthorizationService, createAuthorizationParams } from './authorization-service';
4
- import { BaseRequest, BaseResponse, Context, ContextGetter, ResourceGetter } from './types/general';
4
+ import { Action, BaseRequest, BaseResponse, Context, ContextGetter, ResourceGetter } from './types/general';
5
5
  import type { NextFunction } from 'express';
6
6
 
7
7
  // getAuthorizationMiddleware is duplicated in testKit/index.ts
8
8
  // If you are making changes to this function, please make sure to update the other file as well
9
9
  export function getAuthorizationMiddleware(
10
- action: string,
10
+ action: Action,
11
11
  resourceGetter: ResourceGetter,
12
12
  contextGetter?: ContextGetter
13
13
  ) {
@@ -3,7 +3,7 @@ import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
3
3
  import { Api } from '@mondaydotcomorg/trident-backend-api';
4
4
  import { HttpFetcherError } from '@mondaydotcomorg/monday-fetch-api';
5
5
  import { getIgniteClient, IgniteClient } from '@mondaydotcomorg/ignite-sdk';
6
- import { AuthorizationObject, AuthorizationParams, Resource } from './types/general';
6
+ import { Action, AuthorizationObject, AuthorizationParams, Resource } from './types/general';
7
7
  import { sendAuthorizationCheckResponseTimeMetric } from './prometheus-service';
8
8
  import { recordAuthorizationTiming } from './metrics-service';
9
9
  import {
@@ -74,7 +74,7 @@ export class AuthorizationService {
74
74
  accountId: number,
75
75
  userId: number,
76
76
  resources: Resource[],
77
- action: string
77
+ action: Action
78
78
  ): Promise<AuthorizeResponse>;
79
79
 
80
80
  static async isAuthorized(
@@ -223,7 +223,7 @@ export class AuthorizationService {
223
223
  accountId: number,
224
224
  userId: number,
225
225
  resources: Resource[],
226
- action: string
226
+ action: Action
227
227
  ): Promise<AuthorizeResponse> {
228
228
  const { authorizationObjects } = createAuthorizationParams(resources, action);
229
229
  return this.isAuthorizedMultiple(accountId, userId, authorizationObjects);
@@ -338,7 +338,7 @@ export async function setIgniteClient() {
338
338
  AuthorizationInternalService.setIgniteClient(igniteClient);
339
339
  }
340
340
 
341
- export function createAuthorizationParams(resources: Resource[], action: string): AuthorizationParams {
341
+ export function createAuthorizationParams(resources: Resource[], action: Action): AuthorizationParams {
342
342
  const params = {
343
343
  authorizationObjects: resources.map((resource: Resource) => {
344
344
  const authorizationObject: AuthorizationObject = {
@@ -1,37 +1,18 @@
1
- import { ValidationUtils } from './utils/validation';
1
+ import isEqual from 'lodash/isEqual.js';
2
2
 
3
3
  /**
4
4
  * Base class for attribute assignments (Resource or Entity)
5
5
  * Provides common validation and functionality
6
6
  */
7
- export abstract class BaseAttributeAssignment<TId extends number, TType extends string> {
8
- public readonly id: TId;
9
- public readonly type: TType;
7
+ export abstract class BaseAttributeAssignment<T, R> {
8
+ public readonly id: number;
9
+ public readonly type: T;
10
10
  public readonly attributeKey: string;
11
11
  public readonly attributeValue: string;
12
12
 
13
- constructor(
14
- id: TId,
15
- type: string,
16
- attributeKey: string,
17
- attributeValue: string,
18
- validTypes: readonly string[],
19
- idFieldName: string,
20
- typeFieldName: string
21
- ) {
22
- // Validate id
23
- ValidationUtils.validateInteger(id, idFieldName);
24
-
25
- // Validate type
26
- this.type = ValidationUtils.validateEnum(type, validTypes as readonly TType[], typeFieldName) as TType;
27
-
28
- // Validate attributeKey
29
- ValidationUtils.validateString(attributeKey, 'attributeKey');
30
-
31
- // Validate attributeValue
32
- ValidationUtils.validateString(attributeValue, 'attributeValue');
33
-
13
+ constructor(id: number, type: T, attributeKey: string, attributeValue: string) {
34
14
  this.id = id;
15
+ this.type = type;
35
16
  this.attributeKey = attributeKey;
36
17
  this.attributeValue = attributeValue;
37
18
  }
@@ -41,15 +22,9 @@ export abstract class BaseAttributeAssignment<TId extends number, TType extends
41
22
  * @param other Another assignment instance
42
23
  * @returns true if all properties are equal
43
24
  */
44
- equals(other: BaseAttributeAssignment<TId, TType>): boolean {
45
- if (!(other instanceof this.constructor)) {
46
- return false;
47
- }
48
- return (
49
- this.id === other.id &&
50
- this.type === other.type &&
51
- this.attributeKey === other.attributeKey &&
52
- this.attributeValue === other.attributeValue
53
- );
25
+ equals(other: BaseAttributeAssignment<T, R>): boolean {
26
+ return isEqual(this, other);
54
27
  }
28
+
29
+ abstract toDataTransferObject(): R;
55
30
  }
@@ -1,22 +1,5 @@
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 =
1
+ export const SNS_ARN_ENV_VAR_NAME = 'SHARED_AUTHORIZATION_SNS_ENDPOINT_RESOURCE_ATTRIBUTES';
2
+ export const SNS_DEV_TEST_NAME =
9
3
  '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';
15
4
  export const RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND = 'resourceAttributeModification';
16
- export const ENTITY_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND = 'entityAttributeModification';
17
5
  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,17 +1,20 @@
1
- import { ENTITY_TYPES, EntityType } from './entity-attributes-constants';
1
+ import { EntityType } from './entity-attributes-constants';
2
2
  import { BaseAttributeAssignment } from './base-attribute-assignment';
3
+ import { EntityAttributeAssignment as EntityAttributeAssignmentContract } from './types/authorization-attributes-contracts';
4
+ import { ValidationUtils } from './utils/validation';
3
5
 
4
- export class EntityAttributeAssignment extends BaseAttributeAssignment<number, EntityType> {
6
+ export class EntityAttributeAssignment extends BaseAttributeAssignment<EntityType, EntityAttributeAssignmentContract> {
5
7
  public readonly entityId: number;
6
8
  public readonly entityType: EntityType;
7
9
 
8
- constructor(entityId: number, entityType: string, attributeKey: string, attributeValue: string) {
9
- super(entityId, entityType, attributeKey, attributeValue, Object.values(ENTITY_TYPES), 'entityId', 'entityType');
10
+ constructor(entityId: number, entityType: EntityType, key: string, value: string) {
11
+ ValidationUtils.validateEntityAssignment({ entityId, entityType, key, value });
12
+ super(entityId, entityType, key, value);
10
13
  this.entityId = entityId;
11
- this.entityType = this.type;
14
+ this.entityType = entityType;
12
15
  }
13
16
 
14
- toDataTransferObject() {
17
+ toDataTransferObject(): EntityAttributeAssignmentContract {
15
18
  return {
16
19
  entityId: this.entityId,
17
20
  entityType: this.entityType,
@@ -1,7 +1,7 @@
1
- export const ENTITY_TYPES = {
2
- USER: 'user',
3
- TEAM: 'team',
4
- ACCOUNT: 'account',
5
- } as const;
1
+ export enum EntityType {
2
+ User = 'user',
3
+ Team = 'team',
4
+ Account = 'account',
5
+ }
6
6
 
7
- export type EntityType = (typeof ENTITY_TYPES)[keyof typeof ENTITY_TYPES];
7
+ export const ENTITY_TYPES = Object.freeze(Object.values(EntityType));
@@ -2,6 +2,5 @@ export class ArgumentError extends Error {
2
2
  constructor(message: string) {
3
3
  super(message);
4
4
  this.name = 'ArgumentError';
5
- Object.setPrototypeOf(this, ArgumentError.prototype);
6
5
  }
7
6
  }