asyx 0.1.0 → 0.1.2
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/README.md +22 -0
- package/package.json +32 -5
- package/src/lib/csr.js +174 -14
- package/src/tunnel/ws-control.js +4 -13
- package/src/lib/logger.level.spec.js +0 -81
- package/src/lib/logger.test.js +0 -42
- package/src/tunnel/__test_utils__/testUtils.js +0 -76
- package/src/tunnel/__tests__/jwt-refresh.spec.js +0 -948
- package/src/tunnel/__tests__/ws-control.spec.js +0 -164
|
@@ -1,948 +0,0 @@
|
|
|
1
|
-
import { describe, test, expect, jest, beforeEach, afterEach } from '@jest/globals';
|
|
2
|
-
import { createHttpTunnel } from '../__test_utils__/testUtils.js';
|
|
3
|
-
|
|
4
|
-
// Minimal assignment shim
|
|
5
|
-
jest.unstable_mockModule('../../state/assignment.js', () => ({
|
|
6
|
-
getAssignment: jest.fn(() => ({
|
|
7
|
-
leaseId: 'lease-001',
|
|
8
|
-
jwt: 'new.jwt',
|
|
9
|
-
requestId: 'refresh-req-1',
|
|
10
|
-
relayUrl: 'wss://relay.new/agent'
|
|
11
|
-
})),
|
|
12
|
-
recordRefresh: jest.fn(() => 1234)
|
|
13
|
-
}));
|
|
14
|
-
|
|
15
|
-
// Minimal fingerprint shim
|
|
16
|
-
jest.unstable_mockModule('../../lib/fingerprint.js', () => ({
|
|
17
|
-
getFpHash: jest.fn(async () => ({ fph: 'fp', fpi: 'id' }))
|
|
18
|
-
}));
|
|
19
|
-
|
|
20
|
-
describe('JWT refresh', () => {
|
|
21
|
-
let exitSpy;
|
|
22
|
-
beforeEach(() => {
|
|
23
|
-
jest.resetModules();
|
|
24
|
-
jest.clearAllMocks();
|
|
25
|
-
exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => undefined);
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
afterEach(() => {
|
|
29
|
-
exitSpy.mockRestore();
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
test('successful refresh logs success and resets attempts', async () => {
|
|
33
|
-
const { tunnel, logger, coordinatorCore, coordinatorIngress } = await createHttpTunnel();
|
|
34
|
-
|
|
35
|
-
const assignmentMod = await import('../../state/assignment.js');
|
|
36
|
-
assignmentMod.getAssignment.mockReturnValueOnce({ leaseId: 'lease-001' }); // pre-check
|
|
37
|
-
// after ack, return new assignment
|
|
38
|
-
assignmentMod.getAssignment.mockReturnValueOnce({
|
|
39
|
-
leaseId: 'lease-001', jwt: 'refreshed.jwt', requestId: 'refresh-123', relayUrl: 'wss://relay.new/agent'
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
const refreshPromise = tunnel.attemptJwtRefresh();
|
|
43
|
-
// wait for publish to be called
|
|
44
|
-
while (coordinatorCore.publish.mock.calls.length === 0) {
|
|
45
|
-
await new Promise(r => setImmediate(r));
|
|
46
|
-
}
|
|
47
|
-
const publishCall = coordinatorCore.publish.mock.calls.at(-1)[0];
|
|
48
|
-
const payload = JSON.parse(publishCall.payload);
|
|
49
|
-
coordinatorIngress.resolve({ type: 'open_ack', requestId: payload.requestId });
|
|
50
|
-
await refreshPromise;
|
|
51
|
-
// allow any pending microtasks/logs
|
|
52
|
-
await new Promise(r => setImmediate(r));
|
|
53
|
-
|
|
54
|
-
expect(logger.info).toHaveBeenCalledWith('jwt.refresh.start', expect.objectContaining({ retryCount: 1 }));
|
|
55
|
-
expect(coordinatorCore.publish).toHaveBeenCalled();
|
|
56
|
-
// leaving attempt counter check out; behavior is validated by subsequent flows
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
test('timeout triggers lease-preserving fallback', async () => {
|
|
60
|
-
const waitForControlPlane = jest.fn(async () => {});
|
|
61
|
-
const { tunnel, logger, coordinatorIngress, coordinatorCore } = await createHttpTunnel({ waitForControlPlane });
|
|
62
|
-
|
|
63
|
-
const assignmentMod = await import('../../state/assignment.js');
|
|
64
|
-
// CLI-RES-REFRESH-FALLBACK: Mock current assignment with leaseId and relayId
|
|
65
|
-
assignmentMod.getAssignment.mockReturnValueOnce({
|
|
66
|
-
leaseId: 'lease-001',
|
|
67
|
-
relayId: 'relay-001',
|
|
68
|
-
jwt: 'current.jwt'
|
|
69
|
-
});
|
|
70
|
-
// After fallback ack, return refreshed assignment with same leaseId
|
|
71
|
-
assignmentMod.getAssignment.mockReturnValueOnce({
|
|
72
|
-
leaseId: 'lease-001',
|
|
73
|
-
relayId: 'relay-001',
|
|
74
|
-
jwt: 'refreshed.jwt',
|
|
75
|
-
requestId: 'refresh-123',
|
|
76
|
-
relayUrl: 'wss://relay.new/agent'
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
const p = tunnel.attemptJwtRefresh();
|
|
80
|
-
// wait for first publish
|
|
81
|
-
while (coordinatorCore.publish.mock.calls.length === 0) {
|
|
82
|
-
await new Promise(r => setImmediate(r));
|
|
83
|
-
}
|
|
84
|
-
// cause the awaiter to time out by rejecting all so fallback triggers
|
|
85
|
-
coordinatorIngress.rejectAll(new Error('timed out'));
|
|
86
|
-
// wait for fallback publish
|
|
87
|
-
while (coordinatorCore.publish.mock.calls.length < 2) {
|
|
88
|
-
await new Promise(r => setImmediate(r));
|
|
89
|
-
}
|
|
90
|
-
// CLI-RES-REFRESH-FALLBACK: Verify fallback payload uses refreshOf
|
|
91
|
-
const fallbackCall = coordinatorCore.publish.mock.calls.at(-1)[0];
|
|
92
|
-
const fallbackPayload = JSON.parse(fallbackCall.payload);
|
|
93
|
-
expect(fallbackPayload.refreshOf).toBe('lease-001');
|
|
94
|
-
expect(fallbackPayload.reconnect).toBe(false);
|
|
95
|
-
|
|
96
|
-
// resolve fallback open_ack
|
|
97
|
-
coordinatorIngress.resolve({ type: 'open_ack', requestId: fallbackPayload.requestId });
|
|
98
|
-
await p;
|
|
99
|
-
|
|
100
|
-
expect(logger.warn).toHaveBeenCalledWith('jwt.refresh.timeout', expect.objectContaining({ retryCount: 1 }));
|
|
101
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
102
|
-
'jwt.refresh.fallback.start',
|
|
103
|
-
expect.objectContaining({
|
|
104
|
-
leaseId: 'lease-001',
|
|
105
|
-
relayId: 'relay-001'
|
|
106
|
-
})
|
|
107
|
-
);
|
|
108
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
109
|
-
'jwt.refresh.fallback.request.sent',
|
|
110
|
-
expect.objectContaining({
|
|
111
|
-
leaseId: 'lease-001',
|
|
112
|
-
relayId: 'relay-001'
|
|
113
|
-
})
|
|
114
|
-
);
|
|
115
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
116
|
-
'jwt.refresh.fallback.success',
|
|
117
|
-
expect.objectContaining({
|
|
118
|
-
leaseId: 'lease-001'
|
|
119
|
-
})
|
|
120
|
-
);
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
test('exhausted attempts logs error and exits', async () => {
|
|
124
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
125
|
-
tunnel.refreshMaxAttempts = 0;
|
|
126
|
-
|
|
127
|
-
const originalExit = process.exit;
|
|
128
|
-
const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit'); });
|
|
129
|
-
|
|
130
|
-
try {
|
|
131
|
-
await tunnel.attemptJwtRefresh();
|
|
132
|
-
} catch (e) {
|
|
133
|
-
// swallow forced exit
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
expect(logger.error).toHaveBeenCalledWith('jwt.refresh.exhausted', expect.objectContaining({ retryCount: 0 }));
|
|
137
|
-
exitSpy.mockRestore();
|
|
138
|
-
process.exit = originalExit;
|
|
139
|
-
});
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
// CLI-RES-DPJWT-LEAD: Tests for proactive refresh scheduling
|
|
143
|
-
describe('CLI-RES-DPJWT-LEAD: Proactive refresh scheduling', () => {
|
|
144
|
-
let exitSpy;
|
|
145
|
-
|
|
146
|
-
beforeEach(() => {
|
|
147
|
-
jest.resetModules();
|
|
148
|
-
jest.clearAllMocks();
|
|
149
|
-
jest.useFakeTimers();
|
|
150
|
-
exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => undefined);
|
|
151
|
-
});
|
|
152
|
-
|
|
153
|
-
afterEach(() => {
|
|
154
|
-
jest.useRealTimers();
|
|
155
|
-
exitSpy.mockRestore();
|
|
156
|
-
});
|
|
157
|
-
|
|
158
|
-
// Helper to create a valid JWT with exp
|
|
159
|
-
function createJWT(expSeconds, iatSeconds = undefined) {
|
|
160
|
-
const header = Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url');
|
|
161
|
-
const payloadObj = { exp: expSeconds };
|
|
162
|
-
if (iatSeconds !== undefined) {
|
|
163
|
-
payloadObj.iat = iatSeconds;
|
|
164
|
-
} else {
|
|
165
|
-
payloadObj.iat = expSeconds - 3600; // Default: issued 1 hour before expiry
|
|
166
|
-
}
|
|
167
|
-
const payload = Buffer.from(JSON.stringify(payloadObj)).toString('base64url');
|
|
168
|
-
const signature = 'fake-signature';
|
|
169
|
-
return `${header}.${payload}.${signature}`;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
test('schedules refresh 3 minutes before expiry', async () => {
|
|
173
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
174
|
-
|
|
175
|
-
// Set current time
|
|
176
|
-
const now = Date.now();
|
|
177
|
-
jest.setSystemTime(now);
|
|
178
|
-
|
|
179
|
-
// Create JWT expiring in 15 minutes (900 seconds)
|
|
180
|
-
const expIn15Min = Math.floor(now / 1000) + 900;
|
|
181
|
-
const jwt = createJWT(expIn15Min);
|
|
182
|
-
|
|
183
|
-
tunnel.scheduleRefresh(jwt, 'test');
|
|
184
|
-
|
|
185
|
-
// Should schedule for 12 minutes from now (15 min - 3 min lead)
|
|
186
|
-
const scheduledDelay = 12 * 60 * 1000;
|
|
187
|
-
|
|
188
|
-
// Verify scheduling log
|
|
189
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
190
|
-
'jwt.refresh.schedule',
|
|
191
|
-
expect.objectContaining({
|
|
192
|
-
leadMs: 180000,
|
|
193
|
-
context: 'test'
|
|
194
|
-
})
|
|
195
|
-
);
|
|
196
|
-
|
|
197
|
-
// Verify timer was set
|
|
198
|
-
expect(tunnel.refreshTimer).toBeDefined();
|
|
199
|
-
expect(jest.getTimerCount()).toBe(1);
|
|
200
|
-
|
|
201
|
-
// Advance time to trigger refresh
|
|
202
|
-
const refreshSpy = jest.spyOn(tunnel, 'attemptJwtRefresh').mockResolvedValue();
|
|
203
|
-
jest.advanceTimersByTime(scheduledDelay);
|
|
204
|
-
await Promise.resolve(); // Allow async handlers to run
|
|
205
|
-
|
|
206
|
-
expect(refreshSpy).toHaveBeenCalled();
|
|
207
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
208
|
-
'jwt.refresh.schedule.trigger',
|
|
209
|
-
expect.objectContaining({
|
|
210
|
-
leadMs: 180000,
|
|
211
|
-
context: 'timer'
|
|
212
|
-
})
|
|
213
|
-
);
|
|
214
|
-
});
|
|
215
|
-
|
|
216
|
-
test('triggers immediate refresh when exp < 3 minutes ahead', async () => {
|
|
217
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
218
|
-
|
|
219
|
-
const now = Date.now();
|
|
220
|
-
jest.setSystemTime(now);
|
|
221
|
-
|
|
222
|
-
// Create JWT expiring in 2 minutes (inside 3 min lead)
|
|
223
|
-
const expIn2Min = Math.floor(now / 1000) + 120;
|
|
224
|
-
const jwt = createJWT(expIn2Min);
|
|
225
|
-
|
|
226
|
-
const refreshSpy = jest.spyOn(tunnel, 'attemptJwtRefresh').mockResolvedValue();
|
|
227
|
-
|
|
228
|
-
tunnel.scheduleRefresh(jwt, 'test');
|
|
229
|
-
|
|
230
|
-
await Promise.resolve(); // Allow async handlers
|
|
231
|
-
|
|
232
|
-
// Should trigger immediately
|
|
233
|
-
expect(refreshSpy).toHaveBeenCalled();
|
|
234
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
235
|
-
'jwt.refresh.schedule.immediate',
|
|
236
|
-
expect.objectContaining({
|
|
237
|
-
leadMs: 180000,
|
|
238
|
-
context: 'test'
|
|
239
|
-
})
|
|
240
|
-
);
|
|
241
|
-
expect(tunnel.refreshTimer).toBeNull();
|
|
242
|
-
});
|
|
243
|
-
|
|
244
|
-
test('re-schedules when newer token arrives', async () => {
|
|
245
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
246
|
-
|
|
247
|
-
const now = Date.now();
|
|
248
|
-
jest.setSystemTime(now);
|
|
249
|
-
|
|
250
|
-
// First token expiring in 30 minutes
|
|
251
|
-
const expIn30Min = Math.floor(now / 1000) + 1800;
|
|
252
|
-
const jwt1 = createJWT(expIn30Min);
|
|
253
|
-
|
|
254
|
-
tunnel.scheduleRefresh(jwt1, 'first');
|
|
255
|
-
|
|
256
|
-
expect(tunnel.refreshTimer).toBeDefined();
|
|
257
|
-
const firstTimer = tunnel.refreshTimer;
|
|
258
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
259
|
-
'jwt.refresh.schedule',
|
|
260
|
-
expect.objectContaining({ context: 'first' })
|
|
261
|
-
);
|
|
262
|
-
|
|
263
|
-
// Second token expiring in 60 minutes (newer, longer expiry)
|
|
264
|
-
const expIn60Min = Math.floor(now / 1000) + 3600;
|
|
265
|
-
const jwt2 = createJWT(expIn60Min);
|
|
266
|
-
|
|
267
|
-
// Should clear previous timer and schedule new one
|
|
268
|
-
const clearSpy = jest.spyOn(global, 'clearTimeout');
|
|
269
|
-
try {
|
|
270
|
-
tunnel.scheduleRefresh(jwt2, 'second');
|
|
271
|
-
|
|
272
|
-
expect(clearSpy).toHaveBeenCalledWith(firstTimer);
|
|
273
|
-
expect(tunnel.refreshTimer).toBeDefined();
|
|
274
|
-
expect(tunnel.refreshTimer).not.toBe(firstTimer);
|
|
275
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
276
|
-
'jwt.refresh.schedule',
|
|
277
|
-
expect.objectContaining({ context: 'second' })
|
|
278
|
-
);
|
|
279
|
-
} finally {
|
|
280
|
-
clearSpy.mockRestore();
|
|
281
|
-
}
|
|
282
|
-
});
|
|
283
|
-
|
|
284
|
-
test('skips scheduling for invalid JWT', async () => {
|
|
285
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
286
|
-
|
|
287
|
-
// Invalid JWT formats
|
|
288
|
-
const invalidJWTs = [
|
|
289
|
-
'not-a-jwt',
|
|
290
|
-
'header.payload', // missing signature
|
|
291
|
-
'header.payload.signature', // but payload not valid JSON
|
|
292
|
-
];
|
|
293
|
-
|
|
294
|
-
for (const jwt of invalidJWTs) {
|
|
295
|
-
tunnel.scheduleRefresh(jwt, 'invalid');
|
|
296
|
-
expect(logger.warn).toHaveBeenCalledWith(
|
|
297
|
-
'jwt.refresh.schedule.invalid_token',
|
|
298
|
-
{ context: 'invalid' }
|
|
299
|
-
);
|
|
300
|
-
expect(tunnel.refreshTimer).toBeNull();
|
|
301
|
-
}
|
|
302
|
-
});
|
|
303
|
-
|
|
304
|
-
test('checks lead window on reconnect', async () => {
|
|
305
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
306
|
-
|
|
307
|
-
const now = Date.now();
|
|
308
|
-
jest.setSystemTime(now);
|
|
309
|
-
|
|
310
|
-
// JWT expiring in 2 minutes (inside 3 min lead window)
|
|
311
|
-
const expIn2Min = Math.floor(now / 1000) + 120;
|
|
312
|
-
const jwt = createJWT(expIn2Min);
|
|
313
|
-
|
|
314
|
-
// Store JWT metadata
|
|
315
|
-
tunnel.jwtMeta = { token: jwt, expMs: expIn2Min * 1000 };
|
|
316
|
-
|
|
317
|
-
const refreshSpy = jest.spyOn(tunnel, 'attemptJwtRefresh').mockResolvedValue();
|
|
318
|
-
|
|
319
|
-
// Simulate reconnect check
|
|
320
|
-
const triggered = tunnel._checkRefreshLeadWindow();
|
|
321
|
-
|
|
322
|
-
expect(triggered).toBe(true);
|
|
323
|
-
expect(refreshSpy).toHaveBeenCalled();
|
|
324
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
325
|
-
'jwt.refresh.schedule.immediate',
|
|
326
|
-
expect.objectContaining({
|
|
327
|
-
context: 'reconnect_lead_window'
|
|
328
|
-
})
|
|
329
|
-
);
|
|
330
|
-
});
|
|
331
|
-
|
|
332
|
-
test('does not trigger on reconnect if outside lead window', async () => {
|
|
333
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
334
|
-
|
|
335
|
-
const now = Date.now();
|
|
336
|
-
jest.setSystemTime(now);
|
|
337
|
-
|
|
338
|
-
// JWT expiring in 30 minutes (outside lead window)
|
|
339
|
-
const expIn30Min = Math.floor(now / 1000) + 1800;
|
|
340
|
-
const jwt = createJWT(expIn30Min);
|
|
341
|
-
|
|
342
|
-
tunnel.jwtMeta = { token: jwt, expMs: expIn30Min * 1000 };
|
|
343
|
-
|
|
344
|
-
const refreshSpy = jest.spyOn(tunnel, 'attemptJwtRefresh').mockResolvedValue();
|
|
345
|
-
|
|
346
|
-
const triggered = tunnel._checkRefreshLeadWindow();
|
|
347
|
-
|
|
348
|
-
expect(triggered).toBe(false);
|
|
349
|
-
expect(refreshSpy).not.toHaveBeenCalled();
|
|
350
|
-
});
|
|
351
|
-
|
|
352
|
-
test('clears timer on close', async () => {
|
|
353
|
-
const { tunnel } = await createHttpTunnel();
|
|
354
|
-
|
|
355
|
-
const now = Date.now();
|
|
356
|
-
jest.setSystemTime(now);
|
|
357
|
-
|
|
358
|
-
const expIn15Min = Math.floor(now / 1000) + 900;
|
|
359
|
-
const jwt = createJWT(expIn15Min);
|
|
360
|
-
|
|
361
|
-
tunnel.scheduleRefresh(jwt, 'test');
|
|
362
|
-
expect(tunnel.refreshTimer).toBeDefined();
|
|
363
|
-
|
|
364
|
-
tunnel.close();
|
|
365
|
-
|
|
366
|
-
expect(tunnel.refreshTimer).toBeNull();
|
|
367
|
-
expect(jest.getTimerCount()).toBe(0);
|
|
368
|
-
});
|
|
369
|
-
|
|
370
|
-
test('warns on clock skew', async () => {
|
|
371
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
372
|
-
|
|
373
|
-
const now = Date.now();
|
|
374
|
-
jest.setSystemTime(now);
|
|
375
|
-
|
|
376
|
-
// JWT with exp only 2 minutes ahead (less than 3 min lead)
|
|
377
|
-
const expIn2Min = Math.floor(now / 1000) + 120;
|
|
378
|
-
const jwt = createJWT(expIn2Min);
|
|
379
|
-
|
|
380
|
-
tunnel.scheduleRefresh(jwt, 'skew_test');
|
|
381
|
-
|
|
382
|
-
// Should warn about clock skew
|
|
383
|
-
expect(logger.warn).toHaveBeenCalledWith(
|
|
384
|
-
'jwt.refresh.schedule.skew_warning',
|
|
385
|
-
expect.objectContaining({
|
|
386
|
-
leadMs: 180000,
|
|
387
|
-
skewMs: expect.any(Number)
|
|
388
|
-
})
|
|
389
|
-
);
|
|
390
|
-
});
|
|
391
|
-
|
|
392
|
-
test('adjusts lead when TTL is shorter than lead time', async () => {
|
|
393
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
394
|
-
|
|
395
|
-
const now = Date.now();
|
|
396
|
-
jest.setSystemTime(now);
|
|
397
|
-
|
|
398
|
-
// JWT expiring in 90 seconds (1.5 minutes) - TTL shorter than 3 min lead
|
|
399
|
-
const expIn90Sec = Math.floor(now / 1000) + 90;
|
|
400
|
-
const issuedAt = Math.floor(now / 1000) - 10; // Issued 10s ago, so TTL = 100s
|
|
401
|
-
const jwt = createJWT(expIn90Sec, issuedAt);
|
|
402
|
-
|
|
403
|
-
tunnel.scheduleRefresh(jwt, 'short_ttl_test');
|
|
404
|
-
|
|
405
|
-
// Should adjust lead: TTL is ~100s, so adjusted = max(30s, 100/4) = max(30s, 25s) = 30s
|
|
406
|
-
expect(logger.warn).toHaveBeenCalledWith(
|
|
407
|
-
'jwt.refresh.lead_adjusted',
|
|
408
|
-
expect.objectContaining({
|
|
409
|
-
context: 'short_ttl_test',
|
|
410
|
-
originalLeadMs: 180000,
|
|
411
|
-
adjustedLeadMs: 30000, // max(30000, floor(100000/4))
|
|
412
|
-
ttlMs: expect.any(Number)
|
|
413
|
-
})
|
|
414
|
-
);
|
|
415
|
-
|
|
416
|
-
// Verify LEAD_MS was adjusted
|
|
417
|
-
expect(tunnel.LEAD_MS).toBe(30000);
|
|
418
|
-
});
|
|
419
|
-
});
|
|
420
|
-
|
|
421
|
-
// CLI-RES-REFRESH-FALLBACK: Tests for lease-preserving fallback
|
|
422
|
-
describe('CLI-RES-REFRESH-FALLBACK: Lease-preserving fallback', () => {
|
|
423
|
-
let exitSpy;
|
|
424
|
-
|
|
425
|
-
beforeEach(() => {
|
|
426
|
-
jest.resetModules();
|
|
427
|
-
jest.clearAllMocks();
|
|
428
|
-
exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => undefined);
|
|
429
|
-
});
|
|
430
|
-
|
|
431
|
-
afterEach(() => {
|
|
432
|
-
exitSpy.mockRestore();
|
|
433
|
-
});
|
|
434
|
-
|
|
435
|
-
test('fallback reuses leaseId via refreshOf when refresh times out', async () => {
|
|
436
|
-
const waitForControlPlane = jest.fn(async () => {});
|
|
437
|
-
const isControlPlaneConnected = jest.fn(() => true);
|
|
438
|
-
const { tunnel, logger, coordinatorCore, coordinatorIngress } = await createHttpTunnel({
|
|
439
|
-
waitForControlPlane,
|
|
440
|
-
isControlPlaneConnected
|
|
441
|
-
});
|
|
442
|
-
|
|
443
|
-
const assignmentMod = await import('../../state/assignment.js');
|
|
444
|
-
// Initial assignment (for refresh attempt)
|
|
445
|
-
assignmentMod.getAssignment.mockReturnValueOnce({
|
|
446
|
-
leaseId: 'existing-lease-123',
|
|
447
|
-
relayId: 'relay-001',
|
|
448
|
-
jwt: 'current.jwt',
|
|
449
|
-
relayUrl: 'wss://relay.example/agent'
|
|
450
|
-
});
|
|
451
|
-
// For fallback start
|
|
452
|
-
assignmentMod.getAssignment.mockReturnValueOnce({
|
|
453
|
-
leaseId: 'existing-lease-123',
|
|
454
|
-
relayId: 'relay-001',
|
|
455
|
-
jwt: 'current.jwt',
|
|
456
|
-
relayUrl: 'wss://relay.example/agent'
|
|
457
|
-
});
|
|
458
|
-
// After fallback ack is received
|
|
459
|
-
assignmentMod.getAssignment.mockReturnValue({
|
|
460
|
-
leaseId: 'existing-lease-123', // Same leaseId
|
|
461
|
-
relayId: 'relay-001',
|
|
462
|
-
jwt: 'refreshed.jwt',
|
|
463
|
-
requestId: 'refresh-fallback-456',
|
|
464
|
-
relayUrl: 'wss://relay.example/agent'
|
|
465
|
-
});
|
|
466
|
-
|
|
467
|
-
const refreshPromise = tunnel.attemptJwtRefresh();
|
|
468
|
-
|
|
469
|
-
// Wait for initial refresh publish
|
|
470
|
-
while (coordinatorCore.publish.mock.calls.length === 0) {
|
|
471
|
-
await new Promise(r => setImmediate(r));
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
// Timeout the initial refresh to trigger fallback
|
|
475
|
-
coordinatorIngress.rejectAll(new Error('ack timeout'));
|
|
476
|
-
|
|
477
|
-
// Wait for fallback publish
|
|
478
|
-
while (coordinatorCore.publish.mock.calls.length < 2) {
|
|
479
|
-
await new Promise(r => setImmediate(r));
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
// Verify fallback payload preserves lease
|
|
483
|
-
const fallbackPublishCall = coordinatorCore.publish.mock.calls.at(-1)[0];
|
|
484
|
-
const fallbackPayload = JSON.parse(fallbackPublishCall.payload);
|
|
485
|
-
|
|
486
|
-
expect(fallbackPayload.refreshOf).toBe('existing-lease-123');
|
|
487
|
-
expect(fallbackPayload.reconnect).toBe(false);
|
|
488
|
-
expect(fallbackPayload.proto).toBe('http');
|
|
489
|
-
|
|
490
|
-
// Resolve fallback ack - this triggers setAssignment via handlers.js
|
|
491
|
-
// In real code, setAssignment is called by the MQTT handler
|
|
492
|
-
// For test, we need to simulate that the assignment was set
|
|
493
|
-
coordinatorIngress.resolve({
|
|
494
|
-
type: 'open_ack',
|
|
495
|
-
requestId: fallbackPayload.requestId,
|
|
496
|
-
correlationId: 'existing-lease-123', // Same leaseId
|
|
497
|
-
data: {
|
|
498
|
-
relayId: 'relay-001',
|
|
499
|
-
leaseMs: 3600000,
|
|
500
|
-
assignment: {
|
|
501
|
-
jwt: 'refreshed.jwt',
|
|
502
|
-
fqdn: 'relay.example',
|
|
503
|
-
proto: 'wss',
|
|
504
|
-
path: '/agent'
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
});
|
|
508
|
-
|
|
509
|
-
await refreshPromise;
|
|
510
|
-
await new Promise(r => setImmediate(r)); // Allow async handlers
|
|
511
|
-
await new Promise(r => setTimeout(r, 50)); // Extra delay for fallback completion
|
|
512
|
-
|
|
513
|
-
// Verify structured logs
|
|
514
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
515
|
-
'jwt.refresh.fallback.start',
|
|
516
|
-
expect.objectContaining({
|
|
517
|
-
leaseId: 'existing-lease-123',
|
|
518
|
-
relayId: 'relay-001',
|
|
519
|
-
reason: 'refresh_timeout_or_publish_failure'
|
|
520
|
-
})
|
|
521
|
-
);
|
|
522
|
-
expect(logger.info).toHaveBeenCalledWith(
|
|
523
|
-
'jwt.refresh.fallback.request.sent',
|
|
524
|
-
expect.objectContaining({
|
|
525
|
-
leaseId: 'existing-lease-123',
|
|
526
|
-
relayId: 'relay-001'
|
|
527
|
-
})
|
|
528
|
-
);
|
|
529
|
-
// Note: success log requires assignment to be set, which happens via handler
|
|
530
|
-
// In test, this may not fire if handler doesn't run, so we verify the payload instead
|
|
531
|
-
expect(fallbackPayload.refreshOf).toBe('existing-lease-123');
|
|
532
|
-
});
|
|
533
|
-
|
|
534
|
-
test('fallback checks control-plane connectivity', async () => {
|
|
535
|
-
const waitForControlPlane = jest.fn(async () => {});
|
|
536
|
-
const isControlPlaneConnected = jest.fn(() => false); // Control-plane offline
|
|
537
|
-
|
|
538
|
-
const { tunnel, logger, coordinatorCore, coordinatorIngress } = await createHttpTunnel({
|
|
539
|
-
waitForControlPlane,
|
|
540
|
-
isControlPlaneConnected
|
|
541
|
-
});
|
|
542
|
-
|
|
543
|
-
const assignmentMod = await import('../../state/assignment.js');
|
|
544
|
-
assignmentMod.getAssignment.mockReturnValue({
|
|
545
|
-
leaseId: 'lease-001',
|
|
546
|
-
relayId: 'relay-001',
|
|
547
|
-
jwt: 'current.jwt'
|
|
548
|
-
});
|
|
549
|
-
|
|
550
|
-
// Start refresh - it will timeout and trigger fallback
|
|
551
|
-
const refreshPromise = tunnel.attemptJwtRefresh().catch(() => {});
|
|
552
|
-
|
|
553
|
-
// Wait for refresh attempt
|
|
554
|
-
while (coordinatorCore.publish.mock.calls.length === 0) {
|
|
555
|
-
await new Promise(r => setImmediate(r));
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
// Timeout to trigger fallback
|
|
559
|
-
coordinatorIngress.rejectAll(new Error('timeout'));
|
|
560
|
-
|
|
561
|
-
// Wait briefly for fallback to start
|
|
562
|
-
await new Promise(r => setTimeout(r, 100));
|
|
563
|
-
|
|
564
|
-
// Control-plane should be checked during fallback
|
|
565
|
-
expect(isControlPlaneConnected).toHaveBeenCalled();
|
|
566
|
-
|
|
567
|
-
// Cleanup - don't wait for full completion
|
|
568
|
-
refreshPromise.catch(() => {});
|
|
569
|
-
});
|
|
570
|
-
|
|
571
|
-
test('fallback uses refreshOf in payload', async () => {
|
|
572
|
-
const waitForControlPlane = jest.fn(async () => {});
|
|
573
|
-
const isControlPlaneConnected = jest.fn(() => true);
|
|
574
|
-
const { tunnel, coordinatorCore, coordinatorIngress } = await createHttpTunnel({
|
|
575
|
-
waitForControlPlane,
|
|
576
|
-
isControlPlaneConnected
|
|
577
|
-
});
|
|
578
|
-
|
|
579
|
-
const assignmentMod = await import('../../state/assignment.js');
|
|
580
|
-
assignmentMod.getAssignment.mockReturnValue({
|
|
581
|
-
leaseId: 'existing-lease-999',
|
|
582
|
-
relayId: 'relay-001',
|
|
583
|
-
jwt: 'current.jwt'
|
|
584
|
-
});
|
|
585
|
-
|
|
586
|
-
// Start refresh that will timeout
|
|
587
|
-
const refreshPromise = tunnel.attemptJwtRefresh().catch(() => {});
|
|
588
|
-
|
|
589
|
-
// Wait for initial publish
|
|
590
|
-
while (coordinatorCore.publish.mock.calls.length === 0) {
|
|
591
|
-
await new Promise(r => setImmediate(r));
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
// Timeout to trigger fallback
|
|
595
|
-
coordinatorIngress.rejectAll(new Error('timeout'));
|
|
596
|
-
|
|
597
|
-
// Wait for fallback publish
|
|
598
|
-
while (coordinatorCore.publish.mock.calls.length < 2) {
|
|
599
|
-
await new Promise(r => setImmediate(r));
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
// Verify fallback payload contains refreshOf
|
|
603
|
-
const fallbackCall = coordinatorCore.publish.mock.calls.at(-1)[0];
|
|
604
|
-
const fallbackPayload = JSON.parse(fallbackCall.payload);
|
|
605
|
-
|
|
606
|
-
expect(fallbackPayload).toHaveProperty('refreshOf', 'existing-lease-999');
|
|
607
|
-
expect(fallbackPayload).toHaveProperty('reconnect', false);
|
|
608
|
-
|
|
609
|
-
refreshPromise.catch(() => {}); // Cleanup
|
|
610
|
-
});
|
|
611
|
-
});
|
|
612
|
-
|
|
613
|
-
describe('CLI-REAUTH: In-band reauth', () => {
|
|
614
|
-
let exitSpy;
|
|
615
|
-
beforeEach(async () => {
|
|
616
|
-
jest.resetModules(); // Harmless but doesn't reset ESM cache
|
|
617
|
-
jest.clearAllMocks();
|
|
618
|
-
jest.useRealTimers(); // Ensure real timers, clear any fake timers from previous tests
|
|
619
|
-
exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => undefined);
|
|
620
|
-
// Clear control frame waiters between tests (explicit reset for module-level state)
|
|
621
|
-
const wsControl = await import('../ws-control.js');
|
|
622
|
-
const cleanupPromise = wsControl.clearAllWaiters(); // Rejects any pending waiters
|
|
623
|
-
if (cleanupPromise) {
|
|
624
|
-
await cleanupPromise.catch(() => {}); // Suppress rejections
|
|
625
|
-
}
|
|
626
|
-
});
|
|
627
|
-
|
|
628
|
-
afterEach(async () => {
|
|
629
|
-
// Ensure cleanup even if test fails - prevent state leakage between tests
|
|
630
|
-
const wsControl = await import('../ws-control.js');
|
|
631
|
-
const cleanupPromise = wsControl.clearAllWaiters(); // Clean up any remaining waiters
|
|
632
|
-
if (cleanupPromise) {
|
|
633
|
-
await cleanupPromise.catch(() => {}); // Suppress any rejections
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
// Ensure all timers are cleared (only if fake timers are active)
|
|
637
|
-
try {
|
|
638
|
-
if (jest.isMockFunction(setTimeout)) {
|
|
639
|
-
jest.runOnlyPendingTimers();
|
|
640
|
-
}
|
|
641
|
-
} catch {}
|
|
642
|
-
jest.useRealTimers(); // Reset timers after test
|
|
643
|
-
|
|
644
|
-
exitSpy.mockRestore();
|
|
645
|
-
|
|
646
|
-
// Give event loop a chance to process any pending operations
|
|
647
|
-
await new Promise(resolve => setImmediate(resolve));
|
|
648
|
-
});
|
|
649
|
-
|
|
650
|
-
const buildJwt = (expSecondsFromNow = 3600) => {
|
|
651
|
-
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
652
|
-
const header = Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url');
|
|
653
|
-
const payload = Buffer.from(JSON.stringify({
|
|
654
|
-
exp: nowSeconds + expSecondsFromNow,
|
|
655
|
-
iat: nowSeconds - 60,
|
|
656
|
-
jti: `jti-${Math.random().toString(16).slice(2, 8)}`
|
|
657
|
-
})).toString('base64url');
|
|
658
|
-
const signature = 'sig';
|
|
659
|
-
return {
|
|
660
|
-
token: `${header}.${payload}.${signature}`,
|
|
661
|
-
exp: nowSeconds + expSecondsFromNow
|
|
662
|
-
};
|
|
663
|
-
};
|
|
664
|
-
test('reauthInBand returns true and updates state when ack is ok', async () => {
|
|
665
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
666
|
-
|
|
667
|
-
// Mock WebSocket as open with message event emitter
|
|
668
|
-
const mockSend = jest.fn();
|
|
669
|
-
const messageListeners = [];
|
|
670
|
-
const mockWs = {
|
|
671
|
-
readyState: 1, // OPEN
|
|
672
|
-
send: mockSend,
|
|
673
|
-
on: jest.fn((event, handler) => {
|
|
674
|
-
if (event === 'message') {
|
|
675
|
-
messageListeners.push(handler);
|
|
676
|
-
}
|
|
677
|
-
}),
|
|
678
|
-
emit: jest.fn((event, data) => {
|
|
679
|
-
if (event === 'message') {
|
|
680
|
-
messageListeners.forEach(listener => listener(data));
|
|
681
|
-
}
|
|
682
|
-
})
|
|
683
|
-
};
|
|
684
|
-
tunnel.ws = mockWs;
|
|
685
|
-
|
|
686
|
-
const assignmentMod = await import('../../state/assignment.js');
|
|
687
|
-
assignmentMod.getAssignment.mockReturnValue({
|
|
688
|
-
leaseId: 'lease-001',
|
|
689
|
-
requestId: 'req-001',
|
|
690
|
-
relayId: 'relay-001'
|
|
691
|
-
});
|
|
692
|
-
|
|
693
|
-
const { token: newJwt } = buildJwt();
|
|
694
|
-
const prevJti = 'old-jti';
|
|
695
|
-
|
|
696
|
-
// Start reauth and simulate ack response
|
|
697
|
-
const reauthPromise = tunnel.reauthInBand(newJwt, prevJti);
|
|
698
|
-
|
|
699
|
-
// Wait for send to be called
|
|
700
|
-
while (mockSend.mock.calls.length === 0) {
|
|
701
|
-
await new Promise(r => setImmediate(r));
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
// Simulate receiving reauth_ack
|
|
705
|
-
const ackExp = Math.floor(Date.now() / 1000) + 3600;
|
|
706
|
-
const ackFrame = JSON.stringify({
|
|
707
|
-
op: 'reauth_ack',
|
|
708
|
-
status: 'ok',
|
|
709
|
-
active: { jti: 'new-jti', exp: ackExp }
|
|
710
|
-
});
|
|
711
|
-
|
|
712
|
-
// Dispatch via message handler
|
|
713
|
-
const { dispatchControlFrame } = await import('../ws-control.js');
|
|
714
|
-
const dispatched = dispatchControlFrame(JSON.parse(ackFrame));
|
|
715
|
-
expect(dispatched).toBe(true);
|
|
716
|
-
|
|
717
|
-
const result = await reauthPromise;
|
|
718
|
-
|
|
719
|
-
expect(result).toBe(true);
|
|
720
|
-
expect(tunnel.jwt).toBe(newJwt);
|
|
721
|
-
expect(tunnel.jwtMeta.token).toBe(newJwt);
|
|
722
|
-
expect(logger.info).toHaveBeenCalledWith('jwt.reauth.ok', expect.objectContaining({
|
|
723
|
-
leadSeconds: expect.any(Number),
|
|
724
|
-
relayId: 'relay-001'
|
|
725
|
-
}));
|
|
726
|
-
});
|
|
727
|
-
|
|
728
|
-
test('reauthInBand returns false on timeout', async () => {
|
|
729
|
-
jest.useFakeTimers();
|
|
730
|
-
try {
|
|
731
|
-
const { tunnel, logger } = await createHttpTunnel();
|
|
732
|
-
|
|
733
|
-
const mockSend = jest.fn();
|
|
734
|
-
const mockWs = {
|
|
735
|
-
readyState: 1,
|
|
736
|
-
send: mockSend
|
|
737
|
-
};
|
|
738
|
-
tunnel.ws = mockWs;
|
|
739
|
-
tunnel.reauthAckTimeoutMs = 3000; // Set timeout
|
|
740
|
-
|
|
741
|
-
const assignmentMod = await import('../../state/assignment.js');
|
|
742
|
-
assignmentMod.getAssignment.mockReturnValue({
|
|
743
|
-
leaseId: 'lease-001',
|
|
744
|
-
requestId: 'req-001',
|
|
745
|
-
relayId: 'relay-001'
|
|
746
|
-
});
|
|
747
|
-
|
|
748
|
-
const reauthPromise = tunnel.reauthInBand('new.jwt', 'old-jti');
|
|
749
|
-
|
|
750
|
-
// Wait for send
|
|
751
|
-
await jest.advanceTimersByTimeAsync(10);
|
|
752
|
-
|
|
753
|
-
// Advance past timeout (no ack received)
|
|
754
|
-
await jest.advanceTimersByTimeAsync(3000);
|
|
755
|
-
|
|
756
|
-
const result = await reauthPromise;
|
|
757
|
-
|
|
758
|
-
expect(result).toBe(false);
|
|
759
|
-
expect(logger.warn).toHaveBeenCalledWith('jwt.reauth.error', expect.objectContaining({ code: 'timeout' }));
|
|
760
|
-
} finally {
|
|
761
|
-
// Ensure fake timers are cleaned up
|
|
762
|
-
jest.runOnlyPendingTimers();
|
|
763
|
-
jest.useRealTimers();
|
|
764
|
-
// Clear any remaining waiters
|
|
765
|
-
const wsControl = await import('../ws-control.js');
|
|
766
|
-
wsControl.clearAllWaiters();
|
|
767
|
-
}
|
|
768
|
-
});
|
|
769
|
-
|
|
770
|
-
test('reauthInBand guards against concurrent attempts', async () => {
|
|
771
|
-
const { tunnel } = await createHttpTunnel();
|
|
772
|
-
|
|
773
|
-
const mockSend = jest.fn();
|
|
774
|
-
const mockWs = {
|
|
775
|
-
readyState: 1,
|
|
776
|
-
send: mockSend
|
|
777
|
-
};
|
|
778
|
-
tunnel.ws = mockWs;
|
|
779
|
-
|
|
780
|
-
const assignmentMod = await import('../../state/assignment.js');
|
|
781
|
-
assignmentMod.getAssignment.mockReturnValue({
|
|
782
|
-
leaseId: 'lease-001',
|
|
783
|
-
requestId: 'req-001',
|
|
784
|
-
relayId: 'relay-001'
|
|
785
|
-
});
|
|
786
|
-
|
|
787
|
-
// Start first reauth
|
|
788
|
-
const firstReauth = tunnel.reauthInBand('jwt1', 'jti1');
|
|
789
|
-
|
|
790
|
-
// Verify reauthInFlight is set
|
|
791
|
-
expect(tunnel.reauthInFlight).toBeDefined();
|
|
792
|
-
|
|
793
|
-
// Wait for send to complete (waiter is registered synchronously before send)
|
|
794
|
-
await new Promise(r => setImmediate(r));
|
|
795
|
-
expect(mockSend).toHaveBeenCalledTimes(1);
|
|
796
|
-
|
|
797
|
-
// Import dispatchControlFrame and verify waiter exists
|
|
798
|
-
const wsControlMod = await import('../ws-control.js');
|
|
799
|
-
const { dispatchControlFrame } = wsControlMod;
|
|
800
|
-
|
|
801
|
-
// Verify first reauth is still in flight
|
|
802
|
-
expect(tunnel.reauthInFlight).toBeDefined();
|
|
803
|
-
|
|
804
|
-
// Start second reauth while first is in flight
|
|
805
|
-
const secondReauth = tunnel.reauthInBand('jwt2', 'jti2');
|
|
806
|
-
|
|
807
|
-
// Single-flight guard: second call should return the same promise
|
|
808
|
-
expect(tunnel.reauthInFlight).toBeDefined();
|
|
809
|
-
expect(mockSend).toHaveBeenCalledTimes(1); // Only one send - key behavioral assertion
|
|
810
|
-
|
|
811
|
-
// Dispatch ack frame - this should find the waiter registered by sendControlAndWaitAck
|
|
812
|
-
const ackFrame = {
|
|
813
|
-
op: 'reauth_ack',
|
|
814
|
-
status: 'ok',
|
|
815
|
-
active: { jti: 'new-jti', exp: Math.floor(Date.now() / 1000) + 3600 }
|
|
816
|
-
};
|
|
817
|
-
|
|
818
|
-
// Wait a tick to ensure waiter is fully registered
|
|
819
|
-
await new Promise(r => setImmediate(r));
|
|
820
|
-
|
|
821
|
-
const dispatched = dispatchControlFrame(ackFrame);
|
|
822
|
-
expect(dispatched).toBe(true); // Confirm waiter was found and resolved
|
|
823
|
-
|
|
824
|
-
// Allow promise resolution callbacks to execute
|
|
825
|
-
await new Promise(r => setImmediate(r));
|
|
826
|
-
await new Promise(r => setImmediate(r)); // Extra tick for nested promise chains
|
|
827
|
-
|
|
828
|
-
// Both promises should resolve to true
|
|
829
|
-
const results = await Promise.all([firstReauth, secondReauth]);
|
|
830
|
-
expect(results[0]).toBe(true);
|
|
831
|
-
expect(results[1]).toBe(true);
|
|
832
|
-
expect(tunnel.reauthInFlight).toBeNull();
|
|
833
|
-
}, 10000);
|
|
834
|
-
|
|
835
|
-
test('attemptJwtRefresh tries in-band reauth when WebSocket is open', async () => {
|
|
836
|
-
const { tunnel, logger, coordinatorCore, coordinatorIngress } = await createHttpTunnel();
|
|
837
|
-
|
|
838
|
-
// Mock _attemptConnect to prevent actual reconnect attempts
|
|
839
|
-
tunnel._attemptConnect = jest.fn().mockResolvedValue(undefined);
|
|
840
|
-
|
|
841
|
-
// Mock WebSocket as open
|
|
842
|
-
const mockSend = jest.fn();
|
|
843
|
-
const mockWs = {
|
|
844
|
-
readyState: 1, // OPEN
|
|
845
|
-
send: mockSend
|
|
846
|
-
};
|
|
847
|
-
tunnel.ws = mockWs;
|
|
848
|
-
|
|
849
|
-
const assignmentMod = await import('../../state/assignment.js');
|
|
850
|
-
assignmentMod.getAssignment
|
|
851
|
-
.mockReturnValueOnce({ leaseId: 'lease-001' }) // pre-check
|
|
852
|
-
.mockReturnValueOnce({ // after ack - used for in-band reauth
|
|
853
|
-
leaseId: 'lease-001',
|
|
854
|
-
jwt: 'refreshed.jwt',
|
|
855
|
-
requestId: 'refresh-123',
|
|
856
|
-
relayUrl: 'wss://relay.new/agent',
|
|
857
|
-
relayId: 'relay-001'
|
|
858
|
-
})
|
|
859
|
-
.mockReturnValue({ // Subsequent calls
|
|
860
|
-
leaseId: 'lease-001',
|
|
861
|
-
jwt: 'refreshed.jwt',
|
|
862
|
-
requestId: 'refresh-123',
|
|
863
|
-
relayUrl: 'wss://relay.new/agent',
|
|
864
|
-
relayId: 'relay-001'
|
|
865
|
-
});
|
|
866
|
-
|
|
867
|
-
// Set up JWT metadata for prevJti extraction
|
|
868
|
-
tunnel.jwtMeta = { token: 'old.jwt.token' };
|
|
869
|
-
jest.spyOn(tunnel, '_extractJti').mockReturnValue('old-jti');
|
|
870
|
-
|
|
871
|
-
// Import dispatchControlFrame before starting refresh
|
|
872
|
-
const { dispatchControlFrame } = await import('../ws-control.js');
|
|
873
|
-
|
|
874
|
-
const refreshPromise = tunnel.attemptJwtRefresh();
|
|
875
|
-
|
|
876
|
-
// Wait for MQTT publish
|
|
877
|
-
let publishRetries = 0;
|
|
878
|
-
while (coordinatorCore.publish.mock.calls.length === 0 && publishRetries < 100) {
|
|
879
|
-
await new Promise(r => setImmediate(r));
|
|
880
|
-
publishRetries++;
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
// Resolve open_ack with new assignment
|
|
884
|
-
const publishCall = coordinatorCore.publish.mock.calls.at(-1)[0];
|
|
885
|
-
const payload = JSON.parse(publishCall.payload);
|
|
886
|
-
coordinatorIngress.resolve({ type: 'open_ack', requestId: payload.requestId });
|
|
887
|
-
|
|
888
|
-
// Allow async operations to process open_ack
|
|
889
|
-
await new Promise(r => setImmediate(r));
|
|
890
|
-
|
|
891
|
-
// Wait for reauth send
|
|
892
|
-
let reauthRetries = 0;
|
|
893
|
-
while (mockSend.mock.calls.length === 0 && reauthRetries < 100) {
|
|
894
|
-
await new Promise(r => setImmediate(r));
|
|
895
|
-
reauthRetries++;
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
// Verify reauth frame was sent
|
|
899
|
-
expect(mockSend).toHaveBeenCalled();
|
|
900
|
-
const reauthCall = mockSend.mock.calls.find(call =>
|
|
901
|
-
typeof call[0] === 'string' && call[0].includes('"op":"reauth"')
|
|
902
|
-
);
|
|
903
|
-
expect(reauthCall).toBeDefined();
|
|
904
|
-
const reauthPayload = JSON.parse(reauthCall[0]);
|
|
905
|
-
expect(reauthPayload).toMatchObject({
|
|
906
|
-
op: 'reauth',
|
|
907
|
-
leaseId: 'lease-001',
|
|
908
|
-
jwt: 'refreshed.jwt',
|
|
909
|
-
prev: { jti: 'old-jti' }
|
|
910
|
-
});
|
|
911
|
-
|
|
912
|
-
// Allow waiter registration (happens synchronously in sendControlAndWaitAck)
|
|
913
|
-
await new Promise(r => setImmediate(r));
|
|
914
|
-
|
|
915
|
-
// Dispatch reauth_ack frame promptly
|
|
916
|
-
const ackFrame = {
|
|
917
|
-
op: 'reauth_ack',
|
|
918
|
-
status: 'ok',
|
|
919
|
-
active: { jti: 'new-jti', exp: 1234567890 }
|
|
920
|
-
};
|
|
921
|
-
const dispatched = dispatchControlFrame(ackFrame);
|
|
922
|
-
expect(dispatched).toBe(true); // Confirm waiter was found
|
|
923
|
-
|
|
924
|
-
// Allow promise resolution to propagate through async chain
|
|
925
|
-
await new Promise(r => setImmediate(r));
|
|
926
|
-
await new Promise(r => setImmediate(r)); // Extra tick for nested async operations
|
|
927
|
-
|
|
928
|
-
// Refresh promise should resolve now
|
|
929
|
-
// The promise chain: refreshPromise -> await reauthInBand -> await sendControlAndWaitAck -> dispatchControlFrame resolves
|
|
930
|
-
try {
|
|
931
|
-
await refreshPromise;
|
|
932
|
-
} catch (err) {
|
|
933
|
-
// If it errors, provide context
|
|
934
|
-
console.error('Refresh promise rejected:', {
|
|
935
|
-
error: err.message,
|
|
936
|
-
mockSendCalls: mockSend.mock.calls.length,
|
|
937
|
-
dispatched,
|
|
938
|
-
reauthInFlight: tunnel.reauthInFlight
|
|
939
|
-
});
|
|
940
|
-
throw err;
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
// Verify in-band reauth succeeded
|
|
944
|
-
expect(logger.info).toHaveBeenCalledWith('jwt.reauth.ok', expect.any(Object));
|
|
945
|
-
expect(logger.info).toHaveBeenCalledWith('jwt.refresh.success', expect.objectContaining({ method: 'in_band' }));
|
|
946
|
-
expect(tunnel._attemptConnect).not.toHaveBeenCalled(); // No reconnect when in-band succeeds
|
|
947
|
-
}, 15000);
|
|
948
|
-
});
|