@mondaydotcomorg/monday-authorization 1.1.9-featuremosheauthorizationesm.3695 → 1.1.9-featureorcomonday-jwt-ts.472
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -15
- package/README.md +0 -57
- package/dist/index.d.ts +2 -5
- package/dist/index.js +14 -18
- package/dist/lib/authorization-internal-service.d.ts +6 -0
- package/dist/lib/authorization-internal-service.js +17 -0
- package/dist/{authorization-middleware.d.ts → lib/authorization-middleware.d.ts} +1 -2
- package/dist/lib/authorization-middleware.js +54 -0
- package/dist/{authorization-service.d.ts → lib/authorization-service.d.ts} +1 -2
- package/dist/lib/authorization-service.js +233 -0
- package/dist/{prometheus-service.js → lib/prometheus-service.js} +10 -11
- package/dist/lib/types/express.js +1 -0
- package/dist/lib/types/general.js +2 -0
- package/dist/{types → lib/types}/scoped-actions-contracts.js +4 -3
- package/package.json +7 -30
- package/dist/attributions-service.d.ts +0 -3
- package/dist/attributions-service.js +0 -55
- package/dist/authorization-attributes-service.d.ts +0 -44
- package/dist/authorization-attributes-service.js +0 -144
- package/dist/authorization-internal-service.d.ts +0 -13
- package/dist/authorization-internal-service.js +0 -80
- package/dist/authorization-middleware.js +0 -48
- package/dist/authorization-service.js +0 -176
- package/dist/constants/sns.d.ts +0 -3
- package/dist/constants/sns.js +0 -9
- package/dist/esm/attributions-service.d.ts +0 -3
- package/dist/esm/attributions-service.mjs +0 -53
- package/dist/esm/authorization-attributes-service.d.ts +0 -44
- package/dist/esm/authorization-attributes-service.mjs +0 -138
- package/dist/esm/authorization-internal-service.d.ts +0 -13
- package/dist/esm/authorization-internal-service.mjs +0 -57
- package/dist/esm/authorization-middleware.d.ts +0 -6
- package/dist/esm/authorization-middleware.mjs +0 -39
- package/dist/esm/authorization-service.d.ts +0 -29
- package/dist/esm/authorization-service.mjs +0 -172
- package/dist/esm/constants/sns.d.ts +0 -3
- package/dist/esm/constants/sns.mjs +0 -5
- package/dist/esm/index.d.ts +0 -13
- package/dist/esm/index.mjs +0 -21
- package/dist/esm/prometheus-service.mjs +0 -45
- package/dist/esm/testKit/index.d.ts +0 -11
- package/dist/esm/testKit/index.mjs +0 -44
- package/dist/esm/types/authorization-attributes-contracts.d.ts +0 -27
- package/dist/esm/types/authorization-attributes-contracts.mjs +0 -7
- package/dist/esm/types/express.mjs +0 -1
- package/dist/esm/types/general.mjs +0 -1
- package/dist/esm/types/scoped-actions-contracts.mjs +0 -8
- package/dist/prometheus-service.d.ts +0 -10
- package/dist/testKit/index.d.ts +0 -11
- package/dist/testKit/index.js +0 -48
- package/dist/types/authorization-attributes-contracts.d.ts +0 -27
- package/dist/types/authorization-attributes-contracts.js +0 -7
- package/dist/types/express.d.ts +0 -10
- package/dist/types/express.js +0 -1
- package/dist/types/general.d.ts +0 -30
- package/dist/types/general.js +0 -1
- package/dist/types/scoped-actions-contracts.d.ts +0 -38
- /package/dist/{esm → lib}/prometheus-service.d.ts +0 -0
- /package/dist/{esm → lib}/types/express.d.ts +0 -0
- /package/dist/{esm → lib}/types/general.d.ts +0 -0
- /package/dist/{esm → lib}/types/scoped-actions-contracts.d.ts +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,21 +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.9] - 2024-10-06
|
|
9
|
-
### Added
|
|
10
|
-
- [`authz/bashanye/add-async-resource-attributes-support`](https://github.com/DaPulse/monday-npm-packages/pull/6859)
|
|
11
|
-
- `AuthorizationAttributesService` - now supports async upsert and delete - requests sent through SNS-SQS).
|
|
12
|
-
|
|
13
|
-
## [1.2.3] - 2024-06-10
|
|
14
|
-
### Added
|
|
15
|
-
|
|
16
|
-
- [`feature/yarden/resource-attributes-api-support-authz-sdk (#5826)`](https://github.com/DaPulse/monday-npm-packages/pull/5826)
|
|
17
|
-
- `AuthorizationAttributesService` - now supports upsert (`upsertResourceAttributesSync`) and delete (`deleteResourceAttributesSync`) resource attributes in the authorization MS
|
|
18
|
-
|
|
19
|
-
## [1.2.0] - 2024-01-05
|
|
20
|
-
### Added
|
|
21
|
-
- `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.)
|
|
22
|
-
|
|
23
8
|
## [1.1.0] - 2023-08-09
|
|
24
9
|
|
|
25
10
|
### ⚠ BREAKING CHANGES
|
package/README.md
CHANGED
|
@@ -136,60 +136,3 @@ const canActionInScopeMultipleResponse: ScopedActionResponseObject[] =
|
|
|
136
136
|
* ]
|
|
137
137
|
* /
|
|
138
138
|
```
|
|
139
|
-
|
|
140
|
-
### Authorization Attributes API
|
|
141
|
-
Authorization attributes have 2 options to get called: sync (http request) and async (send to SNS and consumed asynchronously).
|
|
142
|
-
When you have to make sure the change in the attributes applied before the function return, please use the sync method, otherwise use the async
|
|
143
|
-
|
|
144
|
-
#### Sync method
|
|
145
|
-
Use `AuthorizationAttributesService.upsertResourceAttributesSync` to upsert multiple resource attributes in the authorization MS synchronously.
|
|
146
|
-
|
|
147
|
-
```ts
|
|
148
|
-
import { AuthorizationAttributesService, ResourceAttributeAssignment, ResourceAttributeResponse } from '@mondaydotcomorg/monday-authorization';
|
|
149
|
-
|
|
150
|
-
const accountId = 739630;
|
|
151
|
-
const userId = 4;
|
|
152
|
-
const resourceAttributesAssignments: ResourceAttributeAssignment[] = [
|
|
153
|
-
{ resourceId: 18, resourceType: 'workspace', key: 'is_default_workspace', value: 'true' },
|
|
154
|
-
{ resourceId: 23, resourceType: 'board', key: 'board_kind', value: 'private' }
|
|
155
|
-
];
|
|
156
|
-
|
|
157
|
-
const response: ResourceAttributeResponse = await AuthorizationAttributesService.upsertResourceAttributesSync(accountId, userId, resourceAttributesAssignments);
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
Use `AuthorizationAttributesService.deleteResourceAttributesSync` to delete single resource's attributes in the authorization MS synchronously.
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
```ts
|
|
164
|
-
import { AuthorizationAttributesService, ResourceAttributeResponse, Resource } from '@mondaydotcomorg/monday-authorization';
|
|
165
|
-
|
|
166
|
-
const accountId = 739630;
|
|
167
|
-
const userId = 4;
|
|
168
|
-
const resource: Resource = { type: 'workspace', id: 18 };
|
|
169
|
-
const attributeKeys: string[] = ['is_default_workspace', 'workspace_kind'];
|
|
170
|
-
|
|
171
|
-
const response: ResourceAttributeResponse = await AuthorizationAttributesService.deleteResourceAttributesSync(accountId, userId, resource, attributeKeys);
|
|
172
|
-
```
|
|
173
|
-
|
|
174
|
-
#### Async method
|
|
175
|
-
use `AuthorizationAttributesService.updateResourceAttributesAsync` to upsert or delete multiple resource attributes at once.
|
|
176
|
-
|
|
177
|
-
```ts
|
|
178
|
-
import { AuthorizationAttributesService, ResourceAttributeAssignment, ResourceAttributeResponse } from '@mondaydotcomorg/monday-authorization';
|
|
179
|
-
|
|
180
|
-
const accountId = 739630;
|
|
181
|
-
const appName = process.env.APP_NAME;
|
|
182
|
-
const callerActionIdentifier = "actions_v2";
|
|
183
|
-
const resourceAttributeOperations: ResourceAttributesOperation[] = [
|
|
184
|
-
{ operationType: 'upsert', resourceId: 18, resourceType: 'workspace', key: 'is_default_workspace', value: 'true' },
|
|
185
|
-
{ operationType: 'delete', resourceId: 23, resourceType: 'board', key: 'board_kind' }
|
|
186
|
-
];
|
|
187
|
-
|
|
188
|
-
const response: ResourceAttributeResponse = await AuthorizationAttributesService.updateResourceAttributesAsync(accountId, appName, callerActionIdentifier, resourceAttributeOperations);
|
|
189
|
-
```
|
|
190
|
-
|
|
191
|
-
Special notes for asynchronous operations:
|
|
192
|
-
1. There is no guarantee about the order of the updates, so don't do multiple operations on the same key in the same resource.
|
|
193
|
-
2. To update an existing key, just use upsert operation, it'll override previous value.
|
|
194
|
-
3. Requests with a lot of operations might split to chunks that will be consumed either sequence or in parallel, so there might be a timeframe where some of the operations already applied and some not. Eventually all of them will be applied.
|
|
195
|
-
4. If your MS depends on the access to the asynchronous operation, you can use a health check operation `asyncResourceAttributesHealthCheck` that will return false if it can't reach to SNS or can't find the required topic. Note it doesn't check write permissions so make sure your MS have permissions to write to the SNS topic.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
|
|
2
|
-
import * as TestKit from './testKit';
|
|
3
2
|
export interface InitOptions {
|
|
4
3
|
prometheus?: any;
|
|
5
4
|
mondayFetchOptions?: MondayFetchOptions;
|
|
@@ -7,7 +6,5 @@ export interface InitOptions {
|
|
|
7
6
|
grantedFeatureRedisExpirationInSeconds?: number;
|
|
8
7
|
}
|
|
9
8
|
export declare function init(options?: InitOptions): void;
|
|
10
|
-
export { authorizationCheckMiddleware, getAuthorizationMiddleware, skipAuthorizationMiddleware, } from './authorization-middleware';
|
|
11
|
-
export { AuthorizationService } from './authorization-service';
|
|
12
|
-
export { AuthorizationAttributesService } from './authorization-attributes-service';
|
|
13
|
-
export { TestKit };
|
|
9
|
+
export { authorizationCheckMiddleware, getAuthorizationMiddleware, skipAuthorizationMiddleware, } from './lib/authorization-middleware';
|
|
10
|
+
export { AuthorizationService } from './lib/authorization-service';
|
package/dist/index.js
CHANGED
|
@@ -1,27 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
const
|
|
5
|
-
const
|
|
6
|
-
const authorizationMiddleware = require('./authorization-middleware.js');
|
|
7
|
-
const authorizationAttributesService = require('./authorization-attributes-service.js');
|
|
8
|
-
|
|
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");
|
|
9
6
|
function init(options = {}) {
|
|
10
7
|
if (options.prometheus) {
|
|
11
|
-
|
|
8
|
+
(0, prometheus_service_1.setPrometheus)(options.prometheus);
|
|
12
9
|
}
|
|
13
10
|
if (options.mondayFetchOptions) {
|
|
14
|
-
|
|
11
|
+
(0, authorization_service_1.setRequestFetchOptions)(options.mondayFetchOptions);
|
|
15
12
|
}
|
|
16
13
|
if (options.redisClient) {
|
|
17
|
-
|
|
14
|
+
(0, authorization_service_1.setRedisClient)(options.redisClient, options.grantedFeatureRedisExpirationInSeconds);
|
|
18
15
|
}
|
|
19
16
|
}
|
|
20
|
-
|
|
21
|
-
exports.AuthorizationService = authorizationService.AuthorizationService;
|
|
22
|
-
exports.TestKit = testKit_index;
|
|
23
|
-
exports.authorizationCheckMiddleware = authorizationMiddleware.authorizationCheckMiddleware;
|
|
24
|
-
exports.getAuthorizationMiddleware = authorizationMiddleware.getAuthorizationMiddleware;
|
|
25
|
-
exports.skipAuthorizationMiddleware = authorizationMiddleware.skipAuthorizationMiddleware;
|
|
26
|
-
exports.AuthorizationAttributesService = authorizationAttributesService.AuthorizationAttributesService;
|
|
27
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,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;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { NextFunction } from 'express';
|
|
2
|
-
import { Action, BaseRequest, BaseResponse,
|
|
2
|
+
import { Action, BaseRequest, BaseResponse, ContextGetter, ResourceGetter } from './types/general';
|
|
3
3
|
export declare function getAuthorizationMiddleware(action: Action, resourceGetter: ResourceGetter, contextGetter?: ContextGetter): (request: BaseRequest, response: BaseResponse, next: NextFunction) => Promise<void>;
|
|
4
4
|
export declare function skipAuthorizationMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
|
|
5
5
|
export declare function authorizationCheckMiddleware(request: BaseRequest, response: BaseResponse, next: NextFunction): void;
|
|
6
|
-
export declare function defaultContextGetter(request: BaseRequest): Context;
|
|
@@ -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
|
+
}
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { MondayFetchOptions } from '@mondaydotcomorg/monday-fetch';
|
|
2
2
|
import { Action, AuthorizationObject, Resource } from './types/general';
|
|
3
|
-
import { ScopedAction, ScopedActionPermit, ScopedActionResponseObject, ScopeOptions } from '
|
|
3
|
+
import { ScopedAction, ScopedActionPermit, ScopedActionResponseObject, ScopeOptions } from 'lib/types/scoped-actions-contracts';
|
|
4
4
|
export interface AuthorizeResponse {
|
|
5
5
|
isAuthorized: boolean;
|
|
6
6
|
unauthorizedIds?: number[];
|
|
7
|
-
unauthorizedObjects?: AuthorizationObject[];
|
|
8
7
|
}
|
|
9
8
|
export declare function setRequestFetchOptions(customMondayFetchOptions: MondayFetchOptions): void;
|
|
10
9
|
export declare function setRedisClient(client: any, grantedFeatureRedisExpirationInSeconds?: number): void;
|
|
@@ -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
|
+
}
|
|
@@ -1,20 +1,21 @@
|
|
|
1
|
-
|
|
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
|
-
|
|
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,9 +25,11 @@ 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
|
|
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) {
|
|
@@ -35,6 +38,7 @@ function sendAuthorizationChecksPerRequestMetric(responseStatus, amountOfAuthori
|
|
|
35
38
|
}
|
|
36
39
|
catch (e) { }
|
|
37
40
|
}
|
|
41
|
+
exports.sendAuthorizationChecksPerRequestMetric = sendAuthorizationChecksPerRequestMetric;
|
|
38
42
|
function sendAuthorizationCheckResponseTimeMetric(resourceType, action, isAuthorized, responseStatus, time) {
|
|
39
43
|
try {
|
|
40
44
|
if (authorizationCheckResponseTimeMetric) {
|
|
@@ -43,9 +47,4 @@ function sendAuthorizationCheckResponseTimeMetric(resourceType, action, isAuthor
|
|
|
43
47
|
}
|
|
44
48
|
catch (e) { }
|
|
45
49
|
}
|
|
46
|
-
|
|
47
|
-
exports.METRICS = METRICS;
|
|
48
|
-
exports.getMetricsManager = getMetricsManager;
|
|
49
50
|
exports.sendAuthorizationCheckResponseTimeMetric = sendAuthorizationCheckResponseTimeMetric;
|
|
50
|
-
exports.sendAuthorizationChecksPerRequestMetric = sendAuthorizationChecksPerRequestMetric;
|
|
51
|
-
exports.setPrometheus = setPrometheus;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
|
|
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
|
-
})(
|
|
9
|
+
})(PermitTechnicalReason || (exports.PermitTechnicalReason = PermitTechnicalReason = {}));
|
package/package.json
CHANGED
|
@@ -1,59 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mondaydotcomorg/monday-authorization",
|
|
3
|
-
"version": "1.1.9-
|
|
3
|
+
"version": "1.1.9-featureorcomonday-jwt-ts.472+0053951b7",
|
|
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": "
|
|
17
|
-
"
|
|
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.
|
|
24
|
-
"@mondaydotcomorg/monday-logger": "^
|
|
25
|
-
"@mondaydotcomorg/monday-sns": "^1.0.6",
|
|
26
|
-
"@mondaydotcomorg/trident-backend-api": "^0.23.10",
|
|
27
|
-
"@types/lodash": "^4.17.10",
|
|
28
|
-
"lodash": "^4.17.21",
|
|
13
|
+
"@mondaydotcomorg/monday-jwt": "^3.0.9-featureorcomonday-jwt-ts.472+0053951b7",
|
|
14
|
+
"@mondaydotcomorg/monday-logger": "^3.0.10",
|
|
29
15
|
"node-fetch": "^2.6.7",
|
|
30
|
-
"on-headers": "^1.0.2",
|
|
31
16
|
"ts-node": "^10.0.0"
|
|
32
17
|
},
|
|
33
18
|
"devDependencies": {
|
|
34
|
-
"@mondaydotcomorg/trident-library": "^0.6.53",
|
|
35
19
|
"@types/express": "^4.17.20",
|
|
36
|
-
"@types/jest": "^27.4.1",
|
|
37
20
|
"@types/mocha": "^8.2.2",
|
|
38
21
|
"@types/on-headers": "^1.0.0",
|
|
39
22
|
"@types/supertest": "^2.0.11",
|
|
40
23
|
"express": "^4.17.1",
|
|
41
24
|
"ioredis": "^5.2.4",
|
|
42
25
|
"ioredis-mock": "^8.2.2",
|
|
43
|
-
"jest": "^27.5.1",
|
|
44
26
|
"mocha": "^9.0.1",
|
|
27
|
+
"on-headers": "^1.0.2",
|
|
45
28
|
"supertest": "^6.1.3",
|
|
46
|
-
"ts-jest": "^27.1.3",
|
|
47
29
|
"tsconfig-paths": "^3.9.0",
|
|
48
30
|
"typescript": "^5.1.6"
|
|
49
31
|
},
|
|
50
32
|
"files": [
|
|
51
33
|
"dist/"
|
|
52
34
|
],
|
|
53
|
-
"
|
|
54
|
-
"build": {
|
|
55
|
-
"esmMjsRename": true
|
|
56
|
-
}
|
|
57
|
-
},
|
|
58
|
-
"gitHead": "dabe70b1ee6b4bee07fdd8ca06eb4944d62a4c96"
|
|
35
|
+
"gitHead": "0053951b70f13ef040d8646d709dd3cdcce11168"
|
|
59
36
|
}
|