@mondaydotcomorg/monday-authorization 3.3.0-feature-bashanye-navigate-can-action-in-scope-to-graph-0a3cfd6 → 3.3.0-feature-bashanye-navigate-can-action-in-scope-to-graph-752f21a

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/DEBUG.md ADDED
@@ -0,0 +1,203 @@
1
+ # Debugging @mondaydotcomorg/monday-authorization
2
+
3
+ This guide explains how to debug the monday-authorization package when it's installed as a dependency in your project.
4
+
5
+ ## 🔧 Setup for Debugging
6
+
7
+ ### 1. Install the Package with Source Files
8
+
9
+ When you install the package, it includes both compiled JavaScript and TypeScript source files:
10
+
11
+ ```bash
12
+ npm install @mondaydotcomorg/monday-authorization
13
+ ```
14
+
15
+ The package includes:
16
+
17
+ - `dist/` - Compiled JavaScript with source maps
18
+ - `src/` - Original TypeScript source files
19
+
20
+ ### 2. Configure Your Debugger
21
+
22
+ #### VS Code Launch Configuration
23
+
24
+ Create a `.vscode/launch.json` file in your project:
25
+
26
+ ```json
27
+ {
28
+ "version": "0.2.0",
29
+ "configurations": [
30
+ {
31
+ "name": "Debug Authorization Package",
32
+ "type": "node",
33
+ "request": "launch",
34
+ "program": "${workspaceFolder}/your-main-file.js",
35
+ "sourceMaps": true,
36
+ "resolveSourceMapLocations": [
37
+ "${workspaceFolder}/**",
38
+ "!**/node_modules/**",
39
+ "**/node_modules/@mondaydotcomorg/monday-authorization/**"
40
+ ],
41
+ "skipFiles": ["<node_internals>/**", "node_modules/**"],
42
+ "outFiles": ["${workspaceFolder}/node_modules/@mondaydotcomorg/monday-authorization/dist/**/*.js"]
43
+ }
44
+ ]
45
+ }
46
+ ```
47
+
48
+ #### WebStorm/IntelliJ IDEA
49
+
50
+ 1. Go to `Run` → `Edit Configurations`
51
+ 2. Add a new `Node.js` configuration
52
+ 3. Set the JavaScript file to your main application file
53
+ 4. In the debugger settings, ensure source maps are enabled
54
+
55
+ ### 3. Enable Debug Logging
56
+
57
+ The package includes comprehensive debug logging. To see debug logs:
58
+
59
+ ```bash
60
+ # Set environment variable
61
+ export LOG_LEVEL=debug
62
+
63
+ # Or in your application
64
+ process.env.LOG_LEVEL = 'debug';
65
+ ```
66
+
67
+ ### 4. Breakpoints in Source Files
68
+
69
+ You can set breakpoints directly in the TypeScript source files:
70
+
71
+ 1. Open the source file: `node_modules/@mondaydotcomorg/monday-authorization/src/`
72
+ 2. Set breakpoints in the TypeScript code
73
+ 3. Your debugger should map them to the running JavaScript
74
+
75
+ ## 🔍 Debug Log Categories
76
+
77
+ The package logs debug information with these tags:
78
+
79
+ ### Authorization Service (`authorization-service`)
80
+
81
+ ```
82
+ 🔍 canActionInScopeMultiple called { accountId, userId, scopedActionsCount }
83
+ 📍 Graph API routing feature flag: ENABLED/DISABLED
84
+ 🎯 Attempting Graph API authorization
85
+ ✅ Graph API authorization successful
86
+ ❌ Graph API authorization failed, falling back to Platform API
87
+ 🔄 Using Platform API directly (Graph API FF disabled)
88
+ ```
89
+
90
+ ### Graph API Client (`graph-api-client`)
91
+
92
+ ```
93
+ 🔍 Graph API Debug: Starting request { scopedActionsCount, appName, path, timeout, bodyPayloadKeys }
94
+ ✅ Graph API Debug: Request successful { responseKeys, scopedActionsCount }
95
+ ❌ Graph API Debug: Request failed { error, status, scopedActionsCount }
96
+ ```
97
+
98
+ ### Platform API Client (`platform-api-client`)
99
+
100
+ ```
101
+ 🔍 Platform API Debug: Starting request { profile, userId, scopedActionsCount, appName, path }
102
+ ✅ Platform API Debug: Request successful { hasResult, resultCount }
103
+ ❌ Platform API Debug: Request failed { error, status, profile, userId }
104
+ ```
105
+
106
+ ### Authorization Utils (`authorization-utils`)
107
+
108
+ ```
109
+ 🔍 Utils Debug: Converting scope to resource { scopeKeys, scopeValues }
110
+ 🔍 Utils Debug: Mapped to workspace/board/pulse/etc { resourceId }
111
+ ❌ Utils Debug: Unsupported scope provided { scope }
112
+ ```
113
+
114
+ ## 🐛 Common Debugging Scenarios
115
+
116
+ ### Graph API 500 Errors
117
+
118
+ When you see Graph API failures, the logs will show:
119
+
120
+ 1. ✅ Feature flag status (enabled/disabled)
121
+ 2. 🎯 API attempt (Graph API first)
122
+ 3. ❌ Failure details (error message, status code)
123
+ 4. 🔄 Fallback trigger (automatic switch to Platform API)
124
+ 5. ✅ Fallback success (Platform API response)
125
+
126
+ ### Scope Mapping Issues
127
+
128
+ Debug logs show how scopes are converted to resources:
129
+
130
+ ```
131
+ 🔍 Utils Debug: Converting scope to resource { scopeKeys: ['boardId'], scopeValues: [123] }
132
+ 🔍 Utils Debug: Mapped to board { resourceId: 123 }
133
+ ```
134
+
135
+ ### Authorization Flow
136
+
137
+ Complete flow visibility:
138
+
139
+ 1. **Entry**: `canActionInScopeMultiple called`
140
+ 2. **Decision**: Feature flag check
141
+ 3. **Attempt**: API selection and request
142
+ 4. **Result**: Success/failure with details
143
+ 5. **Fallback**: Automatic recovery if needed
144
+
145
+ ## 📊 Source Maps
146
+
147
+ The package includes source maps for both:
148
+
149
+ - `dist/index.js.map` - Main CommonJS build
150
+ - `dist/esm/index.mjs.map` - ESM build
151
+
152
+ These allow your debugger to map the running JavaScript back to the original TypeScript source.
153
+
154
+ ## 🔧 Advanced Debugging
155
+
156
+ ### Custom Logger Configuration
157
+
158
+ ```typescript
159
+ import { logger } from '@mondaydotcomorg/monday-authorization/src/authorization-internal-service';
160
+
161
+ // Configure custom logging
162
+ logger.level = 'debug';
163
+ ```
164
+
165
+ ### Inspecting Authorization Objects
166
+
167
+ ```typescript
168
+ // Add this to your code to inspect authorization calls
169
+ import { AuthorizationService } from '@mondaydotcomorg/monday-authorization';
170
+
171
+ // Monkey patch for debugging
172
+ const originalCanActionInScopeMultiple = AuthorizationService.canActionInScopeMultiple;
173
+ AuthorizationService.canActionInScopeMultiple = async (...args) => {
174
+ console.log('🔍 Authorization call:', args);
175
+ const result = await originalCanActionInScopeMultiple.apply(AuthorizationService, args);
176
+ console.log('✅ Authorization result:', result);
177
+ return result;
178
+ };
179
+ ```
180
+
181
+ ## 📝 Troubleshooting
182
+
183
+ ### Breakpoints Not Working
184
+
185
+ 1. Ensure source maps are enabled in your debugger
186
+ 2. Check that `node_modules/@mondaydotcomorg/monday-authorization/src/` files are accessible
187
+ 3. Verify the source map files exist in `dist/`
188
+
189
+ ### Logs Not Showing
190
+
191
+ 1. Set `LOG_LEVEL=debug` environment variable
192
+ 2. Check that your logger configuration includes debug level
193
+ 3. Look for logs with tags: `authorization-service`, `graph-api-client`, `platform-api-client`, `authorization-utils`
194
+
195
+ ### Source Files Not Found
196
+
197
+ 1. Clear node_modules and reinstall the package
198
+ 2. Ensure the package version includes source files
199
+ 3. Check that `src/` directory exists in `node_modules/@mondaydotcomorg/monday-authorization/`
200
+
201
+ ---
202
+
203
+ With these debugging capabilities, you can fully inspect and understand the authorization flow in your applications! 🚀
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mondaydotcomorg/monday-authorization",
3
- "version": "3.3.0-feature-bashanye-navigate-can-action-in-scope-to-graph-0a3cfd6",
3
+ "version": "3.3.0-feature-bashanye-navigate-can-action-in-scope-to-graph-752f21a",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "BSD-3-Clause",
@@ -46,7 +46,9 @@
46
46
  "typescript": "^5.2.2"
