@mondaydotcomorg/monday-authorization 1.1.9-bugmoshefixlodashesm.3791 → 1.1.9-featurebelkaauthz-sdk-update.2209

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 (65) hide show
  1. package/CHANGELOG.md +0 -5
  2. package/README.md +0 -25
  3. package/dist/index.d.ts +4 -4
  4. package/dist/index.js +41 -18
  5. package/dist/lib/authorization-attributes-service.d.ts +23 -0
  6. package/dist/lib/authorization-attributes-service.js +65 -0
  7. package/dist/{authorization-internal-service.d.ts → lib/authorization-internal-service.d.ts} +4 -2
  8. package/dist/lib/authorization-internal-service.js +78 -0
  9. package/dist/{authorization-middleware.d.ts → lib/authorization-middleware.d.ts} +1 -1
  10. package/dist/lib/authorization-middleware.js +57 -0
  11. package/dist/lib/authorization-service.js +218 -0
  12. package/dist/{prometheus-service.js → lib/prometheus-service.js} +12 -17
  13. package/dist/{testKit → lib/testKit}/index.d.ts +2 -2
  14. package/dist/lib/testKit/index.js +58 -0
  15. package/dist/lib/types/authorization-attributes-contracts.d.ts +10 -0
  16. package/dist/lib/types/authorization-attributes-contracts.js +2 -0
  17. package/dist/lib/types/express.js +1 -0
  18. package/dist/{types → lib/types}/general.d.ts +4 -6
  19. package/dist/lib/types/general.js +2 -0
  20. package/dist/{types → lib/types}/scoped-actions-contracts.js +4 -3
  21. package/package.json +10 -31
  22. package/dist/attributions-service.d.ts +0 -3
  23. package/dist/attributions-service.js +0 -55
  24. package/dist/authorization-attributes-service.d.ts +0 -44
  25. package/dist/authorization-attributes-service.js +0 -144
  26. package/dist/authorization-internal-service.js +0 -80
  27. package/dist/authorization-middleware.js +0 -48
  28. package/dist/authorization-service.js +0 -184
  29. package/dist/constants/sns.d.ts +0 -3
  30. package/dist/constants/sns.js +0 -9
  31. package/dist/esm/attributions-service.d.ts +0 -3
  32. package/dist/esm/attributions-service.mjs +0 -53
  33. package/dist/esm/authorization-attributes-service.d.ts +0 -44
  34. package/dist/esm/authorization-attributes-service.mjs +0 -138
  35. package/dist/esm/authorization-internal-service.d.ts +0 -13
  36. package/dist/esm/authorization-internal-service.mjs +0 -57
  37. package/dist/esm/authorization-middleware.d.ts +0 -6
  38. package/dist/esm/authorization-middleware.mjs +0 -39
  39. package/dist/esm/authorization-service.d.ts +0 -29
  40. package/dist/esm/authorization-service.mjs +0 -174
  41. package/dist/esm/constants/sns.d.ts +0 -3
  42. package/dist/esm/constants/sns.mjs +0 -5
  43. package/dist/esm/index.d.ts +0 -13
  44. package/dist/esm/index.mjs +0 -21
  45. package/dist/esm/prometheus-service.mjs +0 -49
  46. package/dist/esm/testKit/index.d.ts +0 -11
  47. package/dist/esm/testKit/index.mjs +0 -44
  48. package/dist/esm/types/authorization-attributes-contracts.d.ts +0 -27
  49. package/dist/esm/types/authorization-attributes-contracts.mjs +0 -7
  50. package/dist/esm/types/express.mjs +0 -1
  51. package/dist/esm/types/general.d.ts +0 -32
  52. package/dist/esm/types/general.mjs +0 -1
  53. package/dist/esm/types/scoped-actions-contracts.mjs +0 -8
  54. package/dist/prometheus-service.d.ts +0 -10
  55. package/dist/testKit/index.js +0 -48
  56. package/dist/types/authorization-attributes-contracts.d.ts +0 -27
  57. package/dist/types/authorization-attributes-contracts.js +0 -7
  58. package/dist/types/express.d.ts +0 -10
  59. package/dist/types/express.js +0 -1
  60. package/dist/types/general.js +0 -1
  61. package/dist/types/scoped-actions-contracts.d.ts +0 -38
  62. package/dist/{authorization-service.d.ts → lib/authorization-service.d.ts} +1 -1
  63. /package/dist/{esm → lib}/prometheus-service.d.ts +0 -0
  64. /package/dist/{esm → lib}/types/express.d.ts +0 -0
  65. /package/dist/{esm → lib}/types/scoped-actions-contracts.d.ts +0 -0
@@ -1,20 +1,21 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
-
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendAuthorizationCheckResponseTimeMetric = exports.sendAuthorizationChecksPerRequestMetric = exports.getMetricsManager = exports.setPrometheus = exports.METRICS = void 0;
3
4
  let prometheus = null;
4
5
  let authorizationChecksPerRequestMetric = null;
5
6
  let authorizationCheckResponseTimeMetric = null;
6
- const METRICS = {
7
+ exports.METRICS = {
7
8
  AUTHORIZATION_CHECK: 'authorization_check',
8
9
  AUTHORIZATION_CHECKS_PER_REQUEST: 'authorization_checks_per_request',
9
10
  AUTHORIZATION_CHECK_RESPONSE_TIME: 'authorization_check_response_time',
10
11
  };
11
12
  const authorizationChecksPerRequestMetricConfig = {
12
- name: METRICS.AUTHORIZATION_CHECKS_PER_REQUEST,
13
+ name: exports.METRICS.AUTHORIZATION_CHECKS_PER_REQUEST,
13
14
  labels: ['responseStatus'],
14
15
  description: 'Authorization checks per request summary',
15
16
  };
16
17
  const authorizationCheckResponseTimeMetricConfig = {
17
- name: METRICS.AUTHORIZATION_CHECK_RESPONSE_TIME,
18
+ name: exports.METRICS.AUTHORIZATION_CHECK_RESPONSE_TIME,
18
19
  labels: ['resourceType', 'action', 'isAuthorized', 'responseStatus'],
19
20
  description: 'Authorization check response time summary',
20
21
  };
@@ -24,32 +25,26 @@ function setPrometheus(customPrometheus) {
24
25
  authorizationChecksPerRequestMetric = getMetricsManager().addMetric(METRICS_TYPES.SUMMARY, authorizationChecksPerRequestMetricConfig.name, authorizationChecksPerRequestMetricConfig.labels, authorizationChecksPerRequestMetricConfig.description);
25
26
  authorizationCheckResponseTimeMetric = getMetricsManager().addMetric(METRICS_TYPES.SUMMARY, authorizationCheckResponseTimeMetricConfig.name, authorizationCheckResponseTimeMetricConfig.labels, authorizationCheckResponseTimeMetricConfig.description);
26
27
  }
28
+ exports.setPrometheus = setPrometheus;
27
29
  function getMetricsManager() {
28
- return prometheus?.metricsManager;
30
+ return prometheus === null || prometheus === void 0 ? void 0 : prometheus.metricsManager;
29
31
  }
32
+ exports.getMetricsManager = getMetricsManager;
30
33
  function sendAuthorizationChecksPerRequestMetric(responseStatus, amountOfAuthorizationObjects) {
31
34
  try {
32
35
  if (authorizationChecksPerRequestMetric) {
33
36
  authorizationChecksPerRequestMetric.labels(responseStatus).observe(amountOfAuthorizationObjects);
34
37
  }
35
38
  }
36
- catch (e) {
37
- // ignore
38
- }
39
+ catch (e) { }
39
40
  }
41
+ exports.sendAuthorizationChecksPerRequestMetric = sendAuthorizationChecksPerRequestMetric;
40
42
  function sendAuthorizationCheckResponseTimeMetric(resourceType, action, isAuthorized, responseStatus, time) {
41
43
  try {
42
44
  if (authorizationCheckResponseTimeMetric) {
43
45
  authorizationCheckResponseTimeMetric.labels(resourceType, action, isAuthorized, responseStatus).observe(time);
44
46
  }
45
47
  }
46
- catch (e) {
47
- // ignore
48
- }
48
+ catch (e) { }
49
49
  }
50
-
51
- exports.METRICS = METRICS;
52
- exports.getMetricsManager = getMetricsManager;
53
50
  exports.sendAuthorizationCheckResponseTimeMetric = sendAuthorizationCheckResponseTimeMetric;
54
- exports.sendAuthorizationChecksPerRequestMetric = sendAuthorizationChecksPerRequestMetric;
55
- exports.setPrometheus = setPrometheus;
@@ -1,5 +1,5 @@
1
- import { Action, BaseRequest, BaseResponse, ContextGetter, Resource, ResourceGetter } from '../types/general';
2
- import type { NextFunction } from 'express';
1
+ import { NextFunction } from "express";
2
+ import { Action, BaseRequest, BaseResponse, ContextGetter, Resource, ResourceGetter } from "../types/general";
3
3
  export type TestPermittedAction = {
4
4
  accountId: number;
5
5
  userId: number;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getTestAuthorizationMiddleware = exports.clearTestPermittedActions = exports.addTestPermittedAction = void 0;
13
+ const authorization_middleware_1 = require("../authorization-middleware");
14
+ const authorization_internal_service_1 = require("../authorization-internal-service");
15
+ let testPermittedActions = [];
16
+ const addTestPermittedAction = (accountId, userId, resources, action) => {
17
+ testPermittedActions.push({ accountId, userId, resources, action });
18
+ };
19
+ exports.addTestPermittedAction = addTestPermittedAction;
20
+ const clearTestPermittedActions = () => {
21
+ testPermittedActions = [];
22
+ };
23
+ exports.clearTestPermittedActions = clearTestPermittedActions;
24
+ const isActionAuthorized = (accountId, userId, resources, action) => {
25
+ return {
26
+ isAuthorized: resources.every(resource => {
27
+ return testPermittedActions.some(combination => {
28
+ return combination.accountId === accountId &&
29
+ combination.userId === userId &&
30
+ combination.action === action &&
31
+ combination.resources.some(combinationResource => {
32
+ return resources.some(resource => {
33
+ return combinationResource.id === resource.id &&
34
+ combinationResource.type === resource.type &&
35
+ JSON.stringify(combinationResource.wrapperData) === JSON.stringify(resource.wrapperData);
36
+ });
37
+ });
38
+ });
39
+ })
40
+ };
41
+ };
42
+ const getTestAuthorizationMiddleware = (action, resourceGetter, contextGetter) => {
43
+ return function authorizationMiddleware(request, response, next) {
44
+ return __awaiter(this, void 0, void 0, function* () {
45
+ contextGetter || (contextGetter = authorization_middleware_1.defaultContextGetter);
46
+ const { userId, accountId } = contextGetter(request);
47
+ const resources = resourceGetter(request);
48
+ const { isAuthorized } = isActionAuthorized(accountId, userId, resources, action);
49
+ authorization_internal_service_1.AuthorizationInternalService.markAuthorized(request);
50
+ if (!isAuthorized) {
51
+ response.status(403).json({ message: 'Access denied' });
52
+ return;
53
+ }
54
+ next();
55
+ });
56
+ };
57
+ };
58
+ exports.getTestAuthorizationMiddleware = getTestAuthorizationMiddleware;
@@ -0,0 +1,10 @@
1
+ import { Resource } from './general';
2
+ export interface ResourceAttributeAssignment {
3
+ resourceType: Resource['type'];
4
+ resourceId: Resource['id'];
5
+ key: string;
6
+ value: string;
7
+ }
8
+ export interface ResourceAttributeResponse {
9
+ attributes: ResourceAttributeAssignment[];
10
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ "use strict";
@@ -1,14 +1,16 @@
1
- import type { Request, Response } from 'express';
1
+ import { Request, Response } from 'express';
2
2
  export interface Resource {
3
3
  id?: number;
4
4
  type: string;
5
5
  wrapperData?: object;
6
6
  }
7
7
  export type Action = string;
8
+ export type ResourceGetter = (request: BaseRequest) => Resource[];
8
9
  export interface Context {
9
10
  accountId: number;
10
11
  userId: number;
11
12
  }
13
+ export type ContextGetter = (request: BaseRequest) => Context;
12
14
  export interface AuthorizationObject {
13
15
  resource_id?: Resource['id'];
14
16
  resource_type: Resource['type'];
@@ -18,15 +20,11 @@ export interface AuthorizationObject {
18
20
  export interface AuthorizationParams {
19
21
  authorizationObjects: AuthorizationObject[];
20
22
  }
21
- type BasicObject = {
22
- [key: string]: string;
23
- };
23
+ type BasicObject = {};
24
24
  export type BaseParameters = BasicObject;
25
25
  export type BaseResponseBody = BasicObject;
26
26
  export type BaseBodyParameters = BasicObject;
27
27
  export type BaseQueryParameters = BasicObject;
28
28
  export type BaseRequest = Request<BaseParameters, BaseResponseBody, BaseBodyParameters, BaseQueryParameters>;
29
29
  export type BaseResponse = Response<BaseResponseBody>;
30
- export type ResourceGetter = (request: BaseRequest) => Resource[];
31
- export type ContextGetter = (request: BaseRequest) => Context;
32
30
  export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,8 +1,9 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
-
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PermitTechnicalReason = void 0;
4
+ var PermitTechnicalReason;
4
5
  (function (PermitTechnicalReason) {
5
6
  PermitTechnicalReason[PermitTechnicalReason["NO_REASON"] = 0] = "NO_REASON";
6
7
  PermitTechnicalReason[PermitTechnicalReason["NOT_ELIGIBLE"] = 1] = "NOT_ELIGIBLE";
7
8
  PermitTechnicalReason[PermitTechnicalReason["BY_ROLE_IN_SCOPE"] = 2] = "BY_ROLE_IN_SCOPE";
8
- })(exports.PermitTechnicalReason || (exports.PermitTechnicalReason = {}));
9
+ })(PermitTechnicalReason || (exports.PermitTechnicalReason = PermitTechnicalReason = {}));
package/package.json CHANGED
@@ -1,57 +1,36 @@
1
1
  {
2
2
  "name": "@mondaydotcomorg/monday-authorization",
3
- "version": "1.1.9-bugmoshefixlodashesm.3791+0724a6a58",
3
+ "version": "1.1.9-featurebelkaauthz-sdk-update.2209+0f244fa9f",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "BSD-3-Clause",
7
- "exports": {
8
- ".": {
9
- "import": "./dist/esm/index.mjs",
10
- "require": "./dist/index.js",
11
- "types": "./dist/index.d.ts"
12
- },
13
- "./package.json": "./package.json"
14
- },
15
7
  "scripts": {
16
- "test": "trident-library test",
17
- "lint": "trident-library lint",
18
- "build": "trident-library build",
19
- "watch": "trident-library build -w"
8
+ "test": "mocha -r ts-node/register -r tsconfig-paths/register './tests/*.test.ts' --timeout 5000 --exit",
9
+ "build": "tsc --build"
20
10
  },
21
11
  "dependencies": {
22
12
  "@mondaydotcomorg/monday-fetch": "^0.0.7",
23
- "@mondaydotcomorg/monday-jwt": "^3.0.14",
24
- "@mondaydotcomorg/monday-logger": "^4.0.11",
25
- "@mondaydotcomorg/monday-sns": "^1.0.6",
26
- "@mondaydotcomorg/trident-backend-api": "^0.24.3",
27
- "lodash": "^4.17.21",
13
+ "@mondaydotcomorg/monday-jwt": "^3.0.10",
14
+ "@mondaydotcomorg/monday-logger": "^3.0.10",
28
15
  "node-fetch": "^2.6.7",
29
16
  "on-headers": "^1.0.2",
30
17
  "ts-node": "^10.0.0"
31
18
  },
32
19
  "devDependencies": {
33
- "@mondaydotcomorg/trident-library": "^0.6.53",
34
20
  "@types/express": "^4.17.20",
35
- "@types/lodash": "^4.17.10",
21
+ "@types/mocha": "^8.2.2",
36
22
  "@types/on-headers": "^1.0.0",
37
23
  "@types/supertest": "^2.0.11",
38
24
  "express": "^4.17.1",
39
25
  "ioredis": "^5.2.4",
40
26
  "ioredis-mock": "^8.2.2",
27
+ "mocha": "^9.0.1",
41
28
  "supertest": "^6.1.3",
42
- "typescript": "^5.2.2"
29
+ "tsconfig-paths": "^3.9.0",
30
+ "typescript": "^5.1.6"
43
31
  },
44
32
  "files": [
45
33
  "dist/"
46
34
  ],
47
- "eslintConfig": {
48
- "extends": "@mondaydotcomorg/trident-library",
49
- "root": true
50
- },
51
- "trident": {
52
- "build": {
53
- "esmMjsRename": true
54
- }
55
- },
56
- "gitHead": "0724a6a58ad189b245879473cd13572d601294c0"
35
+ "gitHead": "0f244fa9ffa6a4bb8c24e8ef1f0f0d8e912d2e25"
57
36
  }
@@ -1,3 +0,0 @@
1
- export declare function getAttributionsFromApi(): {
2
- [key: string]: string;
3
- };
@@ -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
- const 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
- const 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 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;
@@ -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
- 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,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;