@mondaydotcomorg/monday-authorization 1.1.9-featurefilipmcipher-core-flags-client.2760 → 1.1.9-featureliorshonehourjwttoken.465

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,16 +5,6 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](http://keepachangelog.com/)
6
6
  and this project adheres to [Semantic Versioning](http://semver.org/).
7
7
 
8
- ## [1.2.3] - 2024-06-10
9
- ### Added
10
-
11
- - [`feature/yarden/resource-attributes-api-support-authz-sdk (#5826)`](https://github.com/DaPulse/monday-npm-packages/pull/5826)
12
- - `AuthorizationAttributesService` - now supports upsert (`upsertResourceAttributesSync`) and delete (`deleteResourceAttributesSync`) resource attributes in the authorization MS
13
-
14
- ## [1.2.0] - 2024-01-05
15
- ### Added
16
- - `isAuthorized` now return the unauthorized objects - regardless to the unauthorized ids (which may be missing resource ids if resource has no id, like `feature` e.g.)
17
-
18
8
  ## [1.1.0] - 2023-08-09
19
9
 
20
10
  ### ⚠ BREAKING CHANGES
package/README.md CHANGED
@@ -136,35 +136,3 @@ const canActionInScopeMultipleResponse: ScopedActionResponseObject[] =
136
136
  * ]
137
137
  * /
138
138
  ```
139
-
140
- ### Authorization Attributes API
141
-
142
- Use `AuthorizationAttributesService.upsertResourceAttributesSync` to upsert multiple resource attributes in the authorization MS synchronously.
143
-
144
- ```ts
145
- import { AuthorizationAttributesService, ResourceAttributeAssignment, ResourceAttributeResponse } from '@mondaydotcomorg/monday-authorization';
146
-
147
- const accountId = 739630;
148
- const userId = 4;
149
- const resourceAttributesAssignments: ResourceAttributeAssignment[] = [
150
- { resourceId: 18, resourceType: 'workspace', key: 'is_default_workspace', value: 'true' },
151
- { resourceId: 23, resourceType: 'board', key: 'board_kind', value: 'private' }
152
- ];
153
-
154
- const response: ResourceAttributeResponse = await AuthorizationAttributesService.upsertResourceAttributesSync(accountId, userId, resourceAttributesAssignments);
155
- ```
156
-
157
- Use `AuthorizationAttributesService.deleteResourceAttributesSync` to delete single resource's attributes in the authorization MS synchronously.
158
-
159
-
160
- ```ts
161
- import { AuthorizationAttributesService, ResourceAttributeResponse, Resource } from '@mondaydotcomorg/monday-authorization';
162
-
163
- const accountId = 739630;
164
- const userId = 4;
165
- const resource: Resource = { type: 'workspace', id: 18 };
166
- const attributeKeys: string[] = ['is_default_workspace', 'workspace_kind'];
167
-
168
- const response: ResourceAttributeResponse = await AuthorizationAttributesService.deleteResourceAttributesSync(accountId, userId, resource, attributeKeys);
169
- ```
170
-
@@ -0,0 +1,10 @@
1
+ import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
2
+ export interface InitOptions {
3
+ prometheus?: any;
4
+ mondayFetchOptions?: MondayFetchOptions;
5
+ redisClient?: any;
6
+ grantedFeatureRedisExpirationInSeconds?: number;
7
+ }
8
+ export declare function init(options?: InitOptions): void;
9
+ export { authorizationCheckMiddleware, getAuthorizationMiddleware, skipAuthorizationMiddleware, } from './lib/authorization-middleware';
10
+ export { AuthorizationService } from './lib/authorization-service';
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthorizationService = exports.skipAuthorizationMiddleware = exports.getAuthorizationMiddleware = exports.authorizationCheckMiddleware = exports.init = void 0;
4
+ const prometheus_service_1 = require("./lib/prometheus-service");
5
+ const authorization_service_1 = require("./lib/authorization-service");
6
+ function init(options = {}) {
7
+ if (options.prometheus) {
8
+ (0, prometheus_service_1.setPrometheus)(options.prometheus);
9
+ }
10
+ if (options.mondayFetchOptions) {
11
+ (0, authorization_service_1.setRequestFetchOptions)(options.mondayFetchOptions);
12
+ }
13
+ if (options.redisClient) {
14
+ (0, authorization_service_1.setRedisClient)(options.redisClient, options.grantedFeatureRedisExpirationInSeconds);
15
+ }
16
+ }
17
+ exports.init = init;
18
+ var authorization_middleware_1 = require("./lib/authorization-middleware");
19
+ Object.defineProperty(exports, "authorizationCheckMiddleware", { enumerable: true, get: function () { return authorization_middleware_1.authorizationCheckMiddleware; } });
20
+ Object.defineProperty(exports, "getAuthorizationMiddleware", { enumerable: true, get: function () { return authorization_middleware_1.getAuthorizationMiddleware; } });
21
+ Object.defineProperty(exports, "skipAuthorizationMiddleware", { enumerable: true, get: function () { return authorization_middleware_1.skipAuthorizationMiddleware; } });
22
+ var authorization_service_2 = require("./lib/authorization-service");
23
+ Object.defineProperty(exports, "AuthorizationService", { enumerable: true, get: function () { return authorization_service_2.AuthorizationService; } });
@@ -0,0 +1,6 @@
1
+ import { Request } from 'express';
2
+ export declare class AuthorizationInternalService {
3
+ static skipAuthorization(requset: Request): void;
4
+ static markAuthorized(request: Request): void;
5
+ static failIfNotCoveredByAuthorization(request: Request): void;
6
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthorizationInternalService = void 0;
4
+ class AuthorizationInternalService {
5
+ static skipAuthorization(requset) {
6
+ requset.authorizationSkipPerformed = true;
7
+ }
8
+ static markAuthorized(request) {
9
+ request.authorizationCheckPerformed = true;
10
+ }
11
+ static failIfNotCoveredByAuthorization(request) {
12
+ if (!request.authorizationCheckPerformed && !request.authorizationSkipPerformed) {
13
+ throw 'Endpoint is not covered by authorization check';
14
+ }
15
+ }
16
+ }
17
+ exports.AuthorizationInternalService = AuthorizationInternalService;
@@ -0,0 +1,5 @@
1
+ import { NextFunction } from 'express';
2
+ import { Action, BaseRequest, BaseResponse, ContextGetter, ResourceGetter } from './types/general';
3
+ export declare function getAuthorizationMiddleware(action: Action, resourceGetter: ResourceGetter, contextGetter?: ContextGetter): (request: BaseRequest, response: BaseResponse, next: NextFunction) => Promise<void>;
4
+ export declare function skipAuthorizationMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
5
+ export declare function authorizationCheckMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
@@ -0,0 +1,54 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.authorizationCheckMiddleware = exports.skipAuthorizationMiddleware = exports.getAuthorizationMiddleware = void 0;
16
+ const on_headers_1 = __importDefault(require("on-headers"));
17
+ const authorization_internal_service_1 = require("./authorization-internal-service");
18
+ const authorization_service_1 = require("./authorization-service");
19
+ function getAuthorizationMiddleware(action, resourceGetter, contextGetter) {
20
+ return function authorizationMiddleware(request, response, next) {
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ contextGetter || (contextGetter = defaultContextGetter);
23
+ const { userId, accountId } = contextGetter(request);
24
+ const resources = resourceGetter(request);
25
+ const { isAuthorized } = yield authorization_service_1.AuthorizationService.isAuthorized(accountId, userId, resources, action);
26
+ authorization_internal_service_1.AuthorizationInternalService.markAuthorized(request);
27
+ if (!isAuthorized) {
28
+ response.status(403).json({ message: 'Access denied' });
29
+ return;
30
+ }
31
+ next();
32
+ });
33
+ };
34
+ }
35
+ exports.getAuthorizationMiddleware = getAuthorizationMiddleware;
36
+ function skipAuthorizationMiddleware(request, response, next) {
37
+ authorization_internal_service_1.AuthorizationInternalService.skipAuthorization(request);
38
+ next();
39
+ }
40
+ exports.skipAuthorizationMiddleware = skipAuthorizationMiddleware;
41
+ function authorizationCheckMiddleware(request, response, next) {
42
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
43
+ (0, on_headers_1.default)(response, function () {
44
+ if (response.statusCode < 400) {
45
+ authorization_internal_service_1.AuthorizationInternalService.failIfNotCoveredByAuthorization(request);
46
+ }
47
+ });
48
+ }
49
+ next();
50
+ }
51
+ exports.authorizationCheckMiddleware = authorizationCheckMiddleware;
52
+ function defaultContextGetter(request) {
53
+ return request.payload;
54
+ }
@@ -0,0 +1,28 @@
1
+ import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
2
+ import { Action, AuthorizationObject, Resource } from './types/general';
3
+ import { ScopedAction, ScopedActionPermit, ScopedActionResponseObject, ScopeOptions } from 'lib/types/scoped-actions-contracts';
4
+ export interface AuthorizeResponse {
5
+ isAuthorized: boolean;
6
+ unauthorizedIds?: number[];
7
+ }
8
+ export declare function setRequestFetchOptions(customMondayFetchOptions: MondayFetchOptions): void;
9
+ export declare function setRedisClient(client: any, grantedFeatureRedisExpirationInSeconds?: number): void;
10
+ export declare class AuthorizationService {
11
+ static redisClient?: any;
12
+ static grantedFeatureRedisExpirationInSeconds?: number;
13
+ /**
14
+ * @deprecated use the second form with authorizationRequestObjects instead,
15
+ * support of this function will be dropped gradually
16
+ */
17
+ static isAuthorized(accountId: number, userId: number, resources: Resource[], action: Action): Promise<AuthorizeResponse>;
18
+ static isAuthorized(accountId: number, userId: number, authorizationRequestObjects: AuthorizationObject[]): Promise<AuthorizeResponse>;
19
+ static isUserGrantedWithFeature(accountId: number, userId: number, featureName: string, options?: {
20
+ shouldSkipCache?: boolean;
21
+ }): Promise<boolean>;
22
+ private static fetchIsUserGrantedWithFeature;
23
+ private static getCachedKeyName;
24
+ static canActionInScope(accountId: number, userId: number, action: string, scope: ScopeOptions): Promise<ScopedActionPermit>;
25
+ static canActionInScopeMultiple(accountId: number, userId: number, scopedActions: ScopedAction[]): Promise<ScopedActionResponseObject[]>;
26
+ private static isAuthorizedSingular;
27
+ private static isAuthorizedMultiple;
28
+ }
@@ -0,0 +1,233 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.AuthorizationService = exports.setRedisClient = exports.setRequestFetchOptions = void 0;
36
+ const lodash_1 = require("lodash");
37
+ const perf_hooks_1 = require("perf_hooks");
38
+ const monday_jwt_1 = require("@mondaydotcomorg/monday-jwt");
39
+ const MondayLogger = __importStar(require("@mondaydotcomorg/monday-logger"));
40
+ const monday_fetch_1 = require("@mondaydotcomorg/monday-fetch");
41
+ const prometheus_service_1 = require("./prometheus-service");
42
+ const INTERNAL_APP_NAME = 'internal_ms';
43
+ const logger = MondayLogger.getLogger();
44
+ const GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS = 5 * 60;
45
+ const defaultMondayFetchOptions = {
46
+ retries: 3,
47
+ callback: logOnFetchFail,
48
+ };
49
+ let mondayFetchOptions = defaultMondayFetchOptions;
50
+ function setRequestFetchOptions(customMondayFetchOptions) {
51
+ mondayFetchOptions = Object.assign(Object.assign({}, defaultMondayFetchOptions), customMondayFetchOptions);
52
+ }
53
+ exports.setRequestFetchOptions = setRequestFetchOptions;
54
+ function setRedisClient(client, grantedFeatureRedisExpirationInSeconds = GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS) {
55
+ AuthorizationService.redisClient = client;
56
+ if (grantedFeatureRedisExpirationInSeconds && grantedFeatureRedisExpirationInSeconds > 0) {
57
+ AuthorizationService.grantedFeatureRedisExpirationInSeconds = grantedFeatureRedisExpirationInSeconds;
58
+ }
59
+ else {
60
+ logger.warn({ grantedFeatureRedisExpirationInSeconds }, 'Invalid input for grantedFeatureRedisExpirationInSeconds, must be positive number. using default ttl.');
61
+ AuthorizationService.grantedFeatureRedisExpirationInSeconds = GRANTED_FEATURE_CACHE_EXPIRATION_SECONDS;
62
+ }
63
+ }
64
+ exports.setRedisClient = setRedisClient;
65
+ class AuthorizationService {
66
+ static isAuthorized(...args) {
67
+ return __awaiter(this, void 0, void 0, function* () {
68
+ if (args.length === 3) {
69
+ return this.isAuthorizedMultiple(args[0], args[1], args[2]);
70
+ }
71
+ else if (args.length == 4) {
72
+ return this.isAuthorizedSingular(args[0], args[1], args[2], args[3]);
73
+ }
74
+ else {
75
+ throw new Error('isAuthorized accepts either 3 or 4 arguments');
76
+ }
77
+ });
78
+ }
79
+ static isUserGrantedWithFeature(accountId, userId, featureName, options = {}) {
80
+ var _a;
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ let cachedKey = this.getCachedKeyName(userId, featureName);
83
+ const shouldSkipCache = (_a = options.shouldSkipCache) !== null && _a !== void 0 ? _a : false;
84
+ if (this.redisClient && !shouldSkipCache) {
85
+ let grantedFeatureValue = yield this.redisClient.get(cachedKey);
86
+ if (!(grantedFeatureValue === undefined || grantedFeatureValue === null)) {
87
+ // redis returns the value as string
88
+ return grantedFeatureValue === 'true';
89
+ }
90
+ }
91
+ let grantedFeatureValue = yield this.fetchIsUserGrantedWithFeature(featureName, accountId, userId);
92
+ if (this.redisClient) {
93
+ yield this.redisClient.set(cachedKey, grantedFeatureValue, 'EX', this.grantedFeatureRedisExpirationInSeconds);
94
+ }
95
+ return grantedFeatureValue;
96
+ });
97
+ }
98
+ static fetchIsUserGrantedWithFeature(featureName, accountId, userId) {
99
+ return __awaiter(this, void 0, void 0, function* () {
100
+ let authorizationObject = {
101
+ action: featureName,
102
+ resource_type: 'feature',
103
+ };
104
+ let authorizeResponsePromise = yield this.isAuthorized(accountId, userId, [authorizationObject]);
105
+ return authorizeResponsePromise.isAuthorized;
106
+ });
107
+ }
108
+ static getCachedKeyName(userId, featureName) {
109
+ return `granted-feature-${featureName}-${userId}`;
110
+ }
111
+ static canActionInScope(accountId, userId, action, scope) {
112
+ return __awaiter(this, void 0, void 0, function* () {
113
+ const scopedActions = [{ action, scope }];
114
+ const scopedActionResponseObjects = yield this.canActionInScopeMultiple(accountId, userId, scopedActions);
115
+ return scopedActionResponseObjects[0].permit;
116
+ });
117
+ }
118
+ static canActionInScopeMultiple(accountId, userId, scopedActions) {
119
+ return __awaiter(this, void 0, void 0, function* () {
120
+ const internalAuthToken = (0, monday_jwt_1.signAuthorizationHeader)({ appName: INTERNAL_APP_NAME, accountId, userId });
121
+ const scopedActionsPayload = scopedActions.map(scopedAction => {
122
+ return Object.assign(Object.assign({}, scopedAction), { scope: (0, lodash_1.mapKeys)(scopedAction.scope, (_, key) => (0, lodash_1.snakeCase)(key)) }); // for example: { workspaceId: 1 } => { workspace_id: 1 }
123
+ });
124
+ const response = yield (0, monday_fetch_1.fetch)(getCanActionsInScopesUrl(), {
125
+ method: 'POST',
126
+ headers: { Authorization: internalAuthToken, 'Content-Type': 'application/json' },
127
+ timeout: getRequestTimeout(),
128
+ body: JSON.stringify({
129
+ user_id: userId,
130
+ scoped_actions: scopedActionsPayload,
131
+ }),
132
+ }, mondayFetchOptions);
133
+ throwOnHttpErrorIfNeeded(response, 'canActionInScopeMultiple');
134
+ const responseBody = yield response.json();
135
+ const camelCaseKeys = (obj) => Object.fromEntries(Object.entries(obj).map(([key, value]) => [(0, lodash_1.camelCase)(key), value]));
136
+ const scopedActionsResponseObjects = responseBody.result.map(responseObject => {
137
+ const { scopedAction, permit } = responseObject;
138
+ const { scope } = scopedAction;
139
+ const transformKeys = (obj) => camelCaseKeys(obj);
140
+ return Object.assign(Object.assign({}, responseObject), { scopedAction: Object.assign(Object.assign({}, scopedAction), { scope: transformKeys(scope) }), permit: transformKeys(permit) });
141
+ });
142
+ return scopedActionsResponseObjects;
143
+ });
144
+ }
145
+ static isAuthorizedSingular(accountId, userId, resources, action) {
146
+ return __awaiter(this, void 0, void 0, function* () {
147
+ const { authorizationObjects } = createAuthorizationParams(resources, action);
148
+ return this.isAuthorizedMultiple(accountId, userId, authorizationObjects);
149
+ });
150
+ }
151
+ static isAuthorizedMultiple(accountId, userId, authorizationRequestObjects) {
152
+ return __awaiter(this, void 0, void 0, function* () {
153
+ const internalAuthToken = (0, monday_jwt_1.signAuthorizationHeader)({ appName: INTERNAL_APP_NAME, accountId, userId });
154
+ const startTime = perf_hooks_1.performance.now();
155
+ const response = yield (0, monday_fetch_1.fetch)(getAuthorizeUrl(), {
156
+ method: 'POST',
157
+ headers: { Authorization: internalAuthToken, 'Content-Type': 'application/json' },
158
+ timeout: getRequestTimeout(),
159
+ body: JSON.stringify({
160
+ user_id: userId,
161
+ authorize_request_objects: authorizationRequestObjects,
162
+ }),
163
+ }, mondayFetchOptions);
164
+ const endTime = perf_hooks_1.performance.now();
165
+ const time = endTime - startTime;
166
+ const responseStatus = response.status;
167
+ (0, prometheus_service_1.sendAuthorizationChecksPerRequestMetric)(responseStatus, authorizationRequestObjects.length);
168
+ throwOnHttpErrorIfNeeded(response, 'isAuthorizedMultiple');
169
+ const responseBody = yield response.json();
170
+ const unauthorizedObjects = [];
171
+ responseBody.result.forEach(function (isAuthorized, index) {
172
+ const authorizationObject = authorizationRequestObjects[index];
173
+ if (!isAuthorized) {
174
+ unauthorizedObjects.push(authorizationObject);
175
+ }
176
+ (0, prometheus_service_1.sendAuthorizationCheckResponseTimeMetric)(authorizationObject.resource_type, authorizationObject.action, isAuthorized, responseStatus, time);
177
+ });
178
+ if (unauthorizedObjects.length > 0) {
179
+ logger.info({
180
+ resources: JSON.stringify(unauthorizedObjects),
181
+ }, 'AuthorizationService: resource is unauthorized');
182
+ const unauthorizedIds = unauthorizedObjects
183
+ .filter(obj => !!obj.resource_id)
184
+ .map(obj => obj.resource_id);
185
+ return { isAuthorized: false, unauthorizedIds };
186
+ }
187
+ return { isAuthorized: true };
188
+ });
189
+ }
190
+ }
191
+ exports.AuthorizationService = AuthorizationService;
192
+ function createAuthorizationParams(resources, action) {
193
+ const params = {
194
+ authorizationObjects: resources.map((resource) => {
195
+ const authorizationObject = {
196
+ resource_id: resource.id,
197
+ resource_type: resource.type,
198
+ action,
199
+ };
200
+ if (resource.wrapperData) {
201
+ authorizationObject.wrapper_data = resource.wrapperData;
202
+ }
203
+ return authorizationObject;
204
+ }),
205
+ };
206
+ return params;
207
+ }
208
+ function logOnFetchFail(retriesLeft, error) {
209
+ if (retriesLeft == 0) {
210
+ logger.error({ retriesLeft, error }, 'Authorization attempt failed due to network issues');
211
+ }
212
+ else {
213
+ logger.info({ retriesLeft, error }, 'Authorization attempt failed due to network issues, trying again');
214
+ }
215
+ }
216
+ function getAuthorizeUrl() {
217
+ return `${process.env.MONDAY_INTERNAL_URL}/internal_ms/authorization/authorize`;
218
+ }
219
+ function getCanActionsInScopesUrl() {
220
+ return `${process.env.MONDAY_INTERNAL_URL}/internal_ms/authorization/can_actions_in_scopes`;
221
+ }
222
+ function getRequestTimeout() {
223
+ const isDevEnv = process.env.NODE_ENV === 'development';
224
+ return isDevEnv ? 60000 : 2000;
225
+ }
226
+ function throwOnHttpErrorIfNeeded(response, placement) {
227
+ if (response.ok) {
228
+ return;
229
+ }
230
+ const status = response.status;
231
+ logger.error({ tag: 'authorization-service', placement, status }, 'AuthorizationService: authorization request failed');
232
+ throw new Error(`AuthorizationService: [${placement}] authorization request failed with status ${status}`);
233
+ }
@@ -0,0 +1,10 @@
1
+ import { Action } from './types/general';
2
+ export declare const METRICS: {
3
+ AUTHORIZATION_CHECK: string;
4
+ AUTHORIZATION_CHECKS_PER_REQUEST: string;
5
+ AUTHORIZATION_CHECK_RESPONSE_TIME: string;
6
+ };
7
+ export declare function setPrometheus(customPrometheus: any): void;
8
+ export declare function getMetricsManager(): any;
9
+ export declare function sendAuthorizationChecksPerRequestMetric(responseStatus: any, amountOfAuthorizationObjects: any): void;
10
+ export declare function sendAuthorizationCheckResponseTimeMetric(resourceType: string, action: Action, isAuthorized: boolean, responseStatus: number, time: number): void;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendAuthorizationCheckResponseTimeMetric = exports.sendAuthorizationChecksPerRequestMetric = exports.getMetricsManager = exports.setPrometheus = exports.METRICS = void 0;
4
+ let prometheus = null;
5
+ let authorizationChecksPerRequestMetric = null;
6
+ let authorizationCheckResponseTimeMetric = null;
7
+ exports.METRICS = {
8
+ AUTHORIZATION_CHECK: 'authorization_check',
9
+ AUTHORIZATION_CHECKS_PER_REQUEST: 'authorization_checks_per_request',
10
+ AUTHORIZATION_CHECK_RESPONSE_TIME: 'authorization_check_response_time',
11
+ };
12
+ const authorizationChecksPerRequestMetricConfig = {
13
+ name: exports.METRICS.AUTHORIZATION_CHECKS_PER_REQUEST,
14
+ labels: ['responseStatus'],
15
+ description: 'Authorization checks per request summary',
16
+ };
17
+ const authorizationCheckResponseTimeMetricConfig = {
18
+ name: exports.METRICS.AUTHORIZATION_CHECK_RESPONSE_TIME,
19
+ labels: ['resourceType', 'action', 'isAuthorized', 'responseStatus'],
20
+ description: 'Authorization check response time summary',
21
+ };
22
+ function setPrometheus(customPrometheus) {
23
+ prometheus = customPrometheus;
24
+ const { METRICS_TYPES } = prometheus;
25
+ authorizationChecksPerRequestMetric = getMetricsManager().addMetric(METRICS_TYPES.SUMMARY, authorizationChecksPerRequestMetricConfig.name, authorizationChecksPerRequestMetricConfig.labels, authorizationChecksPerRequestMetricConfig.description);
26
+ authorizationCheckResponseTimeMetric = getMetricsManager().addMetric(METRICS_TYPES.SUMMARY, authorizationCheckResponseTimeMetricConfig.name, authorizationCheckResponseTimeMetricConfig.labels, authorizationCheckResponseTimeMetricConfig.description);
27
+ }
28
+ exports.setPrometheus = setPrometheus;
29
+ function getMetricsManager() {
30
+ return prometheus === null || prometheus === void 0 ? void 0 : prometheus.metricsManager;
31
+ }
32
+ exports.getMetricsManager = getMetricsManager;
33
+ function sendAuthorizationChecksPerRequestMetric(responseStatus, amountOfAuthorizationObjects) {
34
+ try {
35
+ if (authorizationChecksPerRequestMetric) {
36
+ authorizationChecksPerRequestMetric.labels(responseStatus).observe(amountOfAuthorizationObjects);
37
+ }
38
+ }
39
+ catch (e) { }
40
+ }
41
+ exports.sendAuthorizationChecksPerRequestMetric = sendAuthorizationChecksPerRequestMetric;
42
+ function sendAuthorizationCheckResponseTimeMetric(resourceType, action, isAuthorized, responseStatus, time) {
43
+ try {
44
+ if (authorizationCheckResponseTimeMetric) {
45
+ authorizationCheckResponseTimeMetric.labels(resourceType, action, isAuthorized, responseStatus).observe(time);
46
+ }
47
+ }
48
+ catch (e) { }
49
+ }
50
+ exports.sendAuthorizationCheckResponseTimeMetric = sendAuthorizationCheckResponseTimeMetric;
@@ -0,0 +1,10 @@
1
+ declare namespace Express {
2
+ interface Request {
3
+ payload: {
4
+ accountId: number;
5
+ userId: number;
6
+ };
7
+ authorizationCheckPerformed: boolean;
8
+ authorizationSkipPerformed: boolean;
9
+ }
10
+ }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,30 @@
1
+ import { Request, Response } from 'express';
2
+ export interface Resource {
3
+ id?: number;
4
+ type: string;
5
+ wrapperData?: object;
6
+ }
7
+ export type Action = string;
8
+ export type ResourceGetter = (request: BaseRequest) => Resource[];
9
+ export interface Context {
10
+ accountId: number;
11
+ userId: number;
12
+ }
13
+ export type ContextGetter = (request: BaseRequest) => Context;
14
+ export interface AuthorizationObject {
15
+ resource_id?: Resource['id'];
16
+ resource_type: Resource['type'];
17
+ wrapper_data?: Resource['wrapperData'];
18
+ action: Action;
19
+ }
20
+ export interface AuthorizationParams {
21
+ authorizationObjects: AuthorizationObject[];
22
+ }
23
+ type BasicObject = {};
24
+ export type BaseParameters = BasicObject;
25
+ export type BaseResponseBody = BasicObject;
26
+ export type BaseBodyParameters = BasicObject;
27
+ export type BaseQueryParameters = BasicObject;
28
+ export type BaseRequest = Request<BaseParameters, BaseResponseBody, BaseBodyParameters, BaseQueryParameters>;
29
+ export type BaseResponse = Response<BaseResponseBody>;
30
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,38 @@
1
+ export interface WorkspaceScope {
2
+ workspaceId: number;
3
+ }
4
+ export interface BoardScope {
5
+ boardId: number;
6
+ }
7
+ export interface PulseScope {
8
+ pulseId: number;
9
+ }
10
+ export interface AccountProductScope {
11
+ accountProductId: number;
12
+ }
13
+ export interface AccountScope {
14
+ accountId: number;
15
+ }
16
+ export type ScopeOptions = WorkspaceScope | BoardScope | PulseScope | AccountProductScope | AccountScope;
17
+ export interface Translation {
18
+ key: string;
19
+ [option: string]: string;
20
+ }
21
+ export declare enum PermitTechnicalReason {
22
+ NO_REASON = 0,
23
+ NOT_ELIGIBLE = 1,
24
+ BY_ROLE_IN_SCOPE = 2
25
+ }
26
+ export interface ScopedActionPermit {
27
+ can: boolean;
28
+ reason: Translation;
29
+ technicalReason: PermitTechnicalReason;
30
+ }
31
+ export interface ScopedAction {
32
+ action: string;
33
+ scope: ScopeOptions;
34
+ }
35
+ export interface ScopedActionResponseObject {
36
+ scopedAction: ScopedAction;
37
+ permit: ScopedActionPermit;
38
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PermitTechnicalReason = void 0;
4
+ var PermitTechnicalReason;
5
+ (function (PermitTechnicalReason) {
6
+ PermitTechnicalReason[PermitTechnicalReason["NO_REASON"] = 0] = "NO_REASON";
7
+ PermitTechnicalReason[PermitTechnicalReason["NOT_ELIGIBLE"] = 1] = "NOT_ELIGIBLE";
8
+ PermitTechnicalReason[PermitTechnicalReason["BY_ROLE_IN_SCOPE"] = 2] = "BY_ROLE_IN_SCOPE";
9
+ })(PermitTechnicalReason || (exports.PermitTechnicalReason = PermitTechnicalReason = {}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mondaydotcomorg/monday-authorization",
3
- "version": "1.1.9-featurefilipmcipher-core-flags-client.2760+996328beb",
3
+ "version": "1.1.9-featureliorshonehourjwttoken.465+164eb3b11",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "BSD-3-Clause",
@@ -10,11 +10,9 @@
10
10
  },
11
11
  "dependencies": {
12
12
  "@mondaydotcomorg/monday-fetch": "^0.0.7",
13
- "@mondaydotcomorg/monday-jwt": "^3.0.14",
14
- "@mondaydotcomorg/monday-logger": "^4.0.11",
15
- "@mondaydotcomorg/trident-backend-api": "^0.23.10",
13
+ "@mondaydotcomorg/monday-jwt": "^3.0.9-featureliorshonehourjwttoken.465+164eb3b11",
14
+ "@mondaydotcomorg/monday-logger": "^3.0.10",
16
15
  "node-fetch": "^2.6.7",
17
- "on-headers": "^1.0.2",
18
16
  "ts-node": "^10.0.0"
19
17
  },
20
18
  "devDependencies": {
@@ -26,6 +24,7 @@
26
24
  "ioredis": "^5.2.4",
27
25
  "ioredis-mock": "^8.2.2",
28
26
  "mocha": "^9.0.1",
27
+ "on-headers": "^1.0.2",
29
28
  "supertest": "^6.1.3",
30
29
  "tsconfig-paths": "^3.9.0",
31
30
  "typescript": "^5.1.6"
@@ -33,5 +32,5 @@
33
32
  "files": [
34
33
  "dist/"
35
34
  ],
36
- "gitHead": "996328beba873d81b9dd60aa3273d807a0a57244"
35
+ "gitHead": "164eb3b11392586ed8175eaa15ec61c914a85234"
37
36
  }