@mondaydotcomorg/monday-authorization 1.1.9-featuremosheauthorizationesm.3695 → 1.1.9-featureorcomonday-jwt-ts.472

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 (61) hide show
  1. package/CHANGELOG.md +0 -15
  2. package/README.md +0 -57
  3. package/dist/index.d.ts +2 -5
  4. package/dist/index.js +14 -18
  5. package/dist/lib/authorization-internal-service.d.ts +6 -0
  6. package/dist/lib/authorization-internal-service.js +17 -0
  7. package/dist/{authorization-middleware.d.ts → lib/authorization-middleware.d.ts} +1 -2
  8. package/dist/lib/authorization-middleware.js +54 -0
  9. package/dist/{authorization-service.d.ts → lib/authorization-service.d.ts} +1 -2
  10. package/dist/lib/authorization-service.js +233 -0
  11. package/dist/{prometheus-service.js → lib/prometheus-service.js} +10 -11
  12. package/dist/lib/types/express.js +1 -0
  13. package/dist/lib/types/general.js +2 -0
  14. package/dist/{types → lib/types}/scoped-actions-contracts.js +4 -3
  15. package/package.json +7 -30
  16. package/dist/attributions-service.d.ts +0 -3
  17. package/dist/attributions-service.js +0 -55
  18. package/dist/authorization-attributes-service.d.ts +0 -44
  19. package/dist/authorization-attributes-service.js +0 -144
  20. package/dist/authorization-internal-service.d.ts +0 -13
  21. package/dist/authorization-internal-service.js +0 -80
  22. package/dist/authorization-middleware.js +0 -48
  23. package/dist/authorization-service.js +0 -176
  24. package/dist/constants/sns.d.ts +0 -3
  25. package/dist/constants/sns.js +0 -9
  26. package/dist/esm/attributions-service.d.ts +0 -3
  27. package/dist/esm/attributions-service.mjs +0 -53
  28. package/dist/esm/authorization-attributes-service.d.ts +0 -44
  29. package/dist/esm/authorization-attributes-service.mjs +0 -138
  30. package/dist/esm/authorization-internal-service.d.ts +0 -13
  31. package/dist/esm/authorization-internal-service.mjs +0 -57
  32. package/dist/esm/authorization-middleware.d.ts +0 -6
  33. package/dist/esm/authorization-middleware.mjs +0 -39
  34. package/dist/esm/authorization-service.d.ts +0 -29
  35. package/dist/esm/authorization-service.mjs +0 -172
  36. package/dist/esm/constants/sns.d.ts +0 -3
  37. package/dist/esm/constants/sns.mjs +0 -5
  38. package/dist/esm/index.d.ts +0 -13
  39. package/dist/esm/index.mjs +0 -21
  40. package/dist/esm/prometheus-service.mjs +0 -45
  41. package/dist/esm/testKit/index.d.ts +0 -11
  42. package/dist/esm/testKit/index.mjs +0 -44
  43. package/dist/esm/types/authorization-attributes-contracts.d.ts +0 -27
  44. package/dist/esm/types/authorization-attributes-contracts.mjs +0 -7
  45. package/dist/esm/types/express.mjs +0 -1
  46. package/dist/esm/types/general.mjs +0 -1
  47. package/dist/esm/types/scoped-actions-contracts.mjs +0 -8
  48. package/dist/prometheus-service.d.ts +0 -10
  49. package/dist/testKit/index.d.ts +0 -11
  50. package/dist/testKit/index.js +0 -48
  51. package/dist/types/authorization-attributes-contracts.d.ts +0 -27
  52. package/dist/types/authorization-attributes-contracts.js +0 -7
  53. package/dist/types/express.d.ts +0 -10
  54. package/dist/types/express.js +0 -1
  55. package/dist/types/general.d.ts +0 -30
  56. package/dist/types/general.js +0 -1
  57. package/dist/types/scoped-actions-contracts.d.ts +0 -38
  58. /package/dist/{esm → lib}/prometheus-service.d.ts +0 -0
  59. /package/dist/{esm → lib}/types/express.d.ts +0 -0
  60. /package/dist/{esm → lib}/types/general.d.ts +0 -0
  61. /package/dist/{esm → lib}/types/scoped-actions-contracts.d.ts +0 -0