47
47
  },
48
48
  "files": [
49
- "dist/"
49
+ "dist/",
50
+ "src/",
51
+ "DEBUG.md"
50
52
  ],
51
53
  "eslintConfig": {
52
54
  "extends": "@mondaydotcomorg/trident-library",
@@ -61,5 +63,8 @@
61
63
  "type": "git",
62
64
  "url": "https://github.com/DaPulse/authorization-domain.git",
63
65
  "directory": "packages/monday-authorization"
66
+ },
67
+ "publishConfig": {
68
+ "access": "public"
64
69
  }
65
70
  }
@@ -0,0 +1,92 @@
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
+ }
15
+
16
+ export function getProfile() {
17
+ const tridentContext = Api.getPart('context');
18
+ if (!tridentContext) {
19
+ return PlatformProfile.INTERNAL;
20
+ }
21
+ const { mondayRequestSource } = getExecutionContext(tridentContext);
22
+
23
+ switch (mondayRequestSource) {
24
+ case 'api': {
25
+ return PlatformProfile.API_INTERNAL;
26
+ }
27
+ case 'slow': {
28
+ return PlatformProfile.SLOW;
29
+ }
30
+ default:
31
+ return PlatformProfile.INTERNAL;
32
+ }
33
+ }
34
+
35
+ export function getExecutionContext(context: Context): ExecutionContext {
36
+ return context.execution.get();
37
+ }
38
+
39
+ export function getAttributionsFromApi(): { [key: string]: string } {
40
+ const callerAppNameFromSdk = {
41
+ [APP_NAME_HEADER_NAME]: tryJsonParse(getEnvVariable(APP_NAME_VARIABLE_KEY)),
42
+ };
43
+
44
+ try {
45
+ const tridentContext = Api.getPart('context');
46
+
47
+ if (!tridentContext) {
48
+ return callerAppNameFromSdk;
49
+ }
50
+
51
+ const { runtimeAttributions } = tridentContext;
52
+ const runtimeAttributionsOutgoingHeaders = runtimeAttributions?.buildOutgoingHeaders('HTTP_INTERNAL');
53
+
54
+ if (!runtimeAttributionsOutgoingHeaders) {
55
+ return callerAppNameFromSdk;
56
+ }
57
+
58
+ const attributionsHeaders = Object.fromEntries(runtimeAttributionsOutgoingHeaders);
59
+
60
+ const attributionHeadersFromSdk = {};
61
+ Object.keys(attributionsHeaders).forEach(function (key) {
62
+ attributionHeadersFromSdk[`${key}${FROM_SDK_HEADER_SUFFIX}`] = attributionsHeaders[key];
63
+ });
64
+
65
+ return attributionHeadersFromSdk;
66
+ } catch (error) {
67
+ if (!didSendFailureLogOnce) {
68
+ logger.warn(
69
+ { tag: 'authorization-service', error },
70
+ 'Failed to generate attributions headers from the API. Unexpected error while extracting headers. It may be caused by out of date Trident version.'
71
+ );
72
+ didSendFailureLogOnce = true;
73
+ }
74
+ return callerAppNameFromSdk;
75
+ }
76
+ }
77
+
78
+ function getEnvVariable(key: string) {
79
+ const envVar = process.env[key] || process.env[key.toUpperCase()] || process.env[key.toLowerCase()];
80
+ return envVar;
81
+ }
82
+
83
+ function tryJsonParse(value: string | undefined) {
84
+ if (!value) {
85
+ return value;
86
+ }
87
+ try {
88
+ return JSON.parse(value);
89
+ } catch (_err) {
90
+ return value;
91
+ }
92
+ }
@@ -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
+ }