@app-connect/core 1.7.5 → 1.7.10
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/handlers/admin.js +29 -17
- package/handlers/auth.js +10 -4
- package/handlers/calldown.js +33 -0
- package/handlers/contact.js +54 -3
- package/handlers/log.js +4 -4
- package/index.js +377 -163
- package/lib/debugTracer.js +159 -0
- package/lib/oauth.js +26 -18
- package/lib/ringcentral.js +2 -2
- package/lib/s3ErrorLogReport.js +66 -0
- package/models/accountDataModel.js +34 -0
- package/package.json +70 -67
- package/releaseNotes.json +68 -0
- package/test/connector/registry.test.js +145 -0
- package/test/handlers/admin.test.js +583 -0
- package/test/handlers/auth.test.js +355 -0
- package/test/handlers/contact.test.js +852 -0
- package/test/handlers/log.test.js +868 -0
- package/test/lib/callLogComposer.test.js +1231 -0
- package/test/lib/debugTracer.test.js +328 -0
- package/test/lib/oauth.test.js +359 -0
- package/test/lib/ringcentral.test.js +473 -0
- package/test/lib/util.test.js +282 -0
- package/test/models/accountDataModel.test.js +98 -0
- package/test/models/dynamo/connectorSchema.test.js +189 -0
- package/test/models/models.test.js +539 -0
- package/test/setup.js +176 -176
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
const { DebugTracer } = require('../../lib/debugTracer');
|
|
2
|
+
|
|
3
|
+
describe('DebugTracer', () => {
|
|
4
|
+
let tracer;
|
|
5
|
+
|
|
6
|
+
beforeEach(() => {
|
|
7
|
+
tracer = new DebugTracer();
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
describe('constructor', () => {
|
|
11
|
+
test('should initialize with empty traces array', () => {
|
|
12
|
+
expect(tracer.traces).toEqual([]);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test('should set start time', () => {
|
|
16
|
+
expect(tracer.startTime).toBeDefined();
|
|
17
|
+
expect(typeof tracer.startTime).toBe('number');
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('should generate unique request ID', () => {
|
|
21
|
+
const tracer2 = new DebugTracer();
|
|
22
|
+
expect(tracer.requestId).toBeDefined();
|
|
23
|
+
expect(tracer.requestId).toMatch(/^req_\d+_[a-z0-9]+$/);
|
|
24
|
+
expect(tracer.requestId).not.toBe(tracer2.requestId);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('should accept headers parameter', () => {
|
|
28
|
+
const headers = { 'x-request-id': 'custom-id' };
|
|
29
|
+
const tracerWithHeaders = new DebugTracer(headers);
|
|
30
|
+
expect(tracerWithHeaders.requestId).toBeDefined();
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
describe('trace', () => {
|
|
35
|
+
test('should add trace entry with method name and data', () => {
|
|
36
|
+
tracer.trace('testMethod', { name: 'value', count: 42 });
|
|
37
|
+
|
|
38
|
+
expect(tracer.traces).toHaveLength(1);
|
|
39
|
+
expect(tracer.traces[0].methodName).toBe('testMethod');
|
|
40
|
+
expect(tracer.traces[0].data).toEqual({ name: 'value', count: 42 });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('should include timestamp and elapsed time', () => {
|
|
44
|
+
tracer.trace('testMethod', {});
|
|
45
|
+
|
|
46
|
+
expect(tracer.traces[0].timestamp).toBeDefined();
|
|
47
|
+
expect(tracer.traces[0].elapsed).toBeGreaterThanOrEqual(0);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('should default to info level', () => {
|
|
51
|
+
tracer.trace('testMethod', {});
|
|
52
|
+
|
|
53
|
+
expect(tracer.traces[0].level).toBe('info');
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('should allow custom log level', () => {
|
|
57
|
+
tracer.trace('testMethod', {}, { level: 'warn' });
|
|
58
|
+
|
|
59
|
+
expect(tracer.traces[0].level).toBe('warn');
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('should include stack trace by default', () => {
|
|
63
|
+
tracer.trace('testMethod', {});
|
|
64
|
+
|
|
65
|
+
expect(tracer.traces[0].stackTrace).toBeDefined();
|
|
66
|
+
expect(Array.isArray(tracer.traces[0].stackTrace)).toBe(true);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('should exclude stack trace when disabled', () => {
|
|
70
|
+
tracer.trace('testMethod', {}, { includeStack: false });
|
|
71
|
+
|
|
72
|
+
expect(tracer.traces[0].stackTrace).toBeUndefined();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test('should return this for chaining', () => {
|
|
76
|
+
const result = tracer.trace('method1', {});
|
|
77
|
+
expect(result).toBe(tracer);
|
|
78
|
+
|
|
79
|
+
tracer.trace('method2', {}).trace('method3', {});
|
|
80
|
+
expect(tracer.traces).toHaveLength(3);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('should handle empty data object', () => {
|
|
84
|
+
tracer.trace('testMethod');
|
|
85
|
+
|
|
86
|
+
expect(tracer.traces[0].data).toEqual({});
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
describe('traceError', () => {
|
|
91
|
+
test('should add error trace with Error object', () => {
|
|
92
|
+
const error = new Error('Test error message');
|
|
93
|
+
tracer.traceError('failingMethod', error);
|
|
94
|
+
|
|
95
|
+
expect(tracer.traces).toHaveLength(1);
|
|
96
|
+
expect(tracer.traces[0].methodName).toBe('failingMethod');
|
|
97
|
+
expect(tracer.traces[0].level).toBe('error');
|
|
98
|
+
expect(tracer.traces[0].data.message).toBe('Test error message');
|
|
99
|
+
expect(tracer.traces[0].data.errorStack).toContain('Error: Test error message');
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test('should handle string error', () => {
|
|
103
|
+
tracer.traceError('failingMethod', 'Something went wrong');
|
|
104
|
+
|
|
105
|
+
expect(tracer.traces[0].data.message).toBe('Something went wrong');
|
|
106
|
+
expect(tracer.traces[0].data.errorStack).toBeNull();
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test('should include additional data', () => {
|
|
110
|
+
const error = new Error('Test error');
|
|
111
|
+
tracer.traceError('failingMethod', error, { userId: 'user-123', action: 'create' });
|
|
112
|
+
|
|
113
|
+
expect(tracer.traces[0].data.userId).toBe('user-123');
|
|
114
|
+
expect(tracer.traces[0].data.action).toBe('create');
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('should return this for chaining', () => {
|
|
118
|
+
const result = tracer.traceError('method', new Error('test'));
|
|
119
|
+
expect(result).toBe(tracer);
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe('_sanitizeData', () => {
|
|
124
|
+
test('should redact sensitive fields', () => {
|
|
125
|
+
tracer.trace('testMethod', {
|
|
126
|
+
accessToken: 'secret-token',
|
|
127
|
+
refreshToken: 'secret-refresh',
|
|
128
|
+
apiKey: 'api-key-123',
|
|
129
|
+
password: 'secret-password',
|
|
130
|
+
username: 'normal-field'
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const data = tracer.traces[0].data;
|
|
134
|
+
expect(data.accessToken).toBe('[REDACTED]');
|
|
135
|
+
expect(data.refreshToken).toBe('[REDACTED]');
|
|
136
|
+
expect(data.apiKey).toBe('[REDACTED]');
|
|
137
|
+
expect(data.password).toBe('[REDACTED]');
|
|
138
|
+
expect(data.username).toBe('normal-field');
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test('should sanitize nested objects', () => {
|
|
142
|
+
tracer.trace('testMethod', {
|
|
143
|
+
user: {
|
|
144
|
+
name: 'John',
|
|
145
|
+
userPassword: 'secret123',
|
|
146
|
+
userAccessToken: 'token123'
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
const data = tracer.traces[0].data;
|
|
151
|
+
expect(data.user.name).toBe('John');
|
|
152
|
+
expect(data.user.userPassword).toBe('[REDACTED]');
|
|
153
|
+
expect(data.user.userAccessToken).toBe('[REDACTED]');
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test('should handle arrays', () => {
|
|
157
|
+
tracer.trace('testMethod', {
|
|
158
|
+
users: [
|
|
159
|
+
{ name: 'User1', apiKey: 'key1' },
|
|
160
|
+
{ name: 'User2', apiKey: 'key2' }
|
|
161
|
+
]
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
const data = tracer.traces[0].data;
|
|
165
|
+
expect(data.users[0].name).toBe('User1');
|
|
166
|
+
expect(data.users[0].apiKey).toBe('[REDACTED]');
|
|
167
|
+
expect(data.users[1].apiKey).toBe('[REDACTED]');
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test('should handle null and undefined data', () => {
|
|
171
|
+
tracer.trace('testMethod', null);
|
|
172
|
+
tracer.trace('testMethod2');
|
|
173
|
+
|
|
174
|
+
expect(tracer.traces[0].data).toBeNull();
|
|
175
|
+
// When undefined is passed, it defaults to {} from the default parameter
|
|
176
|
+
expect(tracer.traces[1].data).toEqual({});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
test('should handle primitive data', () => {
|
|
180
|
+
tracer.trace('testMethod', 'string-value');
|
|
181
|
+
tracer.trace('testMethod2', 42);
|
|
182
|
+
|
|
183
|
+
expect(tracer.traces[0].data).toBe('string-value');
|
|
184
|
+
expect(tracer.traces[1].data).toBe(42);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test('should redact case-insensitive sensitive fields', () => {
|
|
188
|
+
tracer.trace('testMethod', {
|
|
189
|
+
AccessToken: 'secret1',
|
|
190
|
+
APIKEY: 'secret2',
|
|
191
|
+
clientSecret: 'secret3'
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
const data = tracer.traces[0].data;
|
|
195
|
+
expect(data.AccessToken).toBe('[REDACTED]');
|
|
196
|
+
expect(data.APIKEY).toBe('[REDACTED]');
|
|
197
|
+
expect(data.clientSecret).toBe('[REDACTED]');
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test('should redact partial matches', () => {
|
|
201
|
+
tracer.trace('testMethod', {
|
|
202
|
+
userAuthToken: 'secret',
|
|
203
|
+
adminCredentials: 'secret',
|
|
204
|
+
myPrivateKey: 'secret'
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
const data = tracer.traces[0].data;
|
|
208
|
+
expect(data.userAuthToken).toBe('[REDACTED]');
|
|
209
|
+
expect(data.adminCredentials).toBe('[REDACTED]');
|
|
210
|
+
expect(data.myPrivateKey).toBe('[REDACTED]');
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
describe('getTraceData', () => {
|
|
215
|
+
test('should return complete trace data', () => {
|
|
216
|
+
tracer.trace('method1', { step: 1 });
|
|
217
|
+
tracer.trace('method2', { step: 2 });
|
|
218
|
+
|
|
219
|
+
const traceData = tracer.getTraceData();
|
|
220
|
+
|
|
221
|
+
expect(traceData.requestId).toBe(tracer.requestId);
|
|
222
|
+
expect(traceData.totalDuration).toMatch(/\d+ms$/);
|
|
223
|
+
expect(traceData.traceCount).toBe(2);
|
|
224
|
+
expect(traceData.traces).toHaveLength(2);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
test('should return empty traces for new tracer', () => {
|
|
228
|
+
const traceData = tracer.getTraceData();
|
|
229
|
+
|
|
230
|
+
expect(traceData.traceCount).toBe(0);
|
|
231
|
+
expect(traceData.traces).toEqual([]);
|
|
232
|
+
});
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
describe('wrapResponse', () => {
|
|
236
|
+
test('should add debug trace to response', () => {
|
|
237
|
+
tracer.trace('processRequest', { action: 'test' });
|
|
238
|
+
|
|
239
|
+
const response = { success: true, data: { id: 123 } };
|
|
240
|
+
const wrappedResponse = tracer.wrapResponse(response);
|
|
241
|
+
|
|
242
|
+
expect(wrappedResponse.success).toBe(true);
|
|
243
|
+
expect(wrappedResponse.data).toEqual({ id: 123 });
|
|
244
|
+
expect(wrappedResponse._debug).toBeDefined();
|
|
245
|
+
expect(wrappedResponse._debug.requestId).toBe(tracer.requestId);
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
test('should preserve original response properties', () => {
|
|
249
|
+
const response = {
|
|
250
|
+
status: 200,
|
|
251
|
+
message: 'OK',
|
|
252
|
+
nested: { key: 'value' }
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const wrapped = tracer.wrapResponse(response);
|
|
256
|
+
|
|
257
|
+
expect(wrapped.status).toBe(200);
|
|
258
|
+
expect(wrapped.message).toBe('OK');
|
|
259
|
+
expect(wrapped.nested.key).toBe('value');
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
describe('static fromRequest', () => {
|
|
264
|
+
test('should create tracer from Express request', () => {
|
|
265
|
+
const req = {
|
|
266
|
+
headers: {
|
|
267
|
+
'x-request-id': 'req-123',
|
|
268
|
+
'content-type': 'application/json'
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const tracer = DebugTracer.fromRequest(req);
|
|
273
|
+
|
|
274
|
+
expect(tracer).toBeInstanceOf(DebugTracer);
|
|
275
|
+
expect(tracer.requestId).toBeDefined();
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
test('should handle request without headers', () => {
|
|
279
|
+
const req = {};
|
|
280
|
+
|
|
281
|
+
const tracer = DebugTracer.fromRequest(req);
|
|
282
|
+
|
|
283
|
+
expect(tracer).toBeInstanceOf(DebugTracer);
|
|
284
|
+
});
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
describe('_captureStackTrace', () => {
|
|
288
|
+
test('should return array of stack trace lines', () => {
|
|
289
|
+
tracer.trace('testMethod', {});
|
|
290
|
+
|
|
291
|
+
const stackTrace = tracer.traces[0].stackTrace;
|
|
292
|
+
expect(Array.isArray(stackTrace)).toBe(true);
|
|
293
|
+
stackTrace.forEach(line => {
|
|
294
|
+
expect(line).toMatch(/^at /);
|
|
295
|
+
});
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
describe('integration', () => {
|
|
300
|
+
test('should track multiple operations', () => {
|
|
301
|
+
tracer
|
|
302
|
+
.trace('startOperation', { userId: 'user-123' })
|
|
303
|
+
.trace('fetchData', { query: 'SELECT *' })
|
|
304
|
+
.trace('processData', { count: 100 })
|
|
305
|
+
.trace('saveResult', { success: true });
|
|
306
|
+
|
|
307
|
+
const traceData = tracer.getTraceData();
|
|
308
|
+
expect(traceData.traceCount).toBe(4);
|
|
309
|
+
|
|
310
|
+
// Verify elapsed times are increasing
|
|
311
|
+
for (let i = 1; i < tracer.traces.length; i++) {
|
|
312
|
+
expect(tracer.traces[i].elapsed).toBeGreaterThanOrEqual(tracer.traces[i-1].elapsed);
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
test('should handle error in the middle of operations', () => {
|
|
317
|
+
tracer
|
|
318
|
+
.trace('startOperation', { step: 1 })
|
|
319
|
+
.traceError('failedOperation', new Error('Database error'), { query: 'INSERT' })
|
|
320
|
+
.trace('cleanupOperation', { step: 3 });
|
|
321
|
+
|
|
322
|
+
expect(tracer.traces).toHaveLength(3);
|
|
323
|
+
expect(tracer.traces[1].level).toBe('error');
|
|
324
|
+
expect(tracer.traces[2].level).toBe('info');
|
|
325
|
+
});
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
const moment = require('moment');
|
|
2
|
+
|
|
3
|
+
// Mock dependencies before requiring the module
|
|
4
|
+
jest.mock('client-oauth2');
|
|
5
|
+
jest.mock('../../models/userModel');
|
|
6
|
+
jest.mock('../../connector/registry');
|
|
7
|
+
jest.mock('../../models/dynamo/lockSchema', () => ({
|
|
8
|
+
Lock: {
|
|
9
|
+
create: jest.fn(),
|
|
10
|
+
get: jest.fn()
|
|
11
|
+
}
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
const ClientOAuth2 = require('client-oauth2');
|
|
15
|
+
const { UserModel } = require('../../models/userModel');
|
|
16
|
+
const connectorRegistry = require('../../connector/registry');
|
|
17
|
+
const { getOAuthApp, checkAndRefreshAccessToken } = require('../../lib/oauth');
|
|
18
|
+
|
|
19
|
+
describe('oauth', () => {
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
jest.clearAllMocks();
|
|
22
|
+
jest.spyOn(console, 'log').mockImplementation(() => {});
|
|
23
|
+
delete process.env.USE_TOKEN_REFRESH_LOCK_PLATFORMS;
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
afterEach(() => {
|
|
27
|
+
jest.restoreAllMocks();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
describe('getOAuthApp', () => {
|
|
31
|
+
test('should create OAuth app with provided configuration', () => {
|
|
32
|
+
const config = {
|
|
33
|
+
clientId: 'test-client-id',
|
|
34
|
+
clientSecret: 'test-client-secret',
|
|
35
|
+
accessTokenUri: 'https://api.example.com/oauth/token',
|
|
36
|
+
authorizationUri: 'https://api.example.com/oauth/authorize',
|
|
37
|
+
redirectUri: 'https://app.example.com/callback',
|
|
38
|
+
scopes: ['read', 'write']
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const mockOAuthApp = { code: { getToken: jest.fn() } };
|
|
42
|
+
ClientOAuth2.mockReturnValue(mockOAuthApp);
|
|
43
|
+
|
|
44
|
+
const result = getOAuthApp(config);
|
|
45
|
+
|
|
46
|
+
expect(ClientOAuth2).toHaveBeenCalledWith({
|
|
47
|
+
clientId: config.clientId,
|
|
48
|
+
clientSecret: config.clientSecret,
|
|
49
|
+
accessTokenUri: config.accessTokenUri,
|
|
50
|
+
authorizationUri: config.authorizationUri,
|
|
51
|
+
redirectUri: config.redirectUri,
|
|
52
|
+
scopes: config.scopes
|
|
53
|
+
});
|
|
54
|
+
expect(result).toBe(mockOAuthApp);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('should handle missing optional parameters', () => {
|
|
58
|
+
const config = {
|
|
59
|
+
clientId: 'client-id',
|
|
60
|
+
clientSecret: 'client-secret'
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
ClientOAuth2.mockReturnValue({});
|
|
64
|
+
|
|
65
|
+
getOAuthApp(config);
|
|
66
|
+
|
|
67
|
+
expect(ClientOAuth2).toHaveBeenCalledWith({
|
|
68
|
+
clientId: 'client-id',
|
|
69
|
+
clientSecret: 'client-secret',
|
|
70
|
+
accessTokenUri: undefined,
|
|
71
|
+
authorizationUri: undefined,
|
|
72
|
+
redirectUri: undefined,
|
|
73
|
+
scopes: undefined
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe('checkAndRefreshAccessToken', () => {
|
|
79
|
+
const mockOAuthApp = {
|
|
80
|
+
createToken: jest.fn()
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const createMockUser = (overrides = {}) => ({
|
|
84
|
+
id: 'user-123',
|
|
85
|
+
platform: 'testPlatform',
|
|
86
|
+
accessToken: 'old-access-token',
|
|
87
|
+
refreshToken: 'old-refresh-token',
|
|
88
|
+
tokenExpiry: moment().subtract(1, 'minute').toDate(), // Expired
|
|
89
|
+
save: jest.fn().mockResolvedValue(true),
|
|
90
|
+
...overrides
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('should return user unchanged if token is not expired', async () => {
|
|
94
|
+
const user = createMockUser({
|
|
95
|
+
tokenExpiry: moment().add(10, 'minutes').toDate() // Not expired
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
99
|
+
|
|
100
|
+
const result = await checkAndRefreshAccessToken(mockOAuthApp, user);
|
|
101
|
+
|
|
102
|
+
expect(result).toBe(user);
|
|
103
|
+
expect(mockOAuthApp.createToken).not.toHaveBeenCalled();
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('should refresh token when expired', async () => {
|
|
107
|
+
const user = createMockUser();
|
|
108
|
+
const newExpiry = moment().add(1, 'hour').toDate();
|
|
109
|
+
|
|
110
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
111
|
+
|
|
112
|
+
const mockToken = {
|
|
113
|
+
refresh: jest.fn().mockResolvedValue({
|
|
114
|
+
accessToken: 'new-access-token',
|
|
115
|
+
refreshToken: 'new-refresh-token',
|
|
116
|
+
expires: newExpiry
|
|
117
|
+
})
|
|
118
|
+
};
|
|
119
|
+
mockOAuthApp.createToken.mockReturnValue(mockToken);
|
|
120
|
+
|
|
121
|
+
const result = await checkAndRefreshAccessToken(mockOAuthApp, user);
|
|
122
|
+
|
|
123
|
+
expect(mockOAuthApp.createToken).toHaveBeenCalledWith(
|
|
124
|
+
'old-access-token',
|
|
125
|
+
'old-refresh-token'
|
|
126
|
+
);
|
|
127
|
+
expect(mockToken.refresh).toHaveBeenCalled();
|
|
128
|
+
expect(user.accessToken).toBe('new-access-token');
|
|
129
|
+
expect(user.refreshToken).toBe('new-refresh-token');
|
|
130
|
+
expect(user.save).toHaveBeenCalled();
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('should delegate to platform-specific refresh if available', async () => {
|
|
134
|
+
const user = createMockUser({
|
|
135
|
+
platform: 'bullhorn'
|
|
136
|
+
});
|
|
137
|
+
const platformRefreshedUser = { ...user, accessToken: 'bullhorn-token' };
|
|
138
|
+
|
|
139
|
+
connectorRegistry.getConnector.mockReturnValue({
|
|
140
|
+
checkAndRefreshAccessToken: jest.fn().mockResolvedValue(platformRefreshedUser)
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
const result = await checkAndRefreshAccessToken(mockOAuthApp, user);
|
|
144
|
+
|
|
145
|
+
expect(result).toBe(platformRefreshedUser);
|
|
146
|
+
expect(mockOAuthApp.createToken).not.toHaveBeenCalled();
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test('should refresh token even if within buffer time (2 minutes)', async () => {
|
|
150
|
+
const user = createMockUser({
|
|
151
|
+
tokenExpiry: moment().add(1.5, 'minutes').toDate() // Within buffer
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
155
|
+
|
|
156
|
+
const mockToken = {
|
|
157
|
+
refresh: jest.fn().mockResolvedValue({
|
|
158
|
+
accessToken: 'new-token',
|
|
159
|
+
refreshToken: 'new-refresh',
|
|
160
|
+
expires: moment().add(1, 'hour').toDate()
|
|
161
|
+
})
|
|
162
|
+
};
|
|
163
|
+
mockOAuthApp.createToken.mockReturnValue(mockToken);
|
|
164
|
+
|
|
165
|
+
await checkAndRefreshAccessToken(mockOAuthApp, user);
|
|
166
|
+
|
|
167
|
+
expect(mockToken.refresh).toHaveBeenCalled();
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test('should not refresh if missing required tokens', async () => {
|
|
171
|
+
const user = createMockUser({
|
|
172
|
+
accessToken: null,
|
|
173
|
+
refreshToken: null,
|
|
174
|
+
tokenExpiry: moment().subtract(1, 'minute').toDate()
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
178
|
+
|
|
179
|
+
const result = await checkAndRefreshAccessToken(mockOAuthApp, user);
|
|
180
|
+
|
|
181
|
+
expect(result).toBe(user);
|
|
182
|
+
expect(mockOAuthApp.createToken).not.toHaveBeenCalled();
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
describe('with token refresh lock', () => {
|
|
186
|
+
beforeEach(() => {
|
|
187
|
+
process.env.USE_TOKEN_REFRESH_LOCK_PLATFORMS = 'testPlatform,otherPlatform';
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
test('should create lock and refresh token successfully', async () => {
|
|
191
|
+
const { Lock } = require('../../models/dynamo/lockSchema');
|
|
192
|
+
const user = createMockUser();
|
|
193
|
+
const newExpiry = moment().add(1, 'hour').toDate();
|
|
194
|
+
|
|
195
|
+
const mockLock = { delete: jest.fn().mockResolvedValue(true) };
|
|
196
|
+
Lock.create.mockResolvedValue(mockLock);
|
|
197
|
+
|
|
198
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
199
|
+
|
|
200
|
+
const mockToken = {
|
|
201
|
+
refresh: jest.fn().mockResolvedValue({
|
|
202
|
+
accessToken: 'new-token',
|
|
203
|
+
refreshToken: 'new-refresh',
|
|
204
|
+
expires: newExpiry
|
|
205
|
+
})
|
|
206
|
+
};
|
|
207
|
+
mockOAuthApp.createToken.mockReturnValue(mockToken);
|
|
208
|
+
|
|
209
|
+
await checkAndRefreshAccessToken(mockOAuthApp, user);
|
|
210
|
+
|
|
211
|
+
expect(Lock.create).toHaveBeenCalledWith(
|
|
212
|
+
expect.objectContaining({
|
|
213
|
+
userId: 'user-123',
|
|
214
|
+
ttl: expect.any(Number)
|
|
215
|
+
}),
|
|
216
|
+
{ overwrite: false }
|
|
217
|
+
);
|
|
218
|
+
expect(mockToken.refresh).toHaveBeenCalled();
|
|
219
|
+
expect(mockLock.delete).toHaveBeenCalled();
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test('should wait for existing lock and fetch user from DB after lock released', async () => {
|
|
223
|
+
jest.resetModules();
|
|
224
|
+
const { Lock } = require('../../models/dynamo/lockSchema');
|
|
225
|
+
const user = createMockUser();
|
|
226
|
+
|
|
227
|
+
// Simulate lock already exists
|
|
228
|
+
const conditionalError = new Error('Lock exists');
|
|
229
|
+
conditionalError.name = 'ConditionalCheckFailedException';
|
|
230
|
+
Lock.create.mockReset();
|
|
231
|
+
Lock.get.mockReset();
|
|
232
|
+
Lock.create.mockRejectedValue(conditionalError);
|
|
233
|
+
|
|
234
|
+
// Lock exists but not expired (ttl > now), then gets released
|
|
235
|
+
const existingLock = {
|
|
236
|
+
ttl: moment().add(30, 'seconds').unix(),
|
|
237
|
+
delete: jest.fn().mockResolvedValue(true)
|
|
238
|
+
};
|
|
239
|
+
Lock.get.mockResolvedValueOnce(existingLock)
|
|
240
|
+
.mockResolvedValueOnce(null); // Lock released
|
|
241
|
+
|
|
242
|
+
const refreshedUser = { ...user, accessToken: 'refreshed-by-other-process' };
|
|
243
|
+
UserModel.findByPk.mockResolvedValue(refreshedUser);
|
|
244
|
+
|
|
245
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
246
|
+
|
|
247
|
+
const result = await checkAndRefreshAccessToken(mockOAuthApp, user, 5);
|
|
248
|
+
|
|
249
|
+
// Verify the lock polling was performed
|
|
250
|
+
expect(Lock.get).toHaveBeenCalled();
|
|
251
|
+
// The result should have the user data (refreshed by another process)
|
|
252
|
+
expect(result).toBeDefined();
|
|
253
|
+
expect(result.id).toBe(user.id);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
test('should handle expired lock by deleting and creating new one', async () => {
|
|
257
|
+
const { Lock } = require('../../models/dynamo/lockSchema');
|
|
258
|
+
const user = createMockUser();
|
|
259
|
+
const newExpiry = moment().add(1, 'hour').toDate();
|
|
260
|
+
|
|
261
|
+
// First create fails with conditional exception
|
|
262
|
+
const conditionalError = new Error('Lock exists');
|
|
263
|
+
conditionalError.name = 'ConditionalCheckFailedException';
|
|
264
|
+
|
|
265
|
+
// Existing lock is expired (ttl < now)
|
|
266
|
+
const expiredLock = {
|
|
267
|
+
ttl: moment().subtract(10, 'seconds').unix(),
|
|
268
|
+
delete: jest.fn().mockResolvedValue(true)
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// Second create succeeds after deleting expired lock
|
|
272
|
+
const newLock = { delete: jest.fn().mockResolvedValue(true) };
|
|
273
|
+
|
|
274
|
+
Lock.create
|
|
275
|
+
.mockRejectedValueOnce(conditionalError)
|
|
276
|
+
.mockResolvedValueOnce(newLock);
|
|
277
|
+
Lock.get.mockResolvedValue(expiredLock);
|
|
278
|
+
|
|
279
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
280
|
+
|
|
281
|
+
const mockToken = {
|
|
282
|
+
refresh: jest.fn().mockResolvedValue({
|
|
283
|
+
accessToken: 'new-token',
|
|
284
|
+
refreshToken: 'new-refresh',
|
|
285
|
+
expires: newExpiry
|
|
286
|
+
})
|
|
287
|
+
};
|
|
288
|
+
mockOAuthApp.createToken.mockReturnValue(mockToken);
|
|
289
|
+
|
|
290
|
+
await checkAndRefreshAccessToken(mockOAuthApp, user);
|
|
291
|
+
|
|
292
|
+
expect(expiredLock.delete).toHaveBeenCalled();
|
|
293
|
+
expect(newLock.delete).toHaveBeenCalled();
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
test('should delete lock if refresh fails', async () => {
|
|
297
|
+
jest.resetModules();
|
|
298
|
+
const { Lock } = require('../../models/dynamo/lockSchema');
|
|
299
|
+
const user = createMockUser();
|
|
300
|
+
|
|
301
|
+
const mockLock = { delete: jest.fn().mockResolvedValue(true) };
|
|
302
|
+
Lock.create.mockReset();
|
|
303
|
+
Lock.get.mockReset();
|
|
304
|
+
Lock.create.mockResolvedValue(mockLock);
|
|
305
|
+
|
|
306
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
307
|
+
|
|
308
|
+
const mockToken = {
|
|
309
|
+
refresh: jest.fn().mockRejectedValue(new Error('Refresh failed'))
|
|
310
|
+
};
|
|
311
|
+
mockOAuthApp.createToken.mockReturnValue(mockToken);
|
|
312
|
+
|
|
313
|
+
await checkAndRefreshAccessToken(mockOAuthApp, user);
|
|
314
|
+
|
|
315
|
+
expect(mockLock.delete).toHaveBeenCalled();
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
test('should throw on lock timeout', async () => {
|
|
319
|
+
jest.resetModules();
|
|
320
|
+
const { Lock } = require('../../models/dynamo/lockSchema');
|
|
321
|
+
const user = createMockUser();
|
|
322
|
+
|
|
323
|
+
const conditionalError = new Error('Lock exists');
|
|
324
|
+
conditionalError.name = 'ConditionalCheckFailedException';
|
|
325
|
+
Lock.create.mockReset();
|
|
326
|
+
Lock.get.mockReset();
|
|
327
|
+
Lock.create.mockRejectedValue(conditionalError);
|
|
328
|
+
|
|
329
|
+
// Lock never gets released (ttl is in the future, not expired)
|
|
330
|
+
const permanentLock = {
|
|
331
|
+
ttl: moment().add(1, 'hour').unix(),
|
|
332
|
+
delete: jest.fn().mockResolvedValue(true)
|
|
333
|
+
};
|
|
334
|
+
Lock.get.mockResolvedValue(permanentLock);
|
|
335
|
+
|
|
336
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
337
|
+
|
|
338
|
+
await expect(
|
|
339
|
+
checkAndRefreshAccessToken(mockOAuthApp, user, 1) // 1 second timeout
|
|
340
|
+
).rejects.toThrow('Token lock timeout');
|
|
341
|
+
}, 10000);
|
|
342
|
+
|
|
343
|
+
test('should rethrow non-conditional errors', async () => {
|
|
344
|
+
const { Lock } = require('../../models/dynamo/lockSchema');
|
|
345
|
+
const user = createMockUser();
|
|
346
|
+
|
|
347
|
+
const randomError = new Error('Database connection failed');
|
|
348
|
+
Lock.create.mockRejectedValue(randomError);
|
|
349
|
+
|
|
350
|
+
connectorRegistry.getConnector.mockReturnValue({});
|
|
351
|
+
|
|
352
|
+
await expect(
|
|
353
|
+
checkAndRefreshAccessToken(mockOAuthApp, user)
|
|
354
|
+
).rejects.toThrow('Database connection failed');
|
|
355
|
+
});
|
|
356
|
+
});
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
|