@@ -1,55 +0,0 @@
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
- const APP_NAME_VARIABLE_KEY = 'APP_NAME';
7
- const APP_NAME_HEADER_NAME = 'x-caller-app-name-from-sdk';
8
- const FROM_SDK_HEADER_SUFFIX = `-from-sdk`;
9
- let didSendFailureLogOnce = false;
10
- function getAttributionsFromApi() {
11
- let callerAppNameFromSdk = {
12
- [APP_NAME_HEADER_NAME]: tryJsonParse(getEnvVariable(APP_NAME_VARIABLE_KEY)),
13
- };
14
- try {
15
- const tridentContext = tridentBackendApi.Api.getPart('context');
16
- if (!tridentContext) {
17
- return callerAppNameFromSdk;
18
- }
19
- const { runtimeAttributions } = tridentContext;
20
- let runtimeAttributionsOutgoingHeaders = runtimeAttributions?.buildOutgoingHeaders('HTTP_INTERNAL');
21
- if (!runtimeAttributionsOutgoingHeaders) {
22
- return callerAppNameFromSdk;
23
- }
24
- const attributionsHeaders = Object.fromEntries(runtimeAttributionsOutgoingHeaders);
25
- const attributionHeadersFromSdk = {};
26
- Object.keys(attributionsHeaders).forEach(function (key) {
27
- attributionHeadersFromSdk[`${key}${FROM_SDK_HEADER_SUFFIX}`] = attributionsHeaders[key];
28
- });
29
- return attributionHeadersFromSdk;
30
- }
31
- catch (error) {
32
- if (!didSendFailureLogOnce) {
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
- didSendFailureLogOnce = true;
35
- }
36
- return callerAppNameFromSdk;
37
- }
38
- }
39
- function getEnvVariable(key) {
40
- const envVar = process.env[key] || process.env[key.toUpperCase()] || process.env[key.toLowerCase()];
41
- return envVar;
42
- }
43
- function tryJsonParse(value) {
44
- if (!value) {
45
- return value;
46
- }
47
- try {
48
- return JSON.parse(value);
49
- }
50
- catch (_err) {
51
- return value;
52
- }
53
- }
54
-
55
- exports.getAttributionsFromApi = getAttributionsFromApi;
@@ -1,44 +0,0 @@
1
- import { ResourceAttributeAssignment, ResourceAttributeResponse, ResourceAttributesOperation } from './types/authorization-attributes-contracts';
2
- import { Resource } from './types/general';
3
- export declare class AuthorizationAttributesService {
4
- private static LOG_TAG;
5
- /**
6
- * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
7
- * @param accountId
8
- * @param userId
9
- * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
10
- * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
11
- * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
12
- */
13
- static upsertResourceAttributes(accountId: number, userId: number, resourceAttributeAssignments: ResourceAttributeAssignment[]): Promise<ResourceAttributeResponse>;
14
- /**
15
- * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
16
- * @param accountId
17
- * @param userId
18
- * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
19
- * @param attributeKeys - Array of attribute keys to delete for the resource.
20
- * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
21
- */
22
- static deleteResourceAttributes(accountId: number, userId: number, resource: Resource, attributeKeys: string[]): Promise<ResourceAttributeResponse>;
23
- /**
24
- * Async function, this function only send the updates request to SNS and return before the change actually took place
25
- * @param accountId
26
- * @param appName - App name of the calling app
27
- * @param callerActionIdentifier - action identifier
28
- * @param resourceAttributeOperations - Array of operations to do on resource attributes.
29
- * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
30
- * */
31
- static updateResourceAttributesAsync(accountId: number, appName: string, callerActionIdentifier: string, resourceAttributeOperations: ResourceAttributesOperation[]): Promise<ResourceAttributesOperation[]>;
32
- private static sendSingleSnsMessage;
33
- private static getSnsTopicArn;
34
- private static getResourceAttributesUrl;
35
- /**
36
- * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
37
- * This function can be used as health check for services that updating resource attributes in async is crucial.
38
- * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
39
- * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
40
- * However, this is the best we can do without actually push dummy messages to the SNS.
41
- * @return {Promise<boolean>} - true if succeeded
42
- */
43
- static asyncResourceAttributesHealthCheck(): Promise<boolean>;
44
- }
@@ -1,144 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
-
3
- const chunk = require('lodash/chunk');
4
- const mondayFetch = require('@mondaydotcomorg/monday-fetch');
5
- const authorizationInternalService = require('./authorization-internal-service.js');
6
- const attributionsService = require('./attributions-service.js');
7
- const tridentBackendApi = require('@mondaydotcomorg/trident-backend-api');
8
- const mondaySns = require('@mondaydotcomorg/monday-sns');
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;
@@ -1,13 +0,0 @@
1
- import { Request } from 'express';
2
- import { fetch, MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
3
- export declare const logger: import("bunyan");
4
- export declare class AuthorizationInternalService {
5
- static skipAuthorization(requset: Request): void;
6
- static markAuthorized(request: Request): void;
7
- static failIfNotCoveredByAuthorization(request: Request): void;
8
- static throwOnHttpErrorIfNeeded(response: Awaited<ReturnType<typeof fetch>>, placement: string): void;
9
- static generateInternalAuthToken(accountId: number, userId: number): string;
10
- static setRequestFetchOptions(customMondayFetchOptions: MondayFetchOptions): void;
11
- static getRequestFetchOptions(): MondayFetchOptions;
12
- static getRequestTimeout(): 60000 | 2000;
13
- }
@@ -1,80 +0,0 @@
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
- function logOnFetchFail(retriesLeft, error) {
32
- if (retriesLeft == 0) {
33
- logger.error({ retriesLeft, error }, 'Authorization attempt failed due to network issues');
34
- }
35
- else {
36
- logger.info({ retriesLeft, error }, 'Authorization attempt failed due to network issues, trying again');
37
- }
38
- }
39
- let mondayFetchOptions = defaultMondayFetchOptions;
40
- const logger = MondayLogger__namespace.getLogger();
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,48 +0,0 @@
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;
@@ -1,176 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
-
3
- const lodash = require('lodash');
4
- const perf_hooks = require('perf_hooks');
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
- function setRedisClient(client, grantedFeatureRedisExpirationInSeconds = GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS) {
15
- AuthorizationService.redisClient = client;
16
- if (grantedFeatureRedisExpirationInSeconds && grantedFeatureRedisExpirationInSeconds > 0) {
17
- AuthorizationService.grantedFeatureRedisExpirationInSeconds = grantedFeatureRedisExpirationInSeconds;
18
- }
19
- else {
20
- authorizationInternalService.logger.warn({ grantedFeatureRedisExpirationInSeconds }, 'Invalid input for grantedFeatureRedisExpirationInSeconds, must be positive number. using default ttl.');
21
- AuthorizationService.grantedFeatureRedisExpirationInSeconds = GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS;
22
- }
23
- }
24
- class AuthorizationService {
25
- static redisClient;
26
- static grantedFeatureRedisExpirationInSeconds;
27
- static async isAuthorized(...args) {
28
- if (args.length === 3) {
29
- return this.isAuthorizedMultiple(args[0], args[1], args[2]);
30
- }
31
- else if (args.length == 4) {
32
- return this.isAuthorizedSingular(args[0], args[1], args[2], args[3]);
33
- }
34
- else {
35
- throw new Error('isAuthorized accepts either 3 or 4 arguments');
36
- }
37
- }
38
- static async isUserGrantedWithFeature(accountId, userId, featureName, options = {}) {
39
- let cachedKey = this.getCachedKeyName(userId, featureName);
40
- const shouldSkipCache = options.shouldSkipCache ?? false;
41
- if (this.redisClient && !shouldSkipCache) {
42
- let grantedFeatureValue = await this.redisClient.get(cachedKey);
43
- if (!(grantedFeatureValue === undefined || grantedFeatureValue === null)) {
44
- // redis returns the value as string
45
- return grantedFeatureValue === 'true';
46
- }
47
- }
48
- let grantedFeatureValue = await this.fetchIsUserGrantedWithFeature(featureName, accountId, userId);
49
- if (this.redisClient) {
50
- await this.redisClient.set(cachedKey, grantedFeatureValue, 'EX', this.grantedFeatureRedisExpirationInSeconds);
51
- }
52
- return grantedFeatureValue;
53
- }
54
- static async fetchIsUserGrantedWithFeature(featureName, accountId, userId) {
55
- let authorizationObject = {
56
- action: featureName,
57
- resource_type: 'feature',
58
- };
59
- let authorizeResponsePromise = await this.isAuthorized(accountId, userId, [authorizationObject]);
60
- return authorizeResponsePromise.isAuthorized;
61
- }
62
- static getCachedKeyName(userId, featureName) {
63
- return `granted-feature-${featureName}-${userId}`;
64
- }
65
- static async canActionInScope(accountId, userId, action, scope) {
66
- const scopedActions = [{ action, scope }];
67
- const scopedActionResponseObjects = await this.canActionInScopeMultiple(accountId, userId, scopedActions);
68
- return scopedActionResponseObjects[0].permit;
69
- }
70
- static async canActionInScopeMultiple(accountId, userId, scopedActions) {
71
- const internalAuthToken = authorizationInternalService.AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
72
- const scopedActionsPayload = scopedActions.map(scopedAction => {
73
- return { ...scopedAction, scope: lodash.mapKeys(scopedAction.scope, (_, key) => lodash.snakeCase(key)) }; // for example: { workspaceId: 1 } => { workspace_id: 1 }
74
- });
75
- const attributionHeaders = attributionsService.getAttributionsFromApi();
76
- const response = await mondayFetch.fetch(getCanActionsInScopesUrl(), {
77
- method: 'POST',
78
- headers: {
79
- Authorization: internalAuthToken,
80
- 'Content-Type': 'application/json',
81
- ...attributionHeaders,
82
- },
83
- timeout: authorizationInternalService.AuthorizationInternalService.getRequestTimeout(),
84
- body: JSON.stringify({
85
- user_id: userId,
86
- scoped_actions: scopedActionsPayload,
87
- }),
88
- }, authorizationInternalService.AuthorizationInternalService.getRequestFetchOptions());
89
- authorizationInternalService.AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'canActionInScopeMultiple');
90
- const responseBody = await response.json();
91
- const camelCaseKeys = obj => Object.fromEntries(Object.entries(obj).map(([key, value]) => [lodash.camelCase(key), value]));
92
- const scopedActionsResponseObjects = responseBody.result.map(responseObject => {
93
- const { scopedAction, permit } = responseObject;
94
- const { scope } = scopedAction;
95
- const transformKeys = obj => camelCaseKeys(obj);
96
- return {
97
- ...responseObject,
98
- scopedAction: { ...scopedAction, scope: transformKeys(scope) },
99
- permit: transformKeys(permit),
100
- };
101
- });
102
- return scopedActionsResponseObjects;
103
- }
104
- static async isAuthorizedSingular(accountId, userId, resources, action) {
105
- const { authorizationObjects } = createAuthorizationParams(resources, action);
106
- return this.isAuthorizedMultiple(accountId, userId, authorizationObjects);
107
- }
108
- static async isAuthorizedMultiple(accountId, userId, authorizationRequestObjects) {
109
- const internalAuthToken = authorizationInternalService.AuthorizationInternalService.generateInternalAuthToken(accountId, userId);
110
- const startTime = perf_hooks.performance.now();
111
- const attributionHeaders = attributionsService.getAttributionsFromApi();
112
- const response = await mondayFetch.fetch(getAuthorizeUrl(), {
113
- method: 'POST',
114
- headers: {
115
- Authorization: internalAuthToken,
116
- 'Content-Type': 'application/json',
117
- ...attributionHeaders,
118
- },
119
- timeout: authorizationInternalService.AuthorizationInternalService.getRequestTimeout(),
120
- body: JSON.stringify({
121
- user_id: userId,
122
- authorize_request_objects: authorizationRequestObjects,
123
- }),
124
- }, authorizationInternalService.AuthorizationInternalService.getRequestFetchOptions());
125
- const endTime = perf_hooks.performance.now();
126
- const time = endTime - startTime;
127
- const responseStatus = response.status;
128
- prometheusService.sendAuthorizationChecksPerRequestMetric(responseStatus, authorizationRequestObjects.length);
129
- authorizationInternalService.AuthorizationInternalService.throwOnHttpErrorIfNeeded(response, 'isAuthorizedMultiple');
130
- const responseBody = await response.json();
131
- const unauthorizedObjects = [];
132
- responseBody.result.forEach(function (isAuthorized, index) {
133
- const authorizationObject = authorizationRequestObjects[index];
134
- if (!isAuthorized) {
135
- unauthorizedObjects.push(authorizationObject);
136
- }
137
- prometheusService.sendAuthorizationCheckResponseTimeMetric(authorizationObject.resource_type, authorizationObject.action, isAuthorized, responseStatus, time);
138
- });
139
- if (unauthorizedObjects.length > 0) {
140
- authorizationInternalService.logger.info({
141
- resources: JSON.stringify(unauthorizedObjects),
142
- }, 'AuthorizationService: resource is unauthorized');
143
- const unauthorizedIds = unauthorizedObjects
144
- .filter(obj => !!obj.resource_id)
145
- .map(obj => obj.resource_id);
146
- return { isAuthorized: false, unauthorizedIds, unauthorizedObjects };
147
- }
148
- return { isAuthorized: true };
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;
@@ -1,3 +0,0 @@
1
- export declare const RESOURCE_ATTRIBUTES_SNS_ARN_SECRET_NAME = "AUTHORIZATION_RESOURCE_ATTRIBUTES_SNS_TOPIC";
2
- export declare const RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND = "resourceAttributeModification";
3
- export declare const ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE = 100;
@@ -1,9 +0,0 @@
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;
@@ -1,3 +0,0 @@
1
- export declare function getAttributionsFromApi(): {
2
- [key: string]: string;
3
- };
@@ -1,53 +0,0 @@
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
- let 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
- let 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 };