@mondaydotcomorg/monday-authorization 1.2.10 → 1.2.12
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.
- package/README.md +25 -0
- package/dist/{lib/attributions-service.js → attributions-service.js} +11 -10
- package/dist/authorization-attributes-service.js +144 -0
- package/dist/{lib/authorization-internal-service.d.ts → authorization-internal-service.d.ts} +1 -1
- package/dist/authorization-internal-service.js +80 -0
- package/dist/{lib/authorization-middleware.d.ts → authorization-middleware.d.ts} +1 -1
- package/dist/authorization-middleware.js +48 -0
- package/dist/authorization-service.js +176 -0
- package/dist/constants/sns.js +9 -0
- package/dist/esm/attributions-service.d.ts +3 -0
- package/dist/esm/attributions-service.mjs +53 -0
- package/dist/esm/authorization-attributes-service.d.ts +44 -0
- package/dist/esm/authorization-attributes-service.mjs +138 -0
- package/dist/esm/authorization-internal-service.d.ts +13 -0
- package/dist/esm/authorization-internal-service.mjs +57 -0
- package/dist/esm/authorization-middleware.d.ts +6 -0
- package/dist/esm/authorization-middleware.mjs +39 -0
- package/dist/esm/authorization-service.d.ts +29 -0
- package/dist/esm/authorization-service.mjs +172 -0
- package/dist/esm/constants/sns.d.ts +3 -0
- package/dist/esm/constants/sns.mjs +5 -0
- package/dist/esm/index.d.ts +13 -0
- package/dist/esm/index.mjs +21 -0
- package/dist/esm/prometheus-service.mjs +49 -0
- package/dist/{lib → esm}/testKit/index.d.ts +2 -2
- package/dist/esm/testKit/index.mjs +44 -0
- package/dist/esm/types/authorization-attributes-contracts.mjs +7 -0
- package/dist/esm/types/express.mjs +1 -0
- package/dist/{lib → esm}/types/general.d.ts +6 -4
- package/dist/esm/types/general.mjs +1 -0
- package/dist/esm/types/scoped-actions-contracts.mjs +8 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +19 -43
- package/dist/prometheus-service.d.ts +10 -0
- package/dist/{lib/prometheus-service.js → prometheus-service.js} +18 -14
- package/dist/testKit/index.d.ts +11 -0
- package/dist/testKit/index.js +48 -0
- package/dist/types/authorization-attributes-contracts.d.ts +27 -0
- package/dist/types/authorization-attributes-contracts.js +7 -0
- package/dist/types/express.d.ts +10 -0
- package/dist/types/express.js +1 -0
- package/dist/types/general.d.ts +32 -0
- package/dist/types/general.js +1 -0
- package/dist/types/scoped-actions-contracts.d.ts +38 -0
- package/dist/{lib/types → types}/scoped-actions-contracts.js +3 -5
- package/package.json +25 -28
- package/dist/index.js.map +0 -1
- package/dist/lib/attributions-service.js.map +0 -1
- package/dist/lib/authorization-attributes-service.js +0 -155
- package/dist/lib/authorization-attributes-service.js.map +0 -1
- package/dist/lib/authorization-internal-service.js +0 -79
- package/dist/lib/authorization-internal-service.js.map +0 -1
- package/dist/lib/authorization-middleware.js +0 -57
- package/dist/lib/authorization-middleware.js.map +0 -1
- package/dist/lib/authorization-service.js +0 -186
- package/dist/lib/authorization-service.js.map +0 -1
- package/dist/lib/constants/sns.js +0 -7
- package/dist/lib/constants/sns.js.map +0 -1
- package/dist/lib/prometheus-service.js.map +0 -1
- package/dist/lib/testKit/index.js +0 -59
- package/dist/lib/testKit/index.js.map +0 -1
- package/dist/lib/types/authorization-attributes-contracts.js +0 -9
- package/dist/lib/types/authorization-attributes-contracts.js.map +0 -1
- package/dist/lib/types/express.js +0 -2
- package/dist/lib/types/express.js.map +0 -1
- package/dist/lib/types/general.js +0 -3
- package/dist/lib/types/general.js.map +0 -1
- package/dist/lib/types/scoped-actions-contracts.js.map +0 -1
- package/dist/tsconfig.tsbuildinfo +0 -1
- package/dist/{lib/attributions-service.d.ts → attributions-service.d.ts} +0 -0
- package/dist/{lib/authorization-attributes-service.d.ts → authorization-attributes-service.d.ts} +0 -0
- package/dist/{lib/authorization-service.d.ts → authorization-service.d.ts} +1 -1
- /package/dist/{lib/constants → constants}/sns.d.ts +0 -0
- /package/dist/{lib → esm}/prometheus-service.d.ts +0 -0
- /package/dist/{lib → esm}/types/authorization-attributes-contracts.d.ts +0 -0
- /package/dist/{lib → esm}/types/express.d.ts +0 -0
- /package/dist/{lib → esm}/types/scoped-actions-contracts.d.ts +0 -0
package/README.md
CHANGED
|
@@ -138,7 +138,10 @@ const canActionInScopeMultipleResponse: ScopedActionResponseObject[] =
|
|
|
138
138
|
```
|
|
139
139
|
|
|
140
140
|
### Authorization Attributes API
|
|
141
|
+
Authorization attributes have 2 options to get called: sync (http request) and async (send to SNS and consumed asynchronously).
|
|
142
|
+
When you have to make sure the change in the attributes applied before the function return, please use the sync method, otherwise use the async
|
|
141
143
|
|
|
144
|
+
#### Sync method
|
|
142
145
|
Use `AuthorizationAttributesService.upsertResourceAttributesSync` to upsert multiple resource attributes in the authorization MS synchronously.
|
|
143
146
|
|
|
144
147
|
```ts
|
|
@@ -168,3 +171,25 @@ const attributeKeys: string[] = ['is_default_workspace', 'workspace_kind'];
|
|
|
168
171
|
const response: ResourceAttributeResponse = await AuthorizationAttributesService.deleteResourceAttributesSync(accountId, userId, resource, attributeKeys);
|
|
169
172
|
```
|
|
170
173
|
|
|
174
|
+
#### Async method
|
|
175
|
+
use `AuthorizationAttributesService.updateResourceAttributesAsync` to upsert or delete multiple resource attributes at once.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { AuthorizationAttributesService, ResourceAttributeAssignment, ResourceAttributeResponse } from '@mondaydotcomorg/monday-authorization';
|
|
179
|
+
|
|
180
|
+
const accountId = 739630;
|
|
181
|
+
const appName = process.env.APP_NAME;
|
|
182
|
+
const callerActionIdentifier = "actions_v2";
|
|
183
|
+
const resourceAttributeOperations: ResourceAttributesOperation[] = [
|
|
184
|
+
{ operationType: 'upsert', resourceId: 18, resourceType: 'workspace', key: 'is_default_workspace', value: 'true' },
|
|
185
|
+
{ operationType: 'delete', resourceId: 23, resourceType: 'board', key: 'board_kind' }
|
|
186
|
+
];
|
|
187
|
+
|
|
188
|
+
const response: ResourceAttributeResponse = await AuthorizationAttributesService.updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations);
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Special notes for asynchronous operations:
|
|
192
|
+
1. There is no guarantee about the order of the updates, so don't do multiple operations on the same key in the same resource.
|
|
193
|
+
2. To update an existing key, just use upsert operation, it'll override previous value.
|
|
194
|
+
3. Requests with a lot of operations might split to chunks that will be consumed either sequence or in parallel, so there might be a timeframe where some of the operations already applied and some not. Eventually all of them will be applied.
|
|
195
|
+
4. If your MS depends on the access to the asynchronous operation, you can use a health check operation `asyncResourceAttributesHealthCheck` that will return false if it can't reach to SNS or can't find the required topic. Note it doesn't check write permissions so make sure your MS have permissions to write to the SNS topic.
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
const
|
|
5
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const tridentBackendApi = require('@mondaydotcomorg/trident-backend-api');
|
|
4
|
+
const authorizationInternalService = require('./authorization-internal-service.js');
|
|
5
|
+
|
|
6
6
|
const APP_NAME_VARIABLE_KEY = 'APP_NAME';
|
|
7
7
|
const APP_NAME_HEADER_NAME = 'x-caller-app-name-from-sdk';
|
|
8
8
|
const FROM_SDK_HEADER_SUFFIX = `-from-sdk`;
|
|
9
9
|
let didSendFailureLogOnce = false;
|
|
10
10
|
function getAttributionsFromApi() {
|
|
11
|
-
|
|
11
|
+
const callerAppNameFromSdk = {
|
|
12
12
|
[APP_NAME_HEADER_NAME]: tryJsonParse(getEnvVariable(APP_NAME_VARIABLE_KEY)),
|
|
13
13
|
};
|
|
14
14
|
try {
|
|
15
|
-
const tridentContext =
|
|
15
|
+
const tridentContext = tridentBackendApi.Api.getPart('context');
|
|
16
16
|
if (!tridentContext) {
|
|
17
17
|
return callerAppNameFromSdk;
|
|
18
18
|
}
|
|
19
19
|
const { runtimeAttributions } = tridentContext;
|
|
20
|
-
|
|
20
|
+
const runtimeAttributionsOutgoingHeaders = runtimeAttributions?.buildOutgoingHeaders('HTTP_INTERNAL');
|
|
21
21
|
if (!runtimeAttributionsOutgoingHeaders) {
|
|
22
22
|
return callerAppNameFromSdk;
|
|
23
23
|
}
|
|
@@ -30,7 +30,7 @@ function getAttributionsFromApi() {
|
|
|
30
30
|
}
|
|
31
31
|
catch (error) {
|
|
32
32
|
if (!didSendFailureLogOnce) {
|
|
33
|
-
|
|
33
|
+
authorizationInternalService.logger.warn({ tag: 'authorization-service', error }, 'Failed to generate attributions headers from the API. Unexpected error while extracting headers. It may be caused by out of date Trident version.');
|
|
34
34
|
didSendFailureLogOnce = true;
|
|
35
35
|
}
|
|
36
36
|
return callerAppNameFromSdk;
|
|
@@ -51,4 +51,5 @@ function tryJsonParse(value) {
|
|
|
51
51
|
return value;
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
|
-
|
|
54
|
+
|
|
55
|
+
exports.getAttributionsFromApi = getAttributionsFromApi;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const chunk = require('lodash/chunk');
|
|
4
|
+
const mondayFetch = require('@mondaydotcomorg/monday-fetch');
|
|
5
|
+
const tridentBackendApi = require('@mondaydotcomorg/trident-backend-api');
|
|
6
|
+
const mondaySns = require('@mondaydotcomorg/monday-sns');
|
|
7
|
+
const authorizationInternalService = require('./authorization-internal-service.js');
|
|
8
|
+
const attributionsService = require('./attributions-service.js');
|
|
9
|
+
const constants_sns = require('./constants/sns.js');
|
|
10
|
+
|
|
11
|
+
const _interopDefault = e => e && e.__esModule ? e : { default: e };
|
|
12
|
+
|
|
13
|
+
const chunk__default = /*#__PURE__*/_interopDefault(chunk);
|
|
14
|
+
|
|
15
|
+
class AuthorizationAttributesService {
|
|
16
|
+
static LOG_TAG = 'authorization_attributes';
|
|
17
|
+
/**
|
|
18
|
+
* Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
|
|
19
|
+
* @param accountId
|
|
20
|
+
* @param userId
|
|
21
|
+
* @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
|
|
22
|
+
* e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
|
|
23
|
+
* @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
|
|
24
|
+
*/
|
|
25
|
+
static async upsertResourceAttributes(accountId, userId, resourceAttributeAssignments) {
|
|
26
|
+
const internalAuthToken = authorizationInternalService.AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
|
|
27
|
+
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'] };
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
|
|
44
|
+
* @param accountId
|
|
45
|
+
* @param userId
|
|
46
|
+
* @param resource - The resource (resourceType, resourceId) to delete the attributes for.
|
|
47
|
+
* @param attributeKeys - Array of attribute keys to delete for the resource.
|
|
48
|
+
* @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
|
|
49
|
+
*/
|
|
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}`;
|
|
53
|
+
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'] };
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Async function, this function only send the updates request to SNS and return before the change actually took place
|
|
70
|
+
* @param accountId
|
|
71
|
+
* @param appName - App name of the calling app
|
|
72
|
+
* @param callerActionIdentifier - action identifier
|
|
73
|
+
* @param resourceAttributeOperations - Array of operations to do on resource attributes.
|
|
74
|
+
* @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
|
|
75
|
+
* */
|
|
76
|
+
static async updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations) {
|
|
77
|
+
const topicArn = this.getSnsTopicArn();
|
|
78
|
+
const sendToSnsPromises = [];
|
|
79
|
+
const operationChucks = chunk__default.default(resourceAttributeOperations, constants_sns.ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
|
|
80
|
+
for (const operationsChunk of operationChucks) {
|
|
81
|
+
sendToSnsPromises.push(this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk));
|
|
82
|
+
}
|
|
83
|
+
return (await Promise.all(sendToSnsPromises)).flat();
|
|
84
|
+
}
|
|
85
|
+
static async sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operations) {
|
|
86
|
+
const payload = {
|
|
87
|
+
kind: constants_sns.RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
|
|
88
|
+
payload: {
|
|
89
|
+
accountId: accountId,
|
|
90
|
+
callerAppName: appName,
|
|
91
|
+
callerActionIdentifier: callerActionIdentifier,
|
|
92
|
+
operations: operations,
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
try {
|
|
96
|
+
await mondaySns.sendToSns(payload, topicArn);
|
|
97
|
+
return operations;
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
authorizationInternalService.logger.error({ error, tag: this.LOG_TAG }, 'Authorization resource attributes async update: failed to send operations to SNS');
|
|
101
|
+
return [];
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
static getSnsTopicArn() {
|
|
105
|
+
const arnFromApi = tridentBackendApi.Api.getPart('configurationVariables')?.get(constants_sns.RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME).arn;
|
|
106
|
+
if (arnFromApi) {
|
|
107
|
+
return arnFromApi;
|
|
108
|
+
}
|
|
109
|
+
const jsonArnFromEnv = process.env[constants_sns.RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME];
|
|
110
|
+
const arnFromEnv = JSON.parse(jsonArnFromEnv).arn;
|
|
111
|
+
if (arnFromEnv) {
|
|
112
|
+
return arnFromEnv;
|
|
113
|
+
}
|
|
114
|
+
throw new Error('Unable to get sns topic arn from env variable');
|
|
115
|
+
}
|
|
116
|
+
static getResourceAttributesUrl(accountId) {
|
|
117
|
+
return `${process.env.AUTHORIZATION_URL}/attributes/${accountId}/resource`;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
|
|
121
|
+
* This function can be used as health check for services that updating resource attributes in async is crucial.
|
|
122
|
+
* Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
|
|
123
|
+
* errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
|
|
124
|
+
* However, this is the best we can do without actually push dummy messages to the SNS.
|
|
125
|
+
* @return {Promise<boolean>} - true if succeeded
|
|
126
|
+
*/
|
|
127
|
+
static async asyncResourceAttributesHealthCheck() {
|
|
128
|
+
try {
|
|
129
|
+
const requestedTopicArn = this.getSnsTopicArn();
|
|
130
|
+
const attributes = await mondaySns.getTopicAttributes(requestedTopicArn);
|
|
131
|
+
const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
|
|
132
|
+
if (!isHealthy) {
|
|
133
|
+
authorizationInternalService.logger.error({ requestedTopicArn, snsReturnedAttributes: attributes, tag: this.LOG_TAG }, 'authorization-attributes-service failed in health check');
|
|
134
|
+
}
|
|
135
|
+
return isHealthy;
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
authorizationInternalService.logger.error({ error, tag: this.LOG_TAG }, 'authorization-attributes-service got error during health check');
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
exports.AuthorizationAttributesService = AuthorizationAttributesService;
|
package/dist/{lib/authorization-internal-service.d.ts → authorization-internal-service.d.ts}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Request } from 'express';
|
|
2
1
|
import { fetch, MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
|
|
2
|
+
import type { Request } from 'express';
|
|
3
3
|
export declare const logger: import("bunyan");
|
|
4
4
|
export declare class AuthorizationInternalService {
|
|
5
5
|
static skipAuthorization(requset: Request): void;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const mondayJwt = require('@mondaydotcomorg/monday-jwt');
|
|
4
|
+
const MondayLogger = require('@mondaydotcomorg/monday-logger');
|
|
5
|
+
|
|
6
|
+
function _interopNamespace(e) {
|
|
7
|
+
if (e && e.__esModule) return e;
|
|
8
|
+
const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
|
|
9
|
+
if (e) {
|
|
10
|
+
for (const k in e) {
|
|
11
|
+
if (k !== 'default') {
|
|
12
|
+
const d = Object.getOwnPropertyDescriptor(e, k);
|
|
13
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
get: () => e[k]
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
n.default = e;
|
|
21
|
+
return n;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const MondayLogger__namespace = /*#__PURE__*/_interopNamespace(MondayLogger);
|
|
25
|
+
|
|
26
|
+
const INTERNAL_APP_NAME = 'internal_ms';
|
|
27
|
+
const defaultMondayFetchOptions = {
|
|
28
|
+
retries: 3,
|
|
29
|
+
callback: logOnFetchFail,
|
|
30
|
+
};
|
|
31
|
+
const logger = MondayLogger__namespace.getLogger();
|
|
32
|
+
function logOnFetchFail(retriesLeft, error) {
|
|
33
|
+
if (retriesLeft == 0) {
|
|
34
|
+
logger.error({ retriesLeft, error }, 'Authorization attempt failed due to network issues');
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
logger.info({ retriesLeft, error }, 'Authorization attempt failed due to network issues, trying again');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
let mondayFetchOptions = defaultMondayFetchOptions;
|
|
41
|
+
class AuthorizationInternalService {
|
|
42
|
+
static skipAuthorization(requset) {
|
|
43
|
+
requset.authorizationSkipPerformed = true;
|
|
44
|
+
}
|
|
45
|
+
static markAuthorized(request) {
|
|
46
|
+
request.authorizationCheckPerformed = true;
|
|
47
|
+
}
|
|
48
|
+
static failIfNotCoveredByAuthorization(request) {
|
|
49
|
+
if (!request.authorizationCheckPerformed && !request.authorizationSkipPerformed) {
|
|
50
|
+
throw 'Endpoint is not covered by authorization check';
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
static throwOnHttpErrorIfNeeded(response, placement) {
|
|
54
|
+
if (response.ok) {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const status = response.status;
|
|
58
|
+
logger.error({ tag: 'authorization-service', placement, status }, 'AuthorizationService: authorization request failed');
|
|
59
|
+
throw new Error(`AuthorizationService: [${placement}] authorization request failed with status ${status}`);
|
|
60
|
+
}
|
|
61
|
+
static generateInternalAuthToken(accountId, userId) {
|
|
62
|
+
return mondayJwt.signAuthorizationHeader({ appName: INTERNAL_APP_NAME, accountId, userId });
|
|
63
|
+
}
|
|
64
|
+
static setRequestFetchOptions(customMondayFetchOptions) {
|
|
65
|
+
mondayFetchOptions = {
|
|
66
|
+
...defaultMondayFetchOptions,
|
|
67
|
+
...customMondayFetchOptions,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
static getRequestFetchOptions() {
|
|
71
|
+
return mondayFetchOptions;
|
|
72
|
+
}
|
|
73
|
+
static getRequestTimeout() {
|
|
74
|
+
const isDevEnv = process.env.NODE_ENV === 'development';
|
|
75
|
+
return isDevEnv ? 60000 : 2000;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
exports.AuthorizationInternalService = AuthorizationInternalService;
|
|
80
|
+
exports.logger = logger;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { NextFunction } from 'express';
|
|
2
1
|
import { Action, BaseRequest, BaseResponse, Context, ContextGetter, ResourceGetter } from './types/general';
|
|
2
|
+
import type { NextFunction } from 'express';
|
|
3
3
|
export declare function getAuthorizationMiddleware(action: Action, resourceGetter: ResourceGetter, contextGetter?: ContextGetter): (request: BaseRequest, response: BaseResponse, next: NextFunction) => Promise<void>;
|
|
4
4
|
export declare function skipAuthorizationMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
|
|
5
5
|
export declare function authorizationCheckMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const onHeaders = require('on-headers');
|
|
4
|
+
const authorizationInternalService = require('./authorization-internal-service.js');
|
|
5
|
+
const authorizationService = require('./authorization-service.js');
|
|
6
|
+
|
|
7
|
+
const _interopDefault = e => e && e.__esModule ? e : { default: e };
|
|
8
|
+
|
|
9
|
+
const onHeaders__default = /*#__PURE__*/_interopDefault(onHeaders);
|
|
10
|
+
|
|
11
|
+
// getAuthorizationMiddleware is duplicated in testKit/index.ts
|
|
12
|
+
// If you are making changes to this function, please make sure to update the other file as well
|
|
13
|
+
function getAuthorizationMiddleware(action, resourceGetter, contextGetter) {
|
|
14
|
+
return async function authorizationMiddleware(request, response, next) {
|
|
15
|
+
contextGetter ||= defaultContextGetter;
|
|
16
|
+
const { userId, accountId } = contextGetter(request);
|
|
17
|
+
const resources = resourceGetter(request);
|
|
18
|
+
const { isAuthorized } = await authorizationService.AuthorizationService.isAuthorized(accountId, userId, resources, action);
|
|
19
|
+
authorizationInternalService.AuthorizationInternalService.markAuthorized(request);
|
|
20
|
+
if (!isAuthorized) {
|
|
21
|
+
response.status(403).json({ message: 'Access denied' });
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
next();
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function skipAuthorizationMiddleware(request, response, next) {
|
|
28
|
+
authorizationInternalService.AuthorizationInternalService.skipAuthorization(request);
|
|
29
|
+
next();
|
|
30
|
+
}
|
|
31
|
+
function authorizationCheckMiddleware(request, response, next) {
|
|
32
|
+
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
|
|
33
|
+
onHeaders__default.default(response, function () {
|
|
34
|
+
if (response.statusCode < 400) {
|
|
35
|
+
authorizationInternalService.AuthorizationInternalService.failIfNotCoveredByAuthorization(request);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
next();
|
|
40
|
+
}
|
|
41
|
+
function defaultContextGetter(request) {
|
|
42
|
+
return request.payload;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
exports.authorizationCheckMiddleware = authorizationCheckMiddleware;
|
|
46
|
+
exports.defaultContextGetter = defaultContextGetter;
|
|
47
|
+
exports.getAuthorizationMiddleware = getAuthorizationMiddleware;
|
|
48
|
+
exports.skipAuthorizationMiddleware = skipAuthorizationMiddleware;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const perf_hooks = require('perf_hooks');
|
|
4
|
+
const lodash = require('lodash');
|
|
5
|
+
const mondayFetch = require('@mondaydotcomorg/monday-fetch');
|
|
6
|
+
const prometheusService = require('./prometheus-service.js');
|
|
7
|
+
const authorizationInternalService = require('./authorization-internal-service.js');
|
|
8
|
+
const attributionsService = require('./attributions-service.js');
|
|
9
|
+
|
|
10
|
+
const GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS = 5 * 60;
|
|
11
|
+
function setRequestFetchOptions(customMondayFetchOptions) {
|
|
12
|
+
authorizationInternalService.AuthorizationInternalService.setRequestFetchOptions(customMondayFetchOptions);
|
|
13
|
+
}
|
|
14
|
+
class AuthorizationService {
|
|
15
|
+
static redisClient;
|
|
16
|
+
static grantedFeatureRedisExpirationInSeconds;
|
|
17
|
+
static async isAuthorized(...args) {
|
|
18
|
+
if (args.length === 3) {
|
|
19
|
+
return this.isAuthorizedMultiple(args[0], args[1], args[2]);
|
|
20
|
+
}
|
|
21
|
+
else if (args.length == 4) {
|
|
22
|
+
return this.isAuthorizedSingular(args[0], args[1], args[2], args[3]);
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
throw new Error('isAuthorized accepts either 3 or 4 arguments');
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
static async isUserGrantedWithFeature(accountId, userId, featureName, options = {}) {
|
|
29
|
+
const cachedKey = this.getCachedKeyName(userId, featureName);
|
|
30
|
+
const shouldSkipCache = options.shouldSkipCache ?? false;
|
|
31
|
+
if (this.redisClient && !shouldSkipCache) {
|
|
32
|
+
const grantedFeatureValue = await this.redisClient.get(cachedKey);
|
|
33
|
+
if (!(grantedFeatureValue === undefined || grantedFeatureValue === null)) {
|
|
34
|
+
// redis returns the value as string
|
|
35
|
+
return grantedFeatureValue === 'true';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const grantedFeatureValue = await this.fetchIsUserGrantedWithFeature(featureName, accountId, userId);
|
|
39
|
+
if (this.redisClient) {
|
|
40
|
+
await this.redisClient.set(cachedKey, grantedFeatureValue, 'EX', this.grantedFeatureRedisExpirationInSeconds);
|
|
41
|
+
}
|
|
42
|
+
return grantedFeatureValue;
|
|
43
|
+
}
|
|
44
|
+
static async fetchIsUserGrantedWithFeature(featureName, accountId, userId) {
|
|
45
|
+
const authorizationObject = {
|
|
46
|
+
action: featureName,
|
|
47
|
+
resource_type: 'feature',
|
|
48
|
+
};
|
|
49
|
+
const authorizeResponsePromise = await this.isAuthorized(accountId, userId, [authorizationObject]);
|
|
50
|
+
return authorizeResponsePromise.isAuthorized;
|
|
51
|
+
}
|
|
52
|
+
static getCachedKeyName(userId, featureName) {
|
|
53
|
+
return `granted-feature-${featureName}-${userId}`;
|
|
54
|
+
}
|
|
55
|
+
static async canActionInScope(accountId, userId, action, scope) {
|
|
56
|
+
const scopedActions = [{ action, scope }];
|
|
57
|
+
const scopedActionResponseObjects = await this.canActionInScopeMultiple(accountId, userId, scopedActions);
|
|
58
|
+
return scopedActionResponseObjects[0].permit;
|
|
59
|
+
}
|
|
60
|
+
static async canActionInScopeMultiple(accountId, userId, scopedActions) {
|
|
61
|
+
const internalAuthToken = authorizationInternalService.AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
|
|
62
|
+
const scopedActionsPayload = scopedActions.map(scopedAction => {
|
|
63
|
+
return { ...scopedAction, scope: lodash.mapKeys(scopedAction.scope, (_, key) => lodash.snakeCase(key)) }; // for example: { workspaceId: 1 } => { workspace_id: 1 }
|
|
64
|
+
});
|
|
65
|
+
const attributionHeaders = attributionsService.getAttributionsFromApi();
|
|
66
|
+
const response = await mondayFetch.fetch(getCanActionsInScopesUrl(), {
|
|
67
|
+
method: 'POST',
|
|
68
|
+
headers: {
|
|
69
|
+
Authorization: internalAuthToken,
|
|
70
|
+
'Content-Type': 'application/json',
|
|
71
|
+
...attributionHeaders,
|
|
72
|
+
},
|
|
73
|
+
timeout: authorizationInternalService.AuthorizationInternalService.getRequestTimeout(),
|
|
74
|
+
body: JSON.stringify({
|
|
75
|
+
user_id: userId,
|
|
76
|
+
scoped_actions: scopedActionsPayload,
|
|
77
|
+
}),
|
|
78
|
+
}, authorizationInternalService.AuthorizationInternalService.getRequestFetchOptions());
|
|
79
|
+
authorizationInternalService.AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'canActionInScopeMultiple');
|
|
80
|
+
const responseBody = await response.json();
|
|
81
|
+
const camelCaseKeys = obj => Object.fromEntries(Object.entries(obj).map(([key, value]) => [lodash.camelCase(key), value]));
|
|
82
|
+
const scopedActionsResponseObjects = responseBody.result.map(responseObject => {
|
|
83
|
+
const { scopedAction, permit } = responseObject;
|
|
84
|
+
const { scope } = scopedAction;
|
|
85
|
+
const transformKeys = obj => camelCaseKeys(obj);
|
|
86
|
+
return {
|
|
87
|
+
...responseObject,
|
|
88
|
+
scopedAction: { ...scopedAction, scope: transformKeys(scope) },
|
|
89
|
+
permit: transformKeys(permit),
|
|
90
|
+
};
|
|
91
|
+
});
|
|
92
|
+
return scopedActionsResponseObjects;
|
|
93
|
+
}
|
|
94
|
+
static async isAuthorizedSingular(accountId, userId, resources, action) {
|
|
95
|
+
const { authorizationObjects } = createAuthorizationParams(resources, action);
|
|
96
|
+
return this.isAuthorizedMultiple(accountId, userId, authorizationObjects);
|
|
97
|
+
}
|
|
98
|
+
static async isAuthorizedMultiple(accountId, userId, authorizationRequestObjects) {
|
|
99
|
+
const internalAuthToken = authorizationInternalService.AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
|
|
100
|
+
const startTime = perf_hooks.performance.now();
|
|
101
|
+
const attributionHeaders = attributionsService.getAttributionsFromApi();
|
|
102
|
+
const response = await mondayFetch.fetch(getAuthorizeUrl(), {
|
|
103
|
+
method: 'POST',
|
|
104
|
+
headers: {
|
|
105
|
+
Authorization: internalAuthToken,
|
|
106
|
+
'Content-Type': 'application/json',
|
|
107
|
+
...attributionHeaders,
|
|
108
|
+
},
|
|
109
|
+
timeout: authorizationInternalService.AuthorizationInternalService.getRequestTimeout(),
|
|
110
|
+
body: JSON.stringify({
|
|
111
|
+
user_id: userId,
|
|
112
|
+
authorize_request_objects: authorizationRequestObjects,
|
|
113
|
+
}),
|
|
114
|
+
}, authorizationInternalService.AuthorizationInternalService.getRequestFetchOptions());
|
|
115
|
+
const endTime = perf_hooks.performance.now();
|
|
116
|
+
const time = endTime - startTime;
|
|
117
|
+
const responseStatus = response.status;
|
|
118
|
+
prometheusService.sendAuthorizationChecksPerRequestMetric(responseStatus, authorizationRequestObjects.length);
|
|
119
|
+
authorizationInternalService.AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'isAuthorizedMultiple');
|
|
120
|
+
const responseBody = await response.json();
|
|
121
|
+
const unauthorizedObjects = [];
|
|
122
|
+
responseBody.result.forEach(function (isAuthorized, index) {
|
|
123
|
+
const authorizationObject = authorizationRequestObjects[index];
|
|
124
|
+
if (!isAuthorized) {
|
|
125
|
+
unauthorizedObjects.push(authorizationObject);
|
|
126
|
+
}
|
|
127
|
+
prometheusService.sendAuthorizationCheckResponseTimeMetric(authorizationObject.resource_type, authorizationObject.action, isAuthorized, responseStatus, time);
|
|
128
|
+
});
|
|
129
|
+
if (unauthorizedObjects.length > 0) {
|
|
130
|
+
authorizationInternalService.logger.info({
|
|
131
|
+
resources: JSON.stringify(unauthorizedObjects),
|
|
132
|
+
}, 'AuthorizationService: resource is unauthorized');
|
|
133
|
+
const unauthorizedIds = unauthorizedObjects
|
|
134
|
+
.filter(obj => !!obj.resource_id)
|
|
135
|
+
.map(obj => obj.resource_id);
|
|
136
|
+
return { isAuthorized: false, unauthorizedIds, unauthorizedObjects };
|
|
137
|
+
}
|
|
138
|
+
return { isAuthorized: true };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function setRedisClient(client, grantedFeatureRedisExpirationInSeconds = GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS) {
|
|
142
|
+
AuthorizationService.redisClient = client;
|
|
143
|
+
if (grantedFeatureRedisExpirationInSeconds && grantedFeatureRedisExpirationInSeconds > 0) {
|
|
144
|
+
AuthorizationService.grantedFeatureRedisExpirationInSeconds = grantedFeatureRedisExpirationInSeconds;
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
authorizationInternalService.logger.warn({ grantedFeatureRedisExpirationInSeconds }, 'Invalid input for grantedFeatureRedisExpirationInSeconds, must be positive number. using default ttl.');
|
|
148
|
+
AuthorizationService.grantedFeatureRedisExpirationInSeconds = GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function createAuthorizationParams(resources, action) {
|
|
152
|
+
const params = {
|
|
153
|
+
authorizationObjects: resources.map((resource) => {
|
|
154
|
+
const authorizationObject = {
|
|
155
|
+
resource_id: resource.id,
|
|
156
|
+
resource_type: resource.type,
|
|
157
|
+
action,
|
|
158
|
+
};
|
|
159
|
+
if (resource.wrapperData) {
|
|
160
|
+
authorizationObject.wrapper_data = resource.wrapperData;
|
|
161
|
+
}
|
|
162
|
+
return authorizationObject;
|
|
163
|
+
}),
|
|
164
|
+
};
|
|
165
|
+
return params;
|
|
166
|
+
}
|
|
167
|
+
function getAuthorizeUrl() {
|
|
168
|
+
return `${process.env.MONDAY_INTERNAL_URL}/internal_ms/authorization/authorize`;
|
|
169
|
+
}
|
|
170
|
+
function getCanActionsInScopesUrl() {
|
|
171
|
+
return `${process.env.MONDAY_INTERNAL_URL}/internal_ms/authorization/can_actions_in_scopes`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
exports.AuthorizationService = AuthorizationService;
|
|
175
|
+
exports.setRedisClient = setRedisClient;
|
|
176
|
+
exports.setRequestFetchOptions = setRequestFetchOptions;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME = 'AUTHORIZATION_RESOURCE_ATTRIBUTES_SNS_TOPIC';
|
|
4
|
+
const RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND = 'resourceAttributeModification';
|
|
5
|
+
const ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE = 100;
|
|
6
|
+
|
|
7
|
+
exports.ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE = ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE;
|
|
8
|
+
exports.RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME = RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME;
|
|
9
|
+
exports.RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND = RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { Api } from '@mondaydotcomorg/trident-backend-api';
|
|
2
|
+
import { logger } from './authorization-internal-service.mjs';
|
|
3
|
+
|
|
4
|
+
const APP_NAME_VARIABLE_KEY = 'APP_NAME';
|
|
5
|
+
const APP_NAME_HEADER_NAME = 'x-caller-app-name-from-sdk';
|
|
6
|
+
const FROM_SDK_HEADER_SUFFIX = `-from-sdk`;
|
|
7
|
+
let didSendFailureLogOnce = false;
|
|
8
|
+
function getAttributionsFromApi() {
|
|
9
|
+
const callerAppNameFromSdk = {
|
|
10
|
+
[APP_NAME_HEADER_NAME]: tryJsonParse(getEnvVariable(APP_NAME_VARIABLE_KEY)),
|
|
11
|
+
};
|
|
12
|
+
try {
|
|
13
|
+
const tridentContext = Api.getPart('context');
|
|
14
|
+
if (!tridentContext) {
|
|
15
|
+
return callerAppNameFromSdk;
|
|
16
|
+
}
|
|
17
|
+
const { runtimeAttributions } = tridentContext;
|
|
18
|
+
const runtimeAttributionsOutgoingHeaders = runtimeAttributions?.buildOutgoingHeaders('HTTP_INTERNAL');
|
|
19
|
+
if (!runtimeAttributionsOutgoingHeaders) {
|
|
20
|
+
return callerAppNameFromSdk;
|
|
21
|
+
}
|
|
22
|
+
const attributionsHeaders = Object.fromEntries(runtimeAttributionsOutgoingHeaders);
|
|
23
|
+
const attributionHeadersFromSdk = {};
|
|
24
|
+
Object.keys(attributionsHeaders).forEach(function (key) {
|
|
25
|
+
attributionHeadersFromSdk[`${key}${FROM_SDK_HEADER_SUFFIX}`] = attributionsHeaders[key];
|
|
26
|
+
});
|
|
27
|
+
return attributionHeadersFromSdk;
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (!didSendFailureLogOnce) {
|
|
31
|
+
logger.warn({ tag: 'authorization-service', error }, 'Failed to generate attributions headers from the API. Unexpected error while extracting headers. It may be caused by out of date Trident version.');
|
|
32
|
+
didSendFailureLogOnce = true;
|
|
33
|
+
}
|
|
34
|
+
return callerAppNameFromSdk;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function getEnvVariable(key) {
|
|
38
|
+
const envVar = process.env[key] || process.env[key.toUpperCase()] || process.env[key.toLowerCase()];
|
|
39
|
+
return envVar;
|
|
40
|
+
}
|
|
41
|
+
function tryJsonParse(value) {
|
|
42
|
+
if (!value) {
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(value);
|
|
47
|
+
}
|
|
48
|
+
catch (_err) {
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export { getAttributionsFromApi };
|