@mondaydotcomorg/monday-authorization 2.1.1-feature-bashanye-export-fetcher-configuration.e5d71eb → 2.1.1-feature-bashanye-remove-authorization-url-secret-usage.226e096

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.
@@ -1,25 +1,35 @@
1
+ import { FetcherConfig, HttpClient } from '@mondaydotcomorg/trident-backend-api';
1
2
  import { ResourceAttributeAssignment, ResourceAttributeResponse, ResourceAttributesOperation } from './types/authorization-attributes-contracts';
2
3
  import { Resource } from './types/general';
4
+ import { RecursivePartial } from '@mondaydotcomorg/monday-fetch-api';
3
5
  export declare class AuthorizationAttributesService {
4
6
  private static LOG_TAG;
7
+ private static API_PATHS;
8
+ private httpClient;
9
+ private fetchOptions;
10
+ private snsArn;
11
+ /**
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.
15
+ */
16
+ constructor(httpClient?: HttpClient, fetchOptions?: RecursivePartial<FetcherConfig>);
5
17
  /**
6
18
  * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
7
19
  * @param accountId
8
- * @param userId
9
20
  * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
10
21
  * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
11
22
  * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
12
23
  */
13
- static upsertResourceAttributes(accountId: number, userId: number, resourceAttributeAssignments: ResourceAttributeAssignment[]): Promise<ResourceAttributeResponse>;
24
+ upsertResourceAttributes(accountId: number, resourceAttributeAssignments: ResourceAttributeAssignment[]): Promise<ResourceAttributeResponse>;
14
25
  /**
15
26
  * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
16
27
  * @param accountId
17
- * @param userId
18
28
  * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
19
29
  * @param attributeKeys - Array of attribute keys to delete for the resource.
20
30
  * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
21
31
  */
22
- static deleteResourceAttributes(accountId: number, userId: number, resource: Resource, attributeKeys: string[]): Promise<ResourceAttributeResponse>;
32
+ deleteResourceAttributes(accountId: number, resource: Resource, attributeKeys: string[]): Promise<ResourceAttributeResponse>;
23
33
  /**
24
34
  * Async function, this function only send the updates request to SNS and return before the change actually took place
25
35
  * @param accountId
@@ -28,10 +38,9 @@ export declare class AuthorizationAttributesService {
28
38
  * @param resourceAttributeOperations - Array of operations to do on resource attributes.
29
39
  * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
30
40
  * */
31
- static updateResourceAttributesAsync(accountId: number, appName: string, callerActionIdentifier: string, resourceAttributeOperations: ResourceAttributesOperation[]): Promise<ResourceAttributesOperation[]>;
32
- private static sendSingleSnsMessage;
41
+ updateResourceAttributesAsync(accountId: number, appName: string, callerActionIdentifier: string, resourceAttributeOperations: ResourceAttributesOperation[]): Promise<ResourceAttributesOperation[]>;
42
+ private sendSingleSnsMessage;
33
43
  private static getSnsTopicArn;
34
- private static getResourceAttributesUrl;
35
44
  /**
36
45
  * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
37
46
  * This function can be used as health check for services that updating resource attributes in async is crucial.
@@ -40,6 +49,6 @@ export declare class AuthorizationAttributesService {
40
49
  * However, this is the best we can do without actually push dummy messages to the SNS.
41
50
  * @return {Promise<boolean>} - true if succeeded
42
51
  */
43
- static asyncResourceAttributesHealthCheck(): Promise<boolean>;
52
+ asyncResourceAttributesHealthCheck(): Promise<boolean>;
44
53
  }
45
54
  //# 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":"AAIA,OAAO,EACL,2BAA2B,EAC3B,yBAAyB,EACzB,2BAA2B,EAC5B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAU3C,qBAAa,8BAA8B;IACzC,OAAO,CAAC,MAAM,CAAC,OAAO,CAA8B;IACpD;;;;;;;OAOG;WACU,wBAAwB,CACnC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,4BAA4B,EAAE,2BAA2B,EAAE,GAC1D,OAAO,CAAC,yBAAyB,CAAC;IAwBrC;;;;;;;OAOG;WACU,wBAAwB,CACnC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,MAAM,EAAE,GACtB,OAAO,CAAC,yBAAyB,CAAC;IAyBrC;;;;;;;UAOM;WACO,6BAA6B,CACxC,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,sBAAsB,EAAE,MAAM,EAC9B,2BAA2B,EAAE,2BAA2B,EAAE,GACzD,OAAO,CAAC,2BAA2B,EAAE,CAAC;mBAYpB,oBAAoB;IA4BzC,OAAO,CAAC,MAAM,CAAC,cAAc;IAe7B,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAIvC;;;;;;;OAOG;WACU,kCAAkC,IAAI,OAAO,CAAC,OAAO,CAAC;CAiBpE"}
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,EACL,2BAA2B,EAC3B,yBAAyB,EACzB,2BAA2B,EAC5B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAU3C,OAAO,EAAoB,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAgBvF,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;IA2BrC;;;;;;OAMG;IACG,wBAAwB,CAC5B,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,MAAM,EAAE,GACtB,OAAO,CAAC,yBAAyB,CAAC;IA2BrC;;;;;;;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;IAe7B;;;;;;;OAOG;IACG,kCAAkC,IAAI,OAAO,CAAC,OAAO,CAAC;CAiB7D"}
@@ -1,69 +1,124 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  const chunk = require('lodash/chunk.js');
4
- const mondayFetch = require('@mondaydotcomorg/monday-fetch');
5
4
  const tridentBackendApi = require('@mondaydotcomorg/trident-backend-api');
6
5
  const mondaySns = require('@mondaydotcomorg/monday-sns');
7
6
  const authorizationInternalService = require('./authorization-internal-service.js');
8
7
  const attributionsService = require('./attributions-service.js');
9
8
  const constants_sns = require('./constants/sns.js');
9
+ const constants = require('./constants.js');
10
+ const mondayFetchApi = require('@mondaydotcomorg/monday-fetch-api');
10
11
 
11
12
  const _interopDefault = e => e && e.__esModule ? e : { default: e };
12
13
 
13
14
  const chunk__default = /*#__PURE__*/_interopDefault(chunk);
14
15
 
16
+ function getDefaultFetchOptions() {
17
+ return {
18
+ retryPolicy: {
19
+ useRetries: true,
20
+ maxRetries: 3,
21
+ retryDelayMS: 10,
22
+ },
23
+ logPolicy: {
24
+ logErrors: 'error',
25
+ logRequests: 'info',
26
+ }
27
+ };
28
+ }
15
29
  class AuthorizationAttributesService {
16
30
  static LOG_TAG = 'authorization_attributes';
31
+ static API_PATHS = {
32
+ UPSERT_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource',
33
+ DELETE_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource/{resourceType}/{resourceId}',
34
+ };
35
+ httpClient;
36
+ fetchOptions;
37
+ snsArn;
38
+ /**
39
+ * Public constructor to create the AuthorizationAttributesService instance.
40
+ * @param httpClient The HTTP client to use for API requests, if not provided, the default HTTP client from Api will be used.
41
+ * @param fetchOptions The fetch options to use for API requests, if not provided, the default fetch options will be used.
42
+ */
43
+ constructor(httpClient, fetchOptions) {
44
+ if (!httpClient) {
45
+ httpClient = tridentBackendApi.Api.getPart('httpClient');
46
+ if (!httpClient) {
47
+ throw new Error(constants.ERROR_MESSAGES.HTTP_CLIENT_NOT_INITIALIZED);
48
+ }
49
+ }
50
+ if (!fetchOptions) {
51
+ fetchOptions = getDefaultFetchOptions();
52
+ }
53
+ else {
54
+ fetchOptions = {
55
+ ...getDefaultFetchOptions(),
56
+ ...fetchOptions,
57
+ };
58
+ }
59
+ this.httpClient = httpClient;
60
+ this.fetchOptions = fetchOptions;
61
+ this.snsArn = AuthorizationAttributesService.getSnsTopicArn();
62
+ }
17
63
  /**
18
64
  * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
19
65
  * @param accountId
20
- * @param userId
21
66
  * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
22
67
  * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
23
68
  * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
24
69
  */
25
- static async upsertResourceAttributes(accountId, userId, resourceAttributeAssignments) {
26
- const internalAuthToken = authorizationInternalService.AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
70
+ async upsertResourceAttributes(accountId, resourceAttributeAssignments) {
27
71
  const attributionHeaders = attributionsService.getAttributionsFromApi();
28
- const response = await mondayFetch.fetch(this.getResourceAttributesUrl(accountId), {
29
- method: 'POST',
30
- headers: {
31
- Authorization: internalAuthToken,
32
- 'Content-Type': 'application/json',
33
- ...attributionHeaders,
34
- },
35
- timeout: authorizationInternalService.AuthorizationInternalService.getRequestTimeout(),
36
- body: JSON.stringify({ resourceAttributeAssignments }),
37
- }, authorizationInternalService.AuthorizationInternalService.getRequestFetchOptions());
38
- const responseBody = await response.json();
39
- authorizationInternalService.AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'upsertResourceAttributesSync');
40
- return { attributes: responseBody['attributes'] };
72
+ try {
73
+ return await this.httpClient.fetch({
74
+ url: {
75
+ appName: constants.APP_NAME,
76
+ path: AuthorizationAttributesService.API_PATHS.UPSERT_RESOURCE_ATTRIBUTES.replace('{accountId}', accountId.toString()),
77
+ },
78
+ method: 'POST',
79
+ headers: {
80
+ 'Content-Type': 'application/json',
81
+ ...attributionHeaders,
82
+ },
83
+ body: JSON.stringify({ resourceAttributeAssignments }),
84
+ }, this.fetchOptions);
85
+ }
86
+ catch (err) {
87
+ if (err instanceof mondayFetchApi.HttpFetcherError) {
88
+ throw new Error(constants.ERROR_MESSAGES.REQUEST_FAILED('upsertResourceAttributes', err.status, err.message));
89
+ }
90
+ throw err;
91
+ }
41
92
  }
42
93
  /**
43
94
  * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
44
95
  * @param accountId
45
- * @param userId
46
96
  * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
47
97
  * @param attributeKeys - Array of attribute keys to delete for the resource.
48
98
  * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
49
99
  */
50
- static async deleteResourceAttributes(accountId, userId, resource, attributeKeys) {
51
- const internalAuthToken = authorizationInternalService.AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
52
- const url = `${this.getResourceAttributesUrl(accountId)}/${resource.type}/${resource.id}`;
100
+ async deleteResourceAttributes(accountId, resource, attributeKeys) {
53
101
  const attributionHeaders = attributionsService.getAttributionsFromApi();
54
- const response = await mondayFetch.fetch(url, {
55
- method: 'DELETE',
56
- headers: {
57
- Authorization: internalAuthToken,
58
- 'Content-Type': 'application/json',
59
- ...attributionHeaders,
60
- },
61
- timeout: authorizationInternalService.AuthorizationInternalService.getRequestTimeout(),
62
- body: JSON.stringify({ keys: attributeKeys }),
63
- }, authorizationInternalService.AuthorizationInternalService.getRequestFetchOptions());
64
- const responseBody = await response.json();
65
- authorizationInternalService.AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'deleteResourceAttributesSync');
66
- return { attributes: responseBody['attributes'] };
102
+ try {
103
+ return await this.httpClient.fetch({
104
+ url: {
105
+ appName: constants.APP_NAME,
106
+ path: AuthorizationAttributesService.API_PATHS.DELETE_RESOURCE_ATTRIBUTES.replace('{accountId}', accountId.toString()).replace('{resourceType}', resource.type).replace('{resourceId}', resource.id.toString()),
107
+ },
108
+ method: 'DELETE',
109
+ headers: {
110
+ 'Content-Type': 'application/json',
111
+ ...attributionHeaders,
112
+ },
113
+ body: JSON.stringify({ keys: attributeKeys }),
114
+ }, this.fetchOptions);
115
+ }
116
+ catch (err) {
117
+ if (err instanceof mondayFetchApi.HttpFetcherError) {
118
+ throw new Error(constants.ERROR_MESSAGES.REQUEST_FAILED('deleteResourceAttributes', err.status, err.message));
119
+ }
120
+ throw err;
121
+ }
67
122
  }
68
123
  /**
69
124
  * Async function, this function only send the updates request to SNS and return before the change actually took place
@@ -73,8 +128,8 @@ class AuthorizationAttributesService {
73
128
  * @param resourceAttributeOperations - Array of operations to do on resource attributes.
74
129
  * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
75
130
  * */
76
- static async updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations) {
77
- const topicArn = this.getSnsTopicArn();
131
+ async updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations) {
132
+ const topicArn = this.snsArn;
78
133
  const sendToSnsPromises = [];
79
134
  const operationChucks = chunk__default.default(resourceAttributeOperations, constants_sns.ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
80
135
  for (const operationsChunk of operationChucks) {
@@ -82,7 +137,7 @@ class AuthorizationAttributesService {
82
137
  }
83
138
  return (await Promise.all(sendToSnsPromises)).flat();
84
139
  }
85
- static async sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operations) {
140
+ async sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operations) {
86
141
  const payload = {
87
142
  kind: constants_sns.RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
88
143
  payload: {
@@ -97,7 +152,7 @@ class AuthorizationAttributesService {
97
152
  return operations;
98
153
  }
99
154
  catch (error) {
100
- authorizationInternalService.logger.error({ error, tag: this.LOG_TAG }, 'Authorization resource attributes async update: failed to send operations to SNS');
155
+ authorizationInternalService.logger.error({ error, tag: AuthorizationAttributesService.LOG_TAG }, 'Authorization resource attributes async update: failed to send operations to SNS');
101
156
  return [];
102
157
  }
103
158
  }
@@ -113,9 +168,6 @@ class AuthorizationAttributesService {
113
168
  }
114
169
  throw new Error('Unable to get sns topic arn from env variable');
115
170
  }
116
- static getResourceAttributesUrl(accountId) {
117
- return `${process.env.AUTHORIZATION_URL}/attributes/${accountId}/resource`;
118
- }
119
171
  /**
120
172
  * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
121
173
  * This function can be used as health check for services that updating resource attributes in async is crucial.
@@ -124,18 +176,18 @@ class AuthorizationAttributesService {
124
176
  * However, this is the best we can do without actually push dummy messages to the SNS.
125
177
  * @return {Promise<boolean>} - true if succeeded
126
178
  */
127
- static async asyncResourceAttributesHealthCheck() {
179
+ async asyncResourceAttributesHealthCheck() {
128
180
  try {
129
- const requestedTopicArn = this.getSnsTopicArn();
181
+ const requestedTopicArn = this.snsArn;
130
182
  const attributes = await mondaySns.getTopicAttributes(requestedTopicArn);
131
183
  const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
132
184
  if (!isHealthy) {
133
- authorizationInternalService.logger.error({ requestedTopicArn, snsReturnedAttributes: attributes, tag: this.LOG_TAG }, 'authorization-attributes-service failed in health check');
185
+ authorizationInternalService.logger.error({ requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesService.LOG_TAG }, 'authorization-attributes-service failed in health check');
134
186
  }
135
187
  return isHealthy;
136
188
  }
137
189
  catch (error) {
138
- authorizationInternalService.logger.error({ error, tag: this.LOG_TAG }, 'authorization-attributes-service got error during health check');
190
+ authorizationInternalService.logger.error({ error, tag: AuthorizationAttributesService.LOG_TAG }, 'authorization-attributes-service got error during health check');
139
191
  return false;
140
192
  }
141
193
  }
@@ -0,0 +1,6 @@
1
+ export declare const APP_NAME = "authorization";
2
+ export declare const ERROR_MESSAGES: {
3
+ readonly HTTP_CLIENT_NOT_INITIALIZED: "MondayAuthorization: HTTP client is not initialized";
4
+ readonly REQUEST_FAILED: (method: string, status: number, reason: string) => string;
5
+ };
6
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,QAAQ,kBAAkB,CAAC;AAExC,eAAO,MAAM,cAAc;;sCAEA,MAAM,UAAU,MAAM,UAAU,MAAM;CAEvD,CAAC"}
@@ -0,0 +1,10 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const APP_NAME = 'authorization';
4
+ const ERROR_MESSAGES = {
5
+ HTTP_CLIENT_NOT_INITIALIZED: 'MondayAuthorization: HTTP client is not initialized',
6
+ REQUEST_FAILED: (method, status, reason) => `MondayAuthorization: [${method}] request failed with status ${status} with reason: ${reason}`,
7
+ };
8
+
9
+ exports.APP_NAME = APP_NAME;
10
+ exports.ERROR_MESSAGES = ERROR_MESSAGES;
@@ -1,25 +1,35 @@
1
+ import { FetcherConfig, HttpClient } from '@mondaydotcomorg/trident-backend-api';
1
2
  import { ResourceAttributeAssignment, ResourceAttributeResponse, ResourceAttributesOperation } from './types/authorization-attributes-contracts';
2
3
  import { Resource } from './types/general';
4
+ import { RecursivePartial } from '@mondaydotcomorg/monday-fetch-api';
3
5
  export declare class AuthorizationAttributesService {
4
6
  private static LOG_TAG;
7
+ private static API_PATHS;
8
+ private httpClient;
9
+ private fetchOptions;
10
+ private snsArn;
11
+ /**
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.
15
+ */
16
+ constructor(httpClient?: HttpClient, fetchOptions?: RecursivePartial<FetcherConfig>);
5
17
  /**
6
18
  * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
7
19
  * @param accountId
8
- * @param userId
9
20
  * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
10
21
  * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
11
22
  * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
12
23
  */
13
- static upsertResourceAttributes(accountId: number, userId: number, resourceAttributeAssignments: ResourceAttributeAssignment[]): Promise<ResourceAttributeResponse>;
24
+ upsertResourceAttributes(accountId: number, resourceAttributeAssignments: ResourceAttributeAssignment[]): Promise<ResourceAttributeResponse>;
14
25
  /**
15
26
  * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
16
27
  * @param accountId
17
- * @param userId
18
28
  * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
19
29
  * @param attributeKeys - Array of attribute keys to delete for the resource.
20
30
  * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
21
31
  */
22
- static deleteResourceAttributes(accountId: number, userId: number, resource: Resource, attributeKeys: string[]): Promise<ResourceAttributeResponse>;
32
+ deleteResourceAttributes(accountId: number, resource: Resource, attributeKeys: string[]): Promise<ResourceAttributeResponse>;
23
33
  /**
24
34
  * Async function, this function only send the updates request to SNS and return before the change actually took place
25
35
  * @param accountId
@@ -28,10 +38,9 @@ export declare class AuthorizationAttributesService {
28
38
  * @param resourceAttributeOperations - Array of operations to do on resource attributes.
29
39
  * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
30
40
  * */
31
- static updateResourceAttributesAsync(accountId: number, appName: string, callerActionIdentifier: string, resourceAttributeOperations: ResourceAttributesOperation[]): Promise<ResourceAttributesOperation[]>;
32
- private static sendSingleSnsMessage;
41
+ updateResourceAttributesAsync(accountId: number, appName: string, callerActionIdentifier: string, resourceAttributeOperations: ResourceAttributesOperation[]): Promise<ResourceAttributesOperation[]>;
42
+ private sendSingleSnsMessage;
33
43
  private static getSnsTopicArn;
34
- private static getResourceAttributesUrl;
35
44
  /**
36
45
  * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
37
46
  * This function can be used as health check for services that updating resource attributes in async is crucial.
@@ -40,6 +49,6 @@ export declare class AuthorizationAttributesService {
40
49
  * However, this is the best we can do without actually push dummy messages to the SNS.
41
50
  * @return {Promise<boolean>} - true if succeeded
42
51
  */
43
- static asyncResourceAttributesHealthCheck(): Promise<boolean>;
52
+ asyncResourceAttributesHealthCheck(): Promise<boolean>;
44
53
  }
45
54
  //# 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":"AAIA,OAAO,EACL,2BAA2B,EAC3B,yBAAyB,EACzB,2BAA2B,EAC5B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAU3C,qBAAa,8BAA8B;IACzC,OAAO,CAAC,MAAM,CAAC,OAAO,CAA8B;IACpD;;;;;;;OAOG;WACU,wBAAwB,CACnC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,4BAA4B,EAAE,2BAA2B,EAAE,GAC1D,OAAO,CAAC,yBAAyB,CAAC;IAwBrC;;;;;;;OAOG;WACU,wBAAwB,CACnC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,MAAM,EAAE,GACtB,OAAO,CAAC,yBAAyB,CAAC;IAyBrC;;;;;;;UAOM;WACO,6BAA6B,CACxC,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,sBAAsB,EAAE,MAAM,EAC9B,2BAA2B,EAAE,2BAA2B,EAAE,GACzD,OAAO,CAAC,2BAA2B,EAAE,CAAC;mBAYpB,oBAAoB;IA4BzC,OAAO,CAAC,MAAM,CAAC,cAAc;IAe7B,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAIvC;;;;;;;OAOG;WACU,kCAAkC,IAAI,OAAO,CAAC,OAAO,CAAC;CAiBpE"}
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,EACL,2BAA2B,EAC3B,yBAAyB,EACzB,2BAA2B,EAC5B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAU3C,OAAO,EAAoB,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAgBvF,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;IA2BrC;;;;;;OAMG;IACG,wBAAwB,CAC5B,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,MAAM,EAAE,GACtB,OAAO,CAAC,yBAAyB,CAAC;IA2BrC;;;;;;;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;IAe7B;;;;;;;OAOG;IACG,kCAAkC,IAAI,OAAO,CAAC,OAAO,CAAC;CAiB7D"}
@@ -1,63 +1,118 @@
1
1
  import chunk from 'lodash/chunk.js';
2
- import { fetch } from '@mondaydotcomorg/monday-fetch';
3
2
  import { Api } from '@mondaydotcomorg/trident-backend-api';
4
3
  import { sendToSns, getTopicAttributes } from '@mondaydotcomorg/monday-sns';
5
- import { AuthorizationInternalService, logger } from './authorization-internal-service.mjs';
4
+ import { logger } from './authorization-internal-service.mjs';
6
5
  import { getAttributionsFromApi } from './attributions-service.mjs';
7
6
  import { ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE, RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME, RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND } from './constants/sns.mjs';
7
+ import { ERROR_MESSAGES, APP_NAME } from './constants.mjs';
8
+ import { HttpFetcherError } from '@mondaydotcomorg/monday-fetch-api';
8
9
 
10
+ function getDefaultFetchOptions() {
11
+ return {
12
+ retryPolicy: {
13
+ useRetries: true,
14
+ maxRetries: 3,
15
+ retryDelayMS: 10,
16
+ },
17
+ logPolicy: {
18
+ logErrors: 'error',
19
+ logRequests: 'info',
20
+ }
21
+ };
22
+ }
9
23
  class AuthorizationAttributesService {
10
24
  static LOG_TAG = 'authorization_attributes';
25
+ static API_PATHS = {
26
+ UPSERT_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource',
27
+ DELETE_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource/{resourceType}/{resourceId}',
28
+ };
29
+ httpClient;
30
+ fetchOptions;
31
+ snsArn;
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, fetchOptions) {
38
+ if (!httpClient) {
39
+ httpClient = Api.getPart('httpClient');
40
+ if (!httpClient) {
41
+ throw new Error(ERROR_MESSAGES.HTTP_CLIENT_NOT_INITIALIZED);
42
+ }
43
+ }
44
+ if (!fetchOptions) {
45
+ fetchOptions = getDefaultFetchOptions();
46
+ }
47
+ else {
48
+ fetchOptions = {
49
+ ...getDefaultFetchOptions(),
50
+ ...fetchOptions,
51
+ };
52
+ }
53
+ this.httpClient = httpClient;
54
+ this.fetchOptions = fetchOptions;
55
+ this.snsArn = AuthorizationAttributesService.getSnsTopicArn();
56
+ }
11
57
  /**
12
58
  * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
13
59
  * @param accountId
14
- * @param userId
15
60
  * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
16
61
  * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
17
62
  * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
18
63
  */
19
- static async upsertResourceAttributes(accountId, userId, resourceAttributeAssignments) {
20
- const internalAuthToken = AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
64
+ async upsertResourceAttributes(accountId, resourceAttributeAssignments) {
21
65
  const attributionHeaders = getAttributionsFromApi();
22
- const response = await fetch(this.getResourceAttributesUrl(accountId), {
23
- method: 'POST',
24
- headers: {
25
- Authorization: internalAuthToken,
26
- 'Content-Type': 'application/json',
27
- ...attributionHeaders,
28
- },
29
- timeout: AuthorizationInternalService.getRequestTimeout(),
30
- body: JSON.stringify({ resourceAttributeAssignments }),
31
- }, AuthorizationInternalService.getRequestFetchOptions());
32
- const responseBody = await response.json();
33
- AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'upsertResourceAttributesSync');
34
- return { attributes: responseBody['attributes'] };
66
+ try {
67
+ return await this.httpClient.fetch({
68
+ url: {
69
+ appName: APP_NAME,
70
+ path: AuthorizationAttributesService.API_PATHS.UPSERT_RESOURCE_ATTRIBUTES.replace('{accountId}', accountId.toString()),
71
+ },
72
+ method: 'POST',
73
+ headers: {
74
+ 'Content-Type': 'application/json',
75
+ ...attributionHeaders,
76
+ },
77
+ body: JSON.stringify({ resourceAttributeAssignments }),
78
+ }, this.fetchOptions);
79
+ }
80
+ catch (err) {
81
+ if (err instanceof HttpFetcherError) {
82
+ throw new Error(ERROR_MESSAGES.REQUEST_FAILED('upsertResourceAttributes', err.status, err.message));
83
+ }
84
+ throw err;
85
+ }
35
86
  }
36
87
  /**
37
88
  * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
38
89
  * @param accountId
39
- * @param userId
40
90
  * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
41
91
  * @param attributeKeys - Array of attribute keys to delete for the resource.
42
92
  * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
43
93
  */
44
- static async deleteResourceAttributes(accountId, userId, resource, attributeKeys) {
45
- const internalAuthToken = AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
46
- const url = `${this.getResourceAttributesUrl(accountId)}/${resource.type}/${resource.id}`;
94
+ async deleteResourceAttributes(accountId, resource, attributeKeys) {
47
95
  const attributionHeaders = getAttributionsFromApi();
48
- const response = await fetch(url, {
49
- method: 'DELETE',
50
- headers: {
51
- Authorization: internalAuthToken,
52
- 'Content-Type': 'application/json',
53
- ...attributionHeaders,
54
- },
55
- timeout: AuthorizationInternalService.getRequestTimeout(),
56
- body: JSON.stringify({ keys: attributeKeys }),
57
- }, AuthorizationInternalService.getRequestFetchOptions());
58
- const responseBody = await response.json();
59
- AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'deleteResourceAttributesSync');
60
- return { attributes: responseBody['attributes'] };
96
+ try {
97
+ return await this.httpClient.fetch({
98
+ url: {
99
+ appName: APP_NAME,
100
+ path: AuthorizationAttributesService.API_PATHS.DELETE_RESOURCE_ATTRIBUTES.replace('{accountId}', accountId.toString()).replace('{resourceType}', resource.type).replace('{resourceId}', resource.id.toString()),
101
+ },
102
+ method: 'DELETE',
103
+ headers: {
104
+ 'Content-Type': 'application/json',
105
+ ...attributionHeaders,
106
+ },
107
+ body: JSON.stringify({ keys: attributeKeys }),
108
+ }, this.fetchOptions);
109
+ }
110
+ catch (err) {
111
+ if (err instanceof HttpFetcherError) {
112
+ throw new Error(ERROR_MESSAGES.REQUEST_FAILED('deleteResourceAttributes', err.status, err.message));
113
+ }
114
+ throw err;
115
+ }
61
116
  }
62
117
  /**
63
118
  * Async function, this function only send the updates request to SNS and return before the change actually took place
@@ -67,8 +122,8 @@ class AuthorizationAttributesService {
67
122
  * @param resourceAttributeOperations - Array of operations to do on resource attributes.
68
123
  * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
69
124
  * */
70
- static async updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations) {
71
- const topicArn = this.getSnsTopicArn();
125
+ async updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations) {
126
+ const topicArn = this.snsArn;
72
127
  const sendToSnsPromises = [];
73
128
  const operationChucks = chunk(resourceAttributeOperations, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
74
129
  for (const operationsChunk of operationChucks) {
@@ -76,7 +131,7 @@ class AuthorizationAttributesService {
76
131
  }
77
132
  return (await Promise.all(sendToSnsPromises)).flat();
78
133
  }
79
- static async sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operations) {
134
+ async sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operations) {
80
135
  const payload = {
81
136
  kind: RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
82
137
  payload: {
@@ -91,7 +146,7 @@ class AuthorizationAttributesService {
91
146
  return operations;
92
147
  }
93
148
  catch (error) {
94
- logger.error({ error, tag: this.LOG_TAG }, 'Authorization resource attributes async update: failed to send operations to SNS');
149
+ logger.error({ error, tag: AuthorizationAttributesService.LOG_TAG }, 'Authorization resource attributes async update: failed to send operations to SNS');
95
150
  return [];
96
151
  }
97
152
  }
@@ -107,9 +162,6 @@ class AuthorizationAttributesService {
107
162
  }
108
163
  throw new Error('Unable to get sns topic arn from env variable');
109
164
  }
110
- static getResourceAttributesUrl(accountId) {
111
- return `${process.env.AUTHORIZATION_URL}/attributes/${accountId}/resource`;
112
- }
113
165
  /**
114
166
  * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
115
167
  * This function can be used as health check for services that updating resource attributes in async is crucial.
@@ -118,18 +170,18 @@ class AuthorizationAttributesService {
118
170
  * However, this is the best we can do without actually push dummy messages to the SNS.
119
171
  * @return {Promise<boolean>} - true if succeeded
120
172
  */
121
- static async asyncResourceAttributesHealthCheck() {
173
+ async asyncResourceAttributesHealthCheck() {
122
174
  try {
123
- const requestedTopicArn = this.getSnsTopicArn();
175
+ const requestedTopicArn = this.snsArn;
124
176
  const attributes = await getTopicAttributes(requestedTopicArn);
125
177
  const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
126
178
  if (!isHealthy) {
127
- logger.error({ requestedTopicArn, snsReturnedAttributes: attributes, tag: this.LOG_TAG }, 'authorization-attributes-service failed in health check');
179
+ logger.error({ requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesService.LOG_TAG }, 'authorization-attributes-service failed in health check');
128
180
  }
129
181
  return isHealthy;
130
182
  }
131
183
  catch (error) {
132
- logger.error({ error, tag: this.LOG_TAG }, 'authorization-attributes-service got error during health check');
184
+ logger.error({ error, tag: AuthorizationAttributesService.LOG_TAG }, 'authorization-attributes-service got error during health check');
133
185
  return false;
134
186
  }
135
187
  }
@@ -0,0 +1,6 @@
1
+ export declare const APP_NAME = "authorization";
2
+ export declare const ERROR_MESSAGES: {
3
+ readonly HTTP_CLIENT_NOT_INITIALIZED: "MondayAuthorization: HTTP client is not initialized";
4
+ readonly REQUEST_FAILED: (method: string, status: number, reason: string) => string;
5
+ };
6
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,QAAQ,kBAAkB,CAAC;AAExC,eAAO,MAAM,cAAc;;sCAEA,MAAM,UAAU,MAAM,UAAU,MAAM;CAEvD,CAAC"}
@@ -0,0 +1,7 @@
1
+ const APP_NAME = 'authorization';
2
+ const ERROR_MESSAGES = {
3
+ HTTP_CLIENT_NOT_INITIALIZED: 'MondayAuthorization: HTTP client is not initialized',
4
+ REQUEST_FAILED: (method, status, reason) => `MondayAuthorization: [${method}] request failed with status ${status} with reason: ${reason}`,
5
+ };
6
+
7
+ export { APP_NAME, ERROR_MESSAGES };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mondaydotcomorg/monday-authorization",
3
- "version": "2.1.1-feature-bashanye-export-fetcher-configuration.e5d71eb",
3
+ "version": "2.1.1-feature-bashanye-remove-authorization-url-secret-usage.226e096",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "BSD-3-Clause",