@mondaydotcomorg/monday-authorization 3.3.0-feat-add-graph-api-routing-support-c8d1d84 → 3.3.0-feat-add-graph-api-routing-support-8a1a68f

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 (62) hide show
  1. package/dist/attributions-service.d.ts +3 -2
  2. package/dist/attributions-service.d.ts.map +1 -1
  3. package/dist/attributions-service.js +1 -0
  4. package/dist/authorization-service.d.ts.map +1 -1
  5. package/dist/authorization-service.js +7 -10
  6. package/dist/clients/graph-api.d.ts +3 -3
  7. package/dist/clients/graph-api.d.ts.map +1 -1
  8. package/dist/clients/graph-api.js +12 -9
  9. package/dist/constants.d.ts +1 -0
  10. package/dist/constants.d.ts.map +1 -1
  11. package/dist/constants.js +2 -0
  12. package/dist/esm/attributions-service.d.ts +3 -2
  13. package/dist/esm/attributions-service.d.ts.map +1 -1
  14. package/dist/esm/attributions-service.mjs +1 -0
  15. package/dist/esm/authorization-service.d.ts.map +1 -1
  16. package/dist/esm/authorization-service.mjs +8 -11
  17. package/dist/esm/clients/graph-api.d.ts +3 -3
  18. package/dist/esm/clients/graph-api.d.ts.map +1 -1
  19. package/dist/esm/clients/graph-api.mjs +12 -9
  20. package/dist/esm/constants.d.ts +1 -0
  21. package/dist/esm/constants.d.ts.map +1 -1
  22. package/dist/esm/constants.mjs +2 -1
  23. package/dist/esm/metrics-service.d.ts +0 -1
  24. package/dist/esm/metrics-service.d.ts.map +1 -1
  25. package/dist/esm/metrics-service.mjs +1 -12
  26. package/dist/esm/prometheus-service.d.ts +1 -1
  27. package/dist/esm/prometheus-service.d.ts.map +1 -1
  28. package/dist/esm/prometheus-service.mjs +4 -14
  29. package/dist/esm/types/scoped-actions-contracts.d.ts +10 -1
  30. package/dist/esm/types/scoped-actions-contracts.d.ts.map +1 -1
  31. package/dist/esm/types/scoped-actions-contracts.mjs +9 -0
  32. package/dist/metrics-service.d.ts +0 -1
  33. package/dist/metrics-service.d.ts.map +1 -1
  34. package/dist/metrics-service.js +0 -12
  35. package/dist/prometheus-service.d.ts +1 -1
  36. package/dist/prometheus-service.d.ts.map +1 -1
  37. package/dist/prometheus-service.js +4 -14
  38. package/dist/types/scoped-actions-contracts.d.ts +10 -1
  39. package/dist/types/scoped-actions-contracts.d.ts.map +1 -1
  40. package/dist/types/scoped-actions-contracts.js +9 -0
  41. package/package.json +4 -2
  42. package/src/attributions-service.ts +93 -0
  43. package/src/authorization-attributes-service.ts +234 -0
  44. package/src/authorization-internal-service.ts +129 -0
  45. package/src/authorization-middleware.ts +51 -0
  46. package/src/authorization-service.ts +372 -0
  47. package/src/clients/graph-api.ts +176 -0
  48. package/src/clients/platform-api.ts +123 -0
  49. package/src/constants/sns.ts +5 -0
  50. package/src/constants.ts +23 -0
  51. package/src/index.ts +62 -0
  52. package/src/metrics-service.ts +67 -0
  53. package/src/prometheus-service.ts +48 -0
  54. package/src/roles-service.ts +125 -0
  55. package/src/testKit/index.ts +69 -0
  56. package/src/types/authorization-attributes-contracts.ts +33 -0
  57. package/src/types/express.ts +8 -0
  58. package/src/types/general.ts +32 -0
  59. package/src/types/graph-api.types.ts +25 -0
  60. package/src/types/roles.ts +42 -0
  61. package/src/types/scoped-actions-contracts.ts +57 -0
  62. package/src/utils/authorization.utils.ts +47 -0
@@ -41,17 +41,6 @@ function recordAuthorizationTiming(apiType, duration) {
41
41
  authorizationInternalService.logger.warn({ tag: 'metrics-service', error }, 'Failed to record authorization timing');
42
42
  }
43
43
  }
44
- function recordAuthorizationSuccess(apiType) {
45
- if (!initialized) {
46
- return;
47
- }
48
- try {
49
- mondayObservabilityKit.Metric.increment(`authorization.authorizationCheck.${apiType}.success`);
50
- }
51
- catch (error) {
52
- authorizationInternalService.logger.warn({ tag: 'metrics-service', error }, 'Failed to record authorization success');
53
- }
54
- }
55
44
  function recordAuthorizationError(apiType, statusCode) {
56
45
  if (!initialized) {
57
46
  return;
@@ -66,5 +55,4 @@ function recordAuthorizationError(apiType, statusCode) {
66
55
 
67
56
  exports.initializeMetrics = initializeMetrics;
68
57
  exports.recordAuthorizationError = recordAuthorizationError;
69
- exports.recordAuthorizationSuccess = recordAuthorizationSuccess;
70
58
  exports.recordAuthorizationTiming = recordAuthorizationTiming;
@@ -6,5 +6,5 @@ export declare const METRICS: {
6
6
  };
7
7
  export declare function setPrometheus(customPrometheus: any): void;
8
8
  export declare function getMetricsManager(): any;
9
- export declare function sendAuthorizationCheckResponseTimeMetric(resourceType: string, action: Action, isAuthorized: boolean, responseStatus: number, time: number, apiType?: 'platform' | 'graph'): void;
9
+ export declare function sendAuthorizationCheckResponseTimeMetric(resourceType: string, action: Action, isAuthorized: boolean, responseStatus: number, time: number): void;
10
10
  //# sourceMappingURL=prometheus-service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prometheus-service.d.ts","sourceRoot":"","sources":["../src/prometheus-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAKzC,eAAO,MAAM,OAAO;;;;CAInB,CAAC;AAQF,wBAAgB,aAAa,CAAC,gBAAgB,KAAA,QAmB7C;AAED,wBAAgB,iBAAiB,QAEhC;AAED,wBAAgB,wCAAwC,CACtD,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,OAAO,EACrB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,UAAU,GAAG,OAAoB,QAW3C"}
1
+ {"version":3,"file":"prometheus-service.d.ts","sourceRoot":"","sources":["../src/prometheus-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAKzC,eAAO,MAAM,OAAO;;;;CAInB,CAAC;AAQF,wBAAgB,aAAa,CAAC,gBAAgB,KAAA,QAU7C;AAED,wBAAgB,iBAAiB,QAEhC;AAED,wBAAgB,wCAAwC,CACtD,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,OAAO,EACrB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,MAAM,QASb"}
@@ -9,31 +9,21 @@ const METRICS = {
9
9
  };
10
10
  const authorizationCheckResponseTimeMetricConfig = {
11
11
  name: METRICS.AUTHORIZATION_CHECK_RESPONSE_TIME,
12
- labels: ['resourceType', 'action', 'isAuthorized', 'responseStatus', 'apiType'],
12
+ labels: ['resourceType', 'action', 'isAuthorized', 'responseStatus'],
13
13
  description: 'Authorization check response time summary',
14
14
  };
15
15
  function setPrometheus(customPrometheus) {
16
16
  prometheus = customPrometheus;
17
- if (!prometheus) {
18
- authorizationCheckResponseTimeMetric = null;
19
- return;
20
- }
21
17
  const { METRICS_TYPES } = prometheus;
22
- const metricsManager = getMetricsManager();
23
- if (!metricsManager) {
24
- return;
25
- }
26
- authorizationCheckResponseTimeMetric = metricsManager.addMetric(METRICS_TYPES.SUMMARY, authorizationCheckResponseTimeMetricConfig.name, authorizationCheckResponseTimeMetricConfig.labels, authorizationCheckResponseTimeMetricConfig.description);
18
+ authorizationCheckResponseTimeMetric = getMetricsManager().addMetric(METRICS_TYPES.SUMMARY, authorizationCheckResponseTimeMetricConfig.name, authorizationCheckResponseTimeMetricConfig.labels, authorizationCheckResponseTimeMetricConfig.description);
27
19
  }
28
20
  function getMetricsManager() {
29
21
  return prometheus?.metricsManager;
30
22
  }
31
- function sendAuthorizationCheckResponseTimeMetric(resourceType, action, isAuthorized, responseStatus, time, apiType = 'platform') {
23
+ function sendAuthorizationCheckResponseTimeMetric(resourceType, action, isAuthorized, responseStatus, time) {
32
24
  try {
33
25
  if (authorizationCheckResponseTimeMetric) {
34
- authorizationCheckResponseTimeMetric
35
- .labels(resourceType, action, isAuthorized, responseStatus, apiType)
36
- .observe(time);
26
+ authorizationCheckResponseTimeMetric.labels(resourceType, action, isAuthorized, responseStatus).observe(time);
37
27
  }
38
28
  }
39
29
  catch (e) {
@@ -21,7 +21,16 @@ export interface Translation {
21
21
  export declare enum PermitTechnicalReason {
22
22
  NO_REASON = 0,
23
23
  NOT_ELIGIBLE = 1,
24
- BY_ROLE_IN_SCOPE = 2
24
+ BY_ROLE_IN_SCOPE = 2,
25
+ /**
26
+ * NOT_APPLICABLE indicates that the permit was requested as part of the `permissions` parameter to the `getPermits`
27
+ * method, but would not otherwise be returned. This is done so that a cache in the monolith can serve
28
+ * two purposes: to mean both that a permit was requested and that it was received; at least: in the
29
+ * case of where a `permissions` parameter is passed to the `getPermits` method.
30
+ */
31
+ NOT_APPLICABLE = 3,
32
+ BY_POLICY = 4,
33
+ BY_OVERRIDE = 5
25
34
  }
26
35
  export interface ScopedActionPermit {
27
36
  can: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"scoped-actions-contracts.d.ts","sourceRoot":"","sources":["../../src/types/scoped-actions-contracts.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,cAAc;IAC7B,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IAClC,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,MAAM,YAAY,GAAG,cAAc,GAAG,UAAU,GAAG,UAAU,GAAG,mBAAmB,GAAG,YAAY,CAAC;AAEzG,MAAM,WAAW,WAAW;IAC1B,GAAG,EAAE,MAAM,CAAC;IACZ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;CAC1B;AAED,oBAAY,qBAAqB;IAC/B,SAAS,IAAI;IACb,YAAY,IAAI;IAChB,gBAAgB,IAAI;CACrB;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,OAAO,CAAC;IACb,MAAM,EAAE,WAAW,CAAC;IACpB,eAAe,EAAE,qBAAqB,CAAC;CACxC;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,YAAY,CAAC;CACrB;AAED,MAAM,WAAW,0BAA0B;IACzC,YAAY,EAAE,YAAY,CAAC;IAC3B,MAAM,EAAE,kBAAkB,CAAC;CAC5B"}
1
+ {"version":3,"file":"scoped-actions-contracts.d.ts","sourceRoot":"","sources":["../../src/types/scoped-actions-contracts.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,cAAc;IAC7B,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IAClC,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,MAAM,YAAY,GAAG,cAAc,GAAG,UAAU,GAAG,UAAU,GAAG,mBAAmB,GAAG,YAAY,CAAC;AAEzG,MAAM,WAAW,WAAW;IAC1B,GAAG,EAAE,MAAM,CAAC;IACZ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;CAC1B;AAED,oBAAY,qBAAqB;IAC/B,SAAS,IAAI;IACb,YAAY,IAAI;IAChB,gBAAgB,IAAI;IACpB;;;;;OAKG;IACH,cAAc,IAAI;IAClB,SAAS,IAAI;IACb,WAAW,IAAI;CAChB;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,OAAO,CAAC;IACb,MAAM,EAAE,WAAW,CAAC;IACpB,eAAe,EAAE,qBAAqB,CAAC;CACxC;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,YAAY,CAAC;CACrB;AAED,MAAM,WAAW,0BAA0B;IACzC,YAAY,EAAE,YAAY,CAAC;IAC3B,MAAM,EAAE,kBAAkB,CAAC;CAC5B"}
@@ -5,4 +5,13 @@ exports.PermitTechnicalReason = void 0;
5
5
  PermitTechnicalReason[PermitTechnicalReason["NO_REASON"] = 0] = "NO_REASON";
6
6
  PermitTechnicalReason[PermitTechnicalReason["NOT_ELIGIBLE"] = 1] = "NOT_ELIGIBLE";
7
7
  PermitTechnicalReason[PermitTechnicalReason["BY_ROLE_IN_SCOPE"] = 2] = "BY_ROLE_IN_SCOPE";
8
+ /**
9
+ * NOT_APPLICABLE indicates that the permit was requested as part of the `permissions` parameter to the `getPermits`
10
+ * method, but would not otherwise be returned. This is done so that a cache in the monolith can serve
11
+ * two purposes: to mean both that a permit was requested and that it was received; at least: in the
12
+ * case of where a `permissions` parameter is passed to the `getPermits` method.
13
+ */
14
+ PermitTechnicalReason[PermitTechnicalReason["NOT_APPLICABLE"] = 3] = "NOT_APPLICABLE";
15
+ PermitTechnicalReason[PermitTechnicalReason["BY_POLICY"] = 4] = "BY_POLICY";
16
+ PermitTechnicalReason[PermitTechnicalReason["BY_OVERRIDE"] = 5] = "BY_OVERRIDE";
8
17
  })(exports.PermitTechnicalReason || (exports.PermitTechnicalReason = {}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mondaydotcomorg/monday-authorization",
3
- "version": "3.3.0-feat-add-graph-api-routing-support-c8d1d84",
3
+ "version": "3.3.0-feat-add-graph-api-routing-support-8a1a68f",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "BSD-3-Clause",
@@ -47,7 +47,9 @@
47
47
  "typescript": "^5.2.2"
48
48
  },
49
49
  "files": [
50
- "dist/"
50
+ "dist/",
51
+ "src/",
52
+ "dist/node_modules/lodash-cjs/"
51
53
  ],
52
54
  "eslintConfig": {
53
55
  "extends": "@mondaydotcomorg/trident-library",
@@ -0,0 +1,93 @@
1
+ import { Api, Context, ExecutionContext } from '@mondaydotcomorg/trident-backend-api';
2
+ import { logger } from './authorization-internal-service';
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
+
8
+ let didSendFailureLogOnce = false;
9
+
10
+ export enum PlatformProfile {
11
+ API_INTERNAL = 'api-internal',
12
+ SLOW = 'slow',
13
+ INTERNAL = 'internal',
14
+ APP = 'app',
15
+ }
16
+
17
+ export function getProfile() {
18
+ const tridentContext = Api.getPart('context');
19
+ if (!tridentContext) {
20
+ return PlatformProfile.INTERNAL;
21
+ }
22
+ const { mondayRequestSource } = getExecutionContext(tridentContext);
23
+
24
+ switch (mondayRequestSource) {
25
+ case 'api': {
26
+ return PlatformProfile.API_INTERNAL;
27
+ }
28
+ case 'slow': {
29
+ return PlatformProfile.SLOW;
30
+ }
31
+ default:
32
+ return PlatformProfile.INTERNAL;
33
+ }
34
+ }
35
+
36
+ export function getExecutionContext(context: Context): ExecutionContext {
37
+ return context.execution.get();
38
+ }
39
+
40
+ export function getAttributionsFromApi(): { [key: string]: string } {
41
+ const callerAppNameFromSdk = {
42
+ [APP_NAME_HEADER_NAME]: tryJsonParse(getEnvVariable(APP_NAME_VARIABLE_KEY)),
43
+ };
44
+
45
+ try {
46
+ const tridentContext = Api.getPart('context');
47
+
48
+ if (!tridentContext) {
49
+ return callerAppNameFromSdk;
50
+ }
51
+
52
+ const { runtimeAttributions } = tridentContext;
53
+ const runtimeAttributionsOutgoingHeaders = runtimeAttributions?.buildOutgoingHeaders('HTTP_INTERNAL');
54
+
55
+ if (!runtimeAttributionsOutgoingHeaders) {
56
+ return callerAppNameFromSdk;
57
+ }
58
+
59
+ const attributionsHeaders = Object.fromEntries(runtimeAttributionsOutgoingHeaders);
60
+
61
+ const attributionHeadersFromSdk = {};
62
+ Object.keys(attributionsHeaders).forEach(function (key) {
63
+ attributionHeadersFromSdk[`${key}${FROM_SDK_HEADER_SUFFIX}`] = attributionsHeaders[key];
64
+ });
65
+
66
+ return attributionHeadersFromSdk;
67
+ } catch (error) {
68
+ if (!didSendFailureLogOnce) {
69
+ logger.warn(
70
+ { tag: 'authorization-service', error },
71
+ 'Failed to generate attributions headers from the API. Unexpected error while extracting headers. It may be caused by out of date Trident version.'
72
+ );
73
+ didSendFailureLogOnce = true;
74
+ }
75
+ return callerAppNameFromSdk;
76
+ }
77
+ }
78
+
79
+ function getEnvVariable(key: string) {
80
+ const envVar = process.env[key] || process.env[key.toUpperCase()] || process.env[key.toLowerCase()];
81
+ return envVar;
82
+ }
83
+
84
+ function tryJsonParse(value: string | undefined) {
85
+ if (!value) {
86
+ return value;
87
+ }
88
+ try {
89
+ return JSON.parse(value);
90
+ } catch (_err) {
91
+ return value;
92
+ }
93
+ }
@@ -0,0 +1,234 @@
1
+ import chunk from 'lodash/chunk.js';
2
+ import { Api, FetcherConfig, HttpClient } from '@mondaydotcomorg/trident-backend-api';
3
+ import { getTopicAttributes, sendToSns } from '@mondaydotcomorg/monday-sns';
4
+ import { HttpFetcherError, RecursivePartial } from '@mondaydotcomorg/monday-fetch-api';
5
+ import {
6
+ ResourceAttributeAssignment,
7
+ ResourceAttributeResponse,
8
+ ResourceAttributesOperation,
9
+ } from './types/authorization-attributes-contracts';
10
+ import { Resource } from './types/general';
11
+ import { logger } from './authorization-internal-service';
12
+ import { getAttributionsFromApi } from './attributions-service';
13
+ import {
14
+ ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE,
15
+ RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
16
+ SNS_ARN_ENV_VAR_NAME,
17
+ SNS_DEV_TEST_NAME,
18
+ } from './constants/sns';
19
+ import { APP_NAME, DEFAULT_FETCH_OPTIONS, ERROR_MESSAGES } from './constants';
20
+ import type { TopicAttributesMap } from 'aws-sdk/clients/sns';
21
+
22
+ export class AuthorizationAttributesService {
23
+ private static LOG_TAG = 'authorization_attributes';
24
+ private static API_PATHS = {
25
+ UPSERT_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource',
26
+ DELETE_RESOURCE_ATTRIBUTES: '/attributes/{accountId}/resource/{resourceType}/{resourceId}',
27
+ } as const;
28
+ private httpClient: HttpClient;
29
+ private fetchOptions: RecursivePartial<FetcherConfig>;
30
+ private snsArn: string;
31
+
32
+ /**
33
+ * Public constructor to create the AuthorizationAttributesService instance.
34
+ * @param httpClient The HTTP client to use for API requests, if not provided, the default HTTP client from Api will be used.
35
+ * @param fetchOptions The fetch options to use for API requests, if not provided, the default fetch options will be used.
36
+ */
37
+ constructor(httpClient?: HttpClient, fetchOptions?: RecursivePartial<FetcherConfig>) {
38
+ if (!httpClient) {
39
+ httpClient = Api.getPart('httpClient');
40
+ if (!httpClient) {
41
+ throw new Error(ERROR_MESSAGES.HTTP_CLIENT_NOT_INITIALIZED);
42
+ }
43
+ }
44
+
45
+ if (!fetchOptions) {
46
+ fetchOptions = DEFAULT_FETCH_OPTIONS;
47
+ } else {
48
+ fetchOptions = {
49
+ ...DEFAULT_FETCH_OPTIONS,
50
+ ...fetchOptions,
51
+ };
52
+ }
53
+ this.httpClient = httpClient;
54
+ this.fetchOptions = fetchOptions;
55
+ this.snsArn = AuthorizationAttributesService.getSnsTopicArn();
56
+ }
57
+
58
+ /**
59
+ * Upsert resource attributes synchronously, performing http call to the authorization MS to assign the given attributes to the given resource.
60
+ * @param accountId
61
+ * @param resourceAttributeAssignments - Array of resource (resourceType, resourceId) and attribute (key, value) pairs to upsert in the authorization MS.
62
+ * e.g. [{ resourceType: 'board', resourceId: 123, key: 'board_kind', value: 'private' }]
63
+ * @returns ResourceAttributeResponse - The affected (created and updated_ resource attributes assignments in the `attributes` field.
64
+ */
65
+ async upsertResourceAttributes(
66
+ accountId: number,
67
+ resourceAttributeAssignments: ResourceAttributeAssignment[]
68
+ ): Promise<ResourceAttributeResponse> {
69
+ const attributionHeaders = getAttributionsFromApi();
70
+ try {
71
+ return await this.httpClient.fetch<ResourceAttributeResponse>(
72
+ {
73
+ url: {
74
+ appName: APP_NAME,
75
+ path: AuthorizationAttributesService.API_PATHS.UPSERT_RESOURCE_ATTRIBUTES.replace(
76
+ '{accountId}',
77
+ accountId.toString()
78
+ ),
79
+ },
80
+ method: 'POST',
81
+ headers: {
82
+ 'Content-Type': 'application/json',
83
+ ...attributionHeaders,
84
+ },
85
+ body: JSON.stringify({ resourceAttributeAssignments }),
86
+ },
87
+ this.fetchOptions
88
+ );
89
+ } catch (err) {
90
+ if (err instanceof HttpFetcherError) {
91
+ throw new Error(ERROR_MESSAGES.REQUEST_FAILED('upsertResourceAttributes', err.status, err.message));
92
+ }
93
+ throw err;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Delete resource attributes assignments synchronously, performing http call to the authorization MS to delete the given attributes from the given singular resource.
99
+ * @param accountId
100
+ * @param resource - The resource (resourceType, resourceId) to delete the attributes for.
101
+ * @param attributeKeys - Array of attribute keys to delete for the resource.
102
+ * @returns ResourceAttributeResponse - The affected (deleted) resource attributes assignments in the `attributes` field.
103
+ */
104
+ async deleteResourceAttributes(
105
+ accountId: number,
106
+ resource: Resource,
107
+ attributeKeys: string[]
108
+ ): Promise<ResourceAttributeResponse> {
109
+ const attributionHeaders = getAttributionsFromApi();
110
+ if (!resource.id) {
111
+ throw new Error('Resource ID is required');
112
+ }
113
+ try {
114
+ return await this.httpClient.fetch<ResourceAttributeResponse>(
115
+ {
116
+ url: {
117
+ appName: APP_NAME,
118
+ path: AuthorizationAttributesService.API_PATHS.DELETE_RESOURCE_ATTRIBUTES.replace(
119
+ '{accountId}',
120
+ accountId.toString()
121
+ )
122
+ .replace('{resourceType}', resource.type)
123
+ .replace('{resourceId}', resource.id.toString()),
124
+ },
125
+ method: 'DELETE',
126
+ headers: {
127
+ 'Content-Type': 'application/json',
128
+ ...attributionHeaders,
129
+ },
130
+ body: JSON.stringify({ keys: attributeKeys }),
131
+ },
132
+ this.fetchOptions
133
+ );
134
+ } catch (err) {
135
+ if (err instanceof HttpFetcherError) {
136
+ throw new Error(ERROR_MESSAGES.REQUEST_FAILED('deleteResourceAttributes', err.status, err.message));
137
+ }
138
+ throw err;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Async function, this function only send the updates request to SNS and return before the change actually took place
144
+ * @param accountId
145
+ * @param appName - App name of the calling app
146
+ * @param callerActionIdentifier - action identifier
147
+ * @param resourceAttributeOperations - Array of operations to do on resource attributes.
148
+ * @return {Promise<ResourceAttributesOperation[]>} Array of sent operations
149
+ * */
150
+ async updateResourceAttributesAsync(
151
+ accountId: number,
152
+ appName: string,
153
+ callerActionIdentifier: string,
154
+ resourceAttributeOperations: ResourceAttributesOperation[]
155
+ ): Promise<ResourceAttributesOperation[]> {
156
+ const topicArn: string = this.snsArn;
157
+ const sendToSnsPromises: Promise<ResourceAttributesOperation[]>[] = [];
158
+ const operationChucks = chunk(resourceAttributeOperations, ASYNC_RESOURCE_ATTRIBUTES_MAX_OPERATIONS_PER_MESSAGE);
159
+ for (const operationsChunk of operationChucks) {
160
+ sendToSnsPromises.push(
161
+ this.sendSingleSnsMessage(topicArn, accountId, appName, callerActionIdentifier, operationsChunk)
162
+ );
163
+ }
164
+ return (await Promise.all(sendToSnsPromises)).flat();
165
+ }
166
+
167
+ private async sendSingleSnsMessage(
168
+ topicArn: string,
169
+ accountId: number,
170
+ appName: string,
171
+ callerActionIdentifier: string,
172
+ operations: ResourceAttributesOperation[]
173
+ ): Promise<ResourceAttributesOperation[]> {
174
+ const payload = {
175
+ kind: RESOURCE_ATTRIBUTES_SNS_UPDATE_OPERATION_MESSAGE_KIND,
176
+ payload: {
177
+ accountId: accountId,
178
+ callerAppName: appName,
179
+ callerActionIdentifier: callerActionIdentifier,
180
+ operations: operations,
181
+ },
182
+ };
183
+ try {
184
+ await sendToSns(payload, topicArn);
185
+ return operations;
186
+ } catch (error) {
187
+ logger.error(
188
+ { error, tag: AuthorizationAttributesService.LOG_TAG },
189
+ 'Authorization resource attributes async update: failed to send operations to SNS'
190
+ );
191
+ return [];
192
+ }
193
+ }
194
+
195
+ private static getSnsTopicArn(): string {
196
+ const arnFromEnv: string | undefined = process.env[SNS_ARN_ENV_VAR_NAME];
197
+ if (arnFromEnv) {
198
+ return arnFromEnv;
199
+ }
200
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
201
+ return SNS_DEV_TEST_NAME;
202
+ }
203
+ throw new Error('Unable to get sns topic arn from env variable');
204
+ }
205
+
206
+ /**
207
+ * Checks we can contact the required SNS topic that used to send attribute updates to Authorization MS.
208
+ * This function can be used as health check for services that updating resource attributes in async is crucial.
209
+ * Note this function only verify the POD can contact AWS SDK and the topic exists, but the user still might get
210
+ * errors when pushing for the SNS (e.g: in case the AWS role of the POD don't have permissions to push messages).
211
+ * However, this is the best we can do without actually push dummy messages to the SNS.
212
+ * @return {Promise<boolean>} - true if succeeded
213
+ */
214
+ async asyncResourceAttributesHealthCheck(): Promise<boolean> {
215
+ try {
216
+ const requestedTopicArn: string = this.snsArn;
217
+ const attributes: TopicAttributesMap = await getTopicAttributes(requestedTopicArn);
218
+ const isHealthy = !(!attributes || !('TopicArn' in attributes) || attributes.TopicArn !== requestedTopicArn);
219
+ if (!isHealthy) {
220
+ logger.error(
221
+ { requestedTopicArn, snsReturnedAttributes: attributes, tag: AuthorizationAttributesService.LOG_TAG },
222
+ 'authorization-attributes-service failed in health check'
223
+ );
224
+ }
225
+ return isHealthy;
226
+ } catch (error) {
227
+ logger.error(
228
+ { error, tag: AuthorizationAttributesService.LOG_TAG },
229
+ 'authorization-attributes-service got error during health check'
230
+ );
231
+ return false;
232
+ }
233
+ }
234
+ }
@@ -0,0 +1,129 @@
1
+ import { signAuthorizationHeader } from '@mondaydotcomorg/monday-jwt';
2
+ import { fetch, MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
3
+ import * as MondayLogger from '@mondaydotcomorg/monday-logger';
4
+ import { NullableErrorWithType, OnRetryCallback, RetryPolicy } from '@mondaydotcomorg/monday-fetch-api';
5
+ import { IgniteClient } from '@mondaydotcomorg/ignite-sdk';
6
+ import { BaseRequest } from './types/general';
7
+
8
+ const INTERNAL_APP_NAME = 'internal_ms';
9
+ const MAX_RETRIES = 3;
10
+ const RETRY_DELAY_MS = 10;
11
+ export const logger = MondayLogger.getLogger();
12
+
13
+ const defaultMondayFetchOptions: MondayFetchOptions = {
14
+ retries: MAX_RETRIES,
15
+ callback: logOnFetchFail,
16
+ };
17
+
18
+ export const onRetryCallback: OnRetryCallback = (attempt: number, error?: NullableErrorWithType) => {
19
+ if (attempt == MAX_RETRIES) {
20
+ logger.error({ tag: 'authorization-service', attempt, error }, 'Authorization attempt failed');
21
+ } else {
22
+ logger.info({ tag: 'authorization-service', attempt, error }, 'Authorization attempt failed, trying again');
23
+ }
24
+ };
25
+
26
+ function logOnFetchFail(retriesLeft: number, error: Error) {
27
+ if (retriesLeft == 0) {
28
+ logger.error({ retriesLeft, error }, 'Authorization attempt failed due to network issues');
29
+ } else {
30
+ logger.info({ retriesLeft, error }, 'Authorization attempt failed due to network issues, trying again');
31
+ }
32
+ }
33
+
34
+ let mondayFetchOptions: MondayFetchOptions = defaultMondayFetchOptions;
35
+
36
+ export class AuthorizationInternalService {
37
+ static igniteClient?: IgniteClient;
38
+ static skipAuthorization(requset: BaseRequest): void {
39
+ requset.authorizationSkipPerformed = true;
40
+ }
41
+
42
+ static markAuthorized(request: BaseRequest): void {
43
+ request.authorizationCheckPerformed = true;
44
+ }
45
+
46
+ static failIfNotCoveredByAuthorization(request: BaseRequest): void {
47
+ if (!request.authorizationCheckPerformed && !request.authorizationSkipPerformed) {
48
+ throw 'Endpoint is not covered by authorization check';
49
+ }
50
+ }
51
+
52
+ static throwOnHttpErrorIfNeeded(response: Awaited<ReturnType<typeof fetch>>, placement: string): void {
53
+ if (response.ok) {
54
+ return;
55
+ }
56
+
57
+ const status = response.status;
58
+ logger.error(
59
+ { tag: 'authorization-service', placement, status },
60
+ 'AuthorizationService: authorization request failed'
61
+ );
62
+
63
+ throw new Error(`AuthorizationService: [${placement}] authorization request failed with status ${status}`);
64
+ }
65
+
66
+ static throwOnHttpError(status: number, placement: string) {
67
+ logger.error(
68
+ { tag: 'authorization-service', placement, status },
69
+ 'AuthorizationService: authorization request failed'
70
+ );
71
+ throw new Error(`AuthorizationService: [${placement}] authorization request failed with status ${status}`);
72
+ }
73
+
74
+ static generateInternalAuthToken(accountId: number, userId: number) {
75
+ return signAuthorizationHeader({ appName: INTERNAL_APP_NAME, accountId, userId });
76
+ }
77
+
78
+ static setRequestFetchOptions(customMondayFetchOptions: MondayFetchOptions) {
79
+ mondayFetchOptions = {
80
+ ...defaultMondayFetchOptions,
81
+ ...customMondayFetchOptions,
82
+ };
83
+ }
84
+
85
+ static getRequestFetchOptions(): MondayFetchOptions {
86
+ return mondayFetchOptions;
87
+ }
88
+
89
+ static setIgniteClient(client: IgniteClient) {
90
+ this.igniteClient = client;
91
+ }
92
+
93
+ static getRequestTimeout() {
94
+ const isDevEnv = process.env.NODE_ENV === 'development';
95
+ const defaultTimeout = isDevEnv ? 60000 : 2000;
96
+
97
+ if (!this.igniteClient) {
98
+ return defaultTimeout;
99
+ }
100
+
101
+ const overrideTimeouts = this.igniteClient.configuration.getObjectValue<Record<string, number>>(
102
+ 'override-outgoing-request-timeout-ms',
103
+ {}
104
+ );
105
+ try {
106
+ if (process.env.APP_NAME && process.env.APP_NAME in overrideTimeouts) {
107
+ return overrideTimeouts[process.env.APP_NAME];
108
+ } else {
109
+ return this.igniteClient.configuration.getNumberValue('outgoing-request-timeout-ms', defaultTimeout);
110
+ }
111
+ } catch (error) {
112
+ logger.error(
113
+ { tag: 'authorization-service', error, defaultTimeout },
114
+ 'Failed to get timeout from ignite configuration, returning default timeout'
115
+ );
116
+ return defaultTimeout;
117
+ }
118
+ }
119
+
120
+ static getRetriesPolicy(): RetryPolicy {
121
+ const fetchOptions = AuthorizationInternalService.getRequestFetchOptions();
122
+ return {
123
+ useRetries: fetchOptions.retries !== undefined,
124
+ maxRetries: fetchOptions.retries !== undefined ? fetchOptions.retries : 0,
125
+ onRetry: onRetryCallback,
126
+ retryDelayMS: fetchOptions.retryDelay ?? RETRY_DELAY_MS,
127
+ };
128
+ }
129
+ }
@@ -0,0 +1,51 @@
1
+ import onHeaders from 'on-headers';
2
+ import { AuthorizationInternalService } from './authorization-internal-service';
3
+ import { AuthorizationService, createAuthorizationParams } from './authorization-service';
4
+ import { Action, BaseRequest, BaseResponse, Context, ContextGetter, ResourceGetter } from './types/general';
5
+ import type { NextFunction } from 'express';
6
+
7
+ // getAuthorizationMiddleware is duplicated in testKit/index.ts
8
+ // If you are making changes to this function, please make sure to update the other file as well
9
+ export function getAuthorizationMiddleware(
10
+ action: Action,
11
+ resourceGetter: ResourceGetter,
12
+ contextGetter?: ContextGetter
13
+ ) {
14
+ return async function authorizationMiddleware(
15
+ request: BaseRequest,
16
+ response: BaseResponse,
17
+ next: NextFunction
18
+ ): Promise<void> {
19
+ contextGetter ||= defaultContextGetter;
20
+ const { userId, accountId } = contextGetter(request);
21
+ const resources = resourceGetter(request);
22
+ const { authorizationObjects } = createAuthorizationParams(resources, action);
23
+ const { isAuthorized } = await AuthorizationService.isAuthorized(accountId, userId, authorizationObjects);
24
+ AuthorizationInternalService.markAuthorized(request);
25
+ if (!isAuthorized) {
26
+ response.status(403).json({ message: 'Access denied' });
27
+ return;
28
+ }
29
+ next();
30
+ };
31
+ }
32
+
33
+ export function skipAuthorizationMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void {
34
+ AuthorizationInternalService.skipAuthorization(request);
35
+ next();
36
+ }
37
+
38
+ export function authorizationCheckMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void {
39
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
40
+ onHeaders(response, function () {
41
+ if (response.statusCode < 400) {
42
+ AuthorizationInternalService.failIfNotCoveredByAuthorization(request);
43
+ }
44
+ });
45
+ }
46
+ next();
47
+ }
48
+
49
+ export function defaultContextGetter(request: BaseRequest): Context {
50
+ return request.payload;
51
+ }