| 1 | // @ts-nocheck |
| 2 | import fetch from "node-fetch"; |
| 3 | import { afterEach, beforeEach, expect, it, vi } from "vitest"; |
| 4 | import { EventEmitter } from "vscode"; |
| 5 | |
| 6 | // Don't import WorkOsAuthProvider directly here |
| 7 | |
| 8 | // Mock the modules we need |
| 9 | vi.mock("vscode", () => ({ |
| 10 | authentication: { |
| 11 | registerAuthenticationProvider: vi.fn(), |
| 12 | }, |
| 13 | window: { |
| 14 | registerUriHandler: vi.fn(), |
| 15 | }, |
| 16 | EventEmitter: vi.fn(() => ({ |
| 17 | event: { dispose: vi.fn() }, |
| 18 | fire: vi.fn(), |
| 19 | })), |
| 20 | Disposable: { |
| 21 | from: vi.fn(() => ({ dispose: vi.fn() })), |
| 22 | }, |
| 23 | env: { |
| 24 | uriScheme: "vscode", |
| 25 | }, |
| 26 | })); |
| 27 | |
| 28 | // Properly mock node-fetch |
| 29 | vi.mock("node-fetch", () => { |
| 30 | return { |
| 31 | __esModule: true, |
| 32 | default: vi.fn(), |
| 33 | }; |
| 34 | }); |
| 35 | |
| 36 | vi.mock("core/control-plane/env", () => ({ |
| 37 | getControlPlaneEnvSync: vi.fn(() => ({ |
| 38 | AUTH_TYPE: "workos", |
| 39 | APP_URL: "https://continue.dev", |
| 40 | CONTROL_PLANE_URL: "https://api.continue.dev", |
| 41 | WORKOS_CLIENT_ID: "client_123", |
| 42 | })), |
| 43 | })); |
| 44 | |
| 45 | vi.mock("crypto", () => ({ |
| 46 | createHash: vi.fn(() => ({ |
| 47 | update: vi.fn(() => ({ |
| 48 | digest: vi.fn(() => Buffer.from("test-hash")), |
| 49 | })), |
| 50 | })), |
| 51 | })); |
| 52 | |
| 53 | // Create a simple SecretStorage mock that we can control |
| 54 | const mockSecretStorageGet = vi.fn(); |
| 55 | const mockSecretStorageStore = vi.fn(); |
| 56 | |
| 57 | // Mock SecretStorage class |
| 58 | vi.mock("./SecretStorage", () => { |
| 59 | return { |
| 60 | SecretStorage: vi.fn().mockImplementation(() => ({ |
| 61 | store: mockSecretStorageStore, |
| 62 | get: mockSecretStorageGet, |
| 63 | })), |
| 64 | }; |
| 65 | }); |
| 66 | |
| 67 | // Helper to create valid and expired JWTs |
| 68 | function createJwt({ expired }: { expired: boolean }): string { |
| 69 | const now = Math.floor(Date.now() / 1000); |
| 70 | const header = { alg: "HS256", typ: "JWT" }; |
| 71 | const payload = { |
| 72 | sub: "user123", |
| 73 | iat: now, |
| 74 | exp: expired ? now - 3600 : now + 3600, // Expired 1 hour ago or valid for 1 hour |
| 75 | }; |
| 76 | |
| 77 | const base64Header = Buffer.from(JSON.stringify(header)) |
| 78 | .toString("base64") |
| 79 | .replace(/=/g, ""); |
| 80 | const base64Payload = Buffer.from(JSON.stringify(payload)) |
| 81 | .toString("base64") |
| 82 | .replace(/=/g, ""); |
| 83 | const signature = "dummysignature"; |
| 84 | |
| 85 | return `${base64Header}.${base64Payload}.${signature}`; |
| 86 | } |
| 87 | |
| 88 | beforeEach(() => { |
| 89 | // Set up fake timers before each test |
| 90 | vi.useFakeTimers(); |
| 91 | }); |
| 92 | |
| 93 | afterEach(() => { |
| 94 | vi.clearAllMocks(); |
| 95 | vi.clearAllTimers(); |
| 96 | vi.useRealTimers(); // Restore real timers after each test |
| 97 | }); |
| 98 | |
| 99 | it("should refresh tokens on initialization when sessions exist", async () => { |
| 100 | // Mock setInterval to prevent the refresh interval |
| 101 | const originalSetInterval = global.setInterval; |
| 102 | global.setInterval = vi.fn().mockReturnValue(123 as any); |
| 103 | |
| 104 | // Setup existing sessions with a valid token |
| 105 | const validToken = createJwt({ expired: false }); |
| 106 | const mockSession = { |
| 107 | id: "test-id", |
| 108 | accessToken: validToken, |
| 109 | refreshToken: "refresh-token", |
| 110 | expiresInMs: 3600000, // 1 hour |
| 111 | account: { label: "Test User", id: "user@example.com" }, |
| 112 | scopes: [], |
| 113 | loginNeeded: false, |
| 114 | }; |
| 115 | |
| 116 | // Setup fetch mock |
| 117 | const fetchMock = fetch as any; |
| 118 | fetchMock.mockClear(); |
| 119 | |
| 120 | // Setup successful token refresh |
| 121 | fetchMock.mockResolvedValueOnce({ |
| 122 | ok: true, |
| 123 | json: async () => ({ |
| 124 | accessToken: createJwt({ expired: false }), |
| 125 | refreshToken: "new-refresh-token", |
| 126 | }), |
| 127 | text: async () => "", |
| 128 | }); |
| 129 | |
| 130 | // Create a mock UriHandler |
| 131 | const mockUriHandler = { |
| 132 | event: new EventEmitter(), |
| 133 | handleCallback: vi.fn(), |
| 134 | }; |
| 135 | |
| 136 | // Create a mock ExtensionContext |
| 137 | const mockContext = { |
| 138 | secrets: { |
| 139 | store: vi.fn(), |
| 140 | get: vi.fn(), |
| 141 | }, |
| 142 | subscriptions: [], |
| 143 | }; |
| 144 | |
| 145 | // Set up our SecretStorage mock to return the session |
| 146 | mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); |
| 147 | |
| 148 | // Import WorkOsAuthProvider after setting up all mocks |
| 149 | const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); |
| 150 | |
| 151 | // Create provider instance - this will automatically call refreshSessions |
| 152 | const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); |
| 153 | |
| 154 | // Wait for all promises to resolve, including any nested promise chains |
| 155 | await new Promise(process.nextTick); |
| 156 | |
| 157 | // Verify that the token refresh endpoint was called |
| 158 | expect(fetchMock).toHaveBeenCalledWith( |
| 159 | expect.any(URL), |
| 160 | expect.objectContaining({ |
| 161 | method: "POST", |
| 162 | body: expect.stringContaining("refresh-token"), |
| 163 | }), |
| 164 | ); |
| 165 | |
| 166 | // Restore setInterval |
| 167 | global.setInterval = originalSetInterval; |
| 168 | |
| 169 | // Clean up |
| 170 | if (provider._refreshInterval) { |
| 171 | clearInterval(provider._refreshInterval); |
| 172 | provider._refreshInterval = null; |
| 173 | } |
| 174 | }); |
| 175 | |
| 176 | it("should not remove sessions during transient network errors", async () => { |
| 177 | // Setup existing sessions with a valid token |
| 178 | const validToken = createJwt({ expired: false }); |
| 179 | const mockSession = { |
| 180 | id: "test-id", |
| 181 | accessToken: validToken, |
| 182 | refreshToken: "refresh-token", |
| 183 | expiresInMs: 300000, // 5 minutes |
| 184 | account: { label: "Test User", id: "user@example.com" }, |
| 185 | scopes: [], |
| 186 | loginNeeded: false, |
| 187 | }; |
| 188 | |
| 189 | // Setup fetch mock |
| 190 | const fetchMock = fetch as any; |
| 191 | fetchMock.mockClear(); |
| 192 | |
| 193 | // First refresh attempt fails with network error |
| 194 | fetchMock.mockRejectedValueOnce(new Error("Network error")); |
| 195 | |
| 196 | // Second refresh attempt should succeed |
| 197 | fetchMock.mockResolvedValueOnce({ |
| 198 | ok: true, |
| 199 | json: async () => ({ |
| 200 | accessToken: createJwt({ expired: false }), |
| 201 | refreshToken: "new-refresh-token", |
| 202 | }), |
| 203 | text: async () => "", |
| 204 | }); |
| 205 | |
| 206 | // Create a mock UriHandler |
| 207 | const mockUriHandler = { |
| 208 | event: new EventEmitter(), |
| 209 | handleCallback: vi.fn(), |
| 210 | }; |
| 211 | |
| 212 | // Create a mock ExtensionContext |
| 213 | const mockContext = { |
| 214 | secrets: { |
| 215 | store: vi.fn(), |
| 216 | get: vi.fn(), |
| 217 | }, |
| 218 | subscriptions: [], |
| 219 | }; |
| 220 | |
| 221 | // Set up our SecretStorage mock to return the session |
| 222 | mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); |
| 223 | |
| 224 | // Import WorkOsAuthProvider after setting up all mocks |
| 225 | const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); |
| 226 | |
| 227 | // Allow setInterval to work normally with fake timers |
| 228 | // We're not mocking it anymore, instead we'll control when it fires |
| 229 | |
| 230 | // Create provider instance - this will automatically call refreshSessions with the network error |
| 231 | const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); |
| 232 | |
| 233 | // Run microtasks to process promises from the initial refresh call |
| 234 | await Promise.resolve(); |
| 235 | |
| 236 | // Check that sessions were not cleared after network error |
| 237 | expect(mockSecretStorageStore).not.toHaveBeenCalledWith( |
| 238 | expect.anything(), |
| 239 | expect.stringMatching(/\[\]/), |
| 240 | ); |
| 241 | |
| 242 | // Reset the fetch mock call count to verify the next call |
| 243 | fetchMock.mockClear(); |
| 244 | |
| 245 | // Advance timers to the next refresh interval to simulate the timer firing |
| 246 | vi.advanceTimersByTime(WorkOsAuthProvider.REFRESH_INTERVAL_MS); |
| 247 | |
| 248 | // Run microtasks to process promises from the interval-triggered refresh |
| 249 | await Promise.resolve(); |
| 250 | |
| 251 | // Verify the second attempt was made via the interval |
| 252 | expect(fetchMock).toHaveBeenCalledTimes(1); |
| 253 | expect(fetchMock).toHaveBeenCalledWith( |
| 254 | expect.any(URL), |
| 255 | expect.objectContaining({ |
| 256 | method: "POST", |
| 257 | headers: expect.objectContaining({ |
| 258 | "Content-Type": "application/json", |
| 259 | }), |
| 260 | body: expect.stringContaining("refresh-token"), |
| 261 | }), |
| 262 | ); |
| 263 | |
| 264 | // Clean up |
| 265 | if (provider._refreshInterval) { |
| 266 | clearInterval(provider._refreshInterval); |
| 267 | provider._refreshInterval = null; |
| 268 | } |
| 269 | }); |
| 270 | |
| 271 | it("should refresh tokens at regular intervals rather than based on expiration", async () => { |
| 272 | // Setup existing sessions with a valid token |
| 273 | const validToken = createJwt({ expired: false }); |
| 274 | const mockSession = { |
| 275 | id: "test-id", |
| 276 | accessToken: validToken, |
| 277 | refreshToken: "refresh-token", |
| 278 | expiresInMs: 3600000, // 1 hour |
| 279 | account: { label: "Test User", id: "user@example.com" }, |
| 280 | scopes: [], |
| 281 | loginNeeded: false, |
| 282 | }; |
| 283 | |
| 284 | // Setup fetch mock |
| 285 | const fetchMock = fetch as any; |
| 286 | fetchMock.mockClear(); |
| 287 | |
| 288 | // Setup successful token refresh responses for multiple calls |
| 289 | fetchMock.mockResolvedValue({ |
| 290 | ok: true, |
| 291 | json: async () => ({ |
| 292 | accessToken: createJwt({ expired: false }), |
| 293 | refreshToken: "new-refresh-token", |
| 294 | }), |
| 295 | text: async () => "", |
| 296 | }); |
| 297 | |
| 298 | // Create a mock UriHandler |
| 299 | const mockUriHandler = { |
| 300 | event: new EventEmitter(), |
| 301 | handleCallback: vi.fn(), |
| 302 | }; |
| 303 | |
| 304 | // Create a mock ExtensionContext |
| 305 | const mockContext = { |
| 306 | secrets: { |
| 307 | store: vi.fn(), |
| 308 | get: vi.fn(), |
| 309 | }, |
| 310 | subscriptions: [], |
| 311 | }; |
| 312 | |
| 313 | // Set up our SecretStorage mock to return the session |
| 314 | mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); |
| 315 | |
| 316 | // Import WorkOsAuthProvider after setting up all mocks |
| 317 | const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); |
| 318 | |
| 319 | // Capture the original setInterval to restore it later |
| 320 | const originalSetInterval = global.setInterval; |
| 321 | |
| 322 | // Create our own implementation of setInterval that we can control better |
| 323 | let intervalCallback: Function; |
| 324 | global.setInterval = vi.fn((callback, ms) => { |
| 325 | intervalCallback = callback; |
| 326 | return 123 as any; // Return a dummy interval ID |
| 327 | }); |
| 328 | |
| 329 | // Create provider instance - this will automatically call refreshSessions |
| 330 | const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); |
| 331 | |
| 332 | // Wait for all promises to resolve, including any nested promise chains |
| 333 | await new Promise(process.nextTick); |
| 334 | |
| 335 | // First refresh should happen immediately on initialization |
| 336 | expect(fetchMock).toHaveBeenCalledTimes(1); |
| 337 | fetchMock.mockClear(); |
| 338 | |
| 339 | // Verify that setInterval was called to set up regular refreshes |
| 340 | expect(global.setInterval).toHaveBeenCalled(); |
| 341 | |
| 342 | // Get the interval time from the call to setInterval |
| 343 | const intervalTime = (global.setInterval as any).mock.calls[0][1]; |
| 344 | |
| 345 | // Should be a reasonable interval (less than the expiration time) |
| 346 | expect(intervalTime).toBeLessThan(mockSession.expiresInMs); |
| 347 | |
| 348 | // Now manually trigger the interval callback - First interval |
| 349 | intervalCallback(); |
| 350 | |
| 351 | // Wait for all promises to resolve |
| 352 | await new Promise(process.nextTick); |
| 353 | |
| 354 | // Verify that refresh was called again when the interval callback fired |
| 355 | expect(fetchMock).toHaveBeenCalledTimes(1); |
| 356 | |
| 357 | // Check that we're making refresh calls to the right endpoint with the right data |
| 358 | expect(fetchMock).toHaveBeenCalledWith( |
| 359 | expect.objectContaining({ pathname: "/auth/refresh" }), |
| 360 | expect.objectContaining({ |
| 361 | method: "POST", |
| 362 | headers: expect.objectContaining({ |
| 363 | "Content-Type": "application/json", |
| 364 | }), |
| 365 | body: expect.stringContaining("refresh-token"), |
| 366 | }), |
| 367 | ); |
| 368 | |
| 369 | // Clear mock calls for the second interval test |
| 370 | fetchMock.mockClear(); |
| 371 | |
| 372 | // Trigger the callback again - Second interval |
| 373 | intervalCallback(); |
| 374 | |
| 375 | // Wait for all promises to resolve |
| 376 | await new Promise(process.nextTick); |
| 377 | |
| 378 | // Verify the refresh was called a second time |
| 379 | expect(fetchMock).toHaveBeenCalledTimes(1); |
| 380 | |
| 381 | // Verify the second call has the same correct parameters |
| 382 | expect(fetchMock).toHaveBeenCalledWith( |
| 383 | expect.objectContaining({ pathname: "/auth/refresh" }), |
| 384 | expect.objectContaining({ |
| 385 | method: "POST", |
| 386 | headers: expect.objectContaining({ |
| 387 | "Content-Type": "application/json", |
| 388 | }), |
| 389 | body: expect.stringContaining("refresh-token"), |
| 390 | }), |
| 391 | ); |
| 392 | |
| 393 | // Restore the original setInterval |
| 394 | global.setInterval = originalSetInterval; |
| 395 | |
| 396 | // Clean up |
| 397 | if (provider._refreshInterval) { |
| 398 | clearInterval(provider._refreshInterval); |
| 399 | provider._refreshInterval = null; |
| 400 | } |
| 401 | }); |
| 402 | |
| 403 | it("should remove session if token refresh fails with authentication error", async () => { |
| 404 | // Setup existing sessions with a valid token |
| 405 | const validToken = createJwt({ expired: false }); |
| 406 | const mockSession = { |
| 407 | id: "test-id", |
| 408 | accessToken: validToken, |
| 409 | refreshToken: "invalid-refresh-token", |
| 410 | expiresInMs: 300000, // 5 minutes |
| 411 | account: { label: "Test User", id: "user@example.com" }, |
| 412 | scopes: [], |
| 413 | loginNeeded: false, |
| 414 | }; |
| 415 | |
| 416 | // Setup fetch mock |
| 417 | const fetchMock = fetch as any; |
| 418 | fetchMock.mockClear(); |
| 419 | |
| 420 | // Setup refresh to fail with 401 unauthorized |
| 421 | fetchMock.mockResolvedValueOnce({ |
| 422 | ok: false, |
| 423 | status: 401, |
| 424 | text: async () => "Invalid refresh token", |
| 425 | }); |
| 426 | |
| 427 | // Create a mock UriHandler |
| 428 | const mockUriHandler = { |
| 429 | event: new EventEmitter(), |
| 430 | handleCallback: vi.fn(), |
| 431 | }; |
| 432 | |
| 433 | // Create a mock ExtensionContext |
| 434 | const mockContext = { |
| 435 | secrets: { |
| 436 | store: vi.fn(), |
| 437 | get: vi.fn(), |
| 438 | }, |
| 439 | subscriptions: [], |
| 440 | }; |
| 441 | |
| 442 | // Mock setInterval to prevent continuous refreshes |
| 443 | const originalSetInterval = global.setInterval; |
| 444 | global.setInterval = vi.fn().mockReturnValue(123 as any); |
| 445 | |
| 446 | // Set up our SecretStorage mock to return the session |
| 447 | mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); |
| 448 | mockSecretStorageStore.mockClear(); |
| 449 | |
| 450 | // Import WorkOsAuthProvider after setting up all mocks |
| 451 | const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); |
| 452 | |
| 453 | // Create provider instance - this will automatically call refreshSessions |
| 454 | const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); |
| 455 | |
| 456 | // Wait for all promises to resolve, including any nested promise chains |
| 457 | await new Promise(process.nextTick); |
| 458 | |
| 459 | // Verify that the token refresh endpoint was called |
| 460 | expect(fetchMock).toHaveBeenCalledWith( |
| 461 | expect.any(URL), |
| 462 | expect.objectContaining({ |
| 463 | method: "POST", |
| 464 | body: expect.stringContaining("invalid-refresh-token"), |
| 465 | }), |
| 466 | ); |
| 467 | |
| 468 | // Verify sessions were removed due to auth error |
| 469 | expect(mockSecretStorageStore).toHaveBeenCalledWith( |
| 470 | "workos.sessions", // Use the hard-coded key that matches our mock |
| 471 | expect.stringMatching(/\[\]/), |
| 472 | ); |
| 473 | |
| 474 | // Restore setInterval |
| 475 | global.setInterval = originalSetInterval; |
| 476 | |
| 477 | // Clean up |
| 478 | if (provider._refreshInterval) { |
| 479 | clearInterval(provider._refreshInterval); |
| 480 | provider._refreshInterval = null; |
| 481 | } |
| 482 | }); |
| 483 | |
| 484 | it("should remove session if token refresh returns Unauthorized error message", async () => { |
| 485 | // Setup existing sessions with a valid token |
| 486 | const validToken = createJwt({ expired: false }); |
| 487 | const mockSession = { |
| 488 | id: "test-id", |
| 489 | accessToken: validToken, |
| 490 | refreshToken: "invalid-refresh-token", |
| 491 | expiresInMs: 300000, // 5 minutes |
| 492 | account: { label: "Test User", id: "user@example.com" }, |
| 493 | scopes: [], |
| 494 | loginNeeded: false, |
| 495 | }; |
| 496 | |
| 497 | // Setup fetch mock |
| 498 | const fetchMock = fetch as any; |
| 499 | fetchMock.mockClear(); |
| 500 | |
| 501 | // Setup refresh to return an error containing "Unauthorized" in the message |
| 502 | // Status code doesn't matter here, what matters is the error message text |
| 503 | fetchMock.mockResolvedValueOnce({ |
| 504 | ok: false, |
| 505 | status: 403, // Could be any error code |
| 506 | text: async () => "Unauthorized", |
| 507 | }); |
| 508 | |
| 509 | // Create a mock UriHandler |
| 510 | const mockUriHandler = { |
| 511 | event: new EventEmitter(), |
| 512 | handleCallback: vi.fn(), |
| 513 | }; |
| 514 | |
| 515 | // Create a mock ExtensionContext |
| 516 | const mockContext = { |
| 517 | secrets: { |
| 518 | store: vi.fn(), |
| 519 | get: vi.fn(), |
| 520 | }, |
| 521 | subscriptions: [], |
| 522 | }; |
| 523 | |
| 524 | // Mock setInterval to prevent continuous refreshes |
| 525 | const originalSetInterval = global.setInterval; |
| 526 | global.setInterval = vi.fn().mockReturnValue(123 as any); |
| 527 | |
| 528 | // Set up our SecretStorage mock to return the session |
| 529 | mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); |
| 530 | mockSecretStorageStore.mockClear(); |
| 531 | |
| 532 | // Import WorkOsAuthProvider after setting up all mocks |
| 533 | const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); |
| 534 | |
| 535 | // Create provider instance - this will automatically call refreshSessions |
| 536 | const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); |
| 537 | |
| 538 | // Wait for all promises to resolve, including any nested promise chains |
| 539 | await new Promise(process.nextTick); |
| 540 | |
| 541 | // Verify that the token refresh endpoint was called |
| 542 | expect(fetchMock).toHaveBeenCalledWith( |
| 543 | expect.any(URL), |
| 544 | expect.objectContaining({ |
| 545 | method: "POST", |
| 546 | body: expect.stringContaining("invalid-refresh-token"), |
| 547 | }), |
| 548 | ); |
| 549 | |
| 550 | // Verify sessions were removed due to Unauthorized error message |
| 551 | expect(mockSecretStorageStore).toHaveBeenCalledWith( |
| 552 | "workos.sessions", // Use the hard-coded key that matches our mock |
| 553 | expect.stringMatching(/\[\]/), |
| 554 | ); |
| 555 | |
| 556 | // Restore setInterval |
| 557 | global.setInterval = originalSetInterval; |
| 558 | |
| 559 | // Clean up |
| 560 | if (provider._refreshInterval) { |
| 561 | clearInterval(provider._refreshInterval); |
| 562 | provider._refreshInterval = null; |
| 563 | } |
| 564 | }); |
| 565 | |
| 566 | it("should preserve valid tokens during network errors by retrying", async () => { |
| 567 | // Mock Date.now to return a fixed timestamp for token validation |
| 568 | const originalDateNow = Date.now; |
| 569 | const currentTimestamp = Date.now(); |
| 570 | Date.now = vi.fn(() => currentTimestamp); |
| 571 | |
| 572 | // Setup with a valid token |
| 573 | const validToken = createJwt({ expired: false }); |
| 574 | const validSession = { |
| 575 | id: "valid-id", |
| 576 | accessToken: validToken, |
| 577 | refreshToken: "valid-refresh-token", |
| 578 | expiresInMs: 3600000, |
| 579 | account: { label: "Valid User", id: "valid@example.com" }, |
| 580 | scopes: [], |
| 581 | loginNeeded: false, |
| 582 | }; |
| 583 | |
| 584 | // Setup fetch mock |
| 585 | const fetchMock = fetch as any; |
| 586 | fetchMock.mockClear(); |
| 587 | |
| 588 | // Create mock objects |
| 589 | const mockUriHandler = { event: new EventEmitter(), handleCallback: vi.fn() }; |
| 590 | const mockContext = { |
| 591 | secrets: { store: vi.fn(), get: vi.fn() }, |
| 592 | subscriptions: [], |
| 593 | }; |
| 594 | |
| 595 | // Mock setInterval and setTimeout |
| 596 | const originalSetInterval = global.setInterval; |
| 597 | global.setInterval = vi.fn().mockReturnValue(123 as any); |
| 598 | |
| 599 | const originalSetTimeout = global.setTimeout; |
| 600 | global.setTimeout = vi.fn((callback) => { |
| 601 | callback(); |
| 602 | return 123 as any; |
| 603 | }); |
| 604 | |
| 605 | // Network error followed by success |
| 606 | fetchMock.mockRejectedValueOnce(new Error("Network error")); |
| 607 | fetchMock.mockResolvedValueOnce({ |
| 608 | ok: true, |
| 609 | json: async () => ({ |
| 610 | accessToken: createJwt({ expired: false }), |
| 611 | refreshToken: "new-refresh-token", |
| 612 | }), |
| 613 | text: async () => "", |
| 614 | }); |
| 615 | |
| 616 | // Setup storage |
| 617 | mockSecretStorageGet.mockResolvedValue(JSON.stringify([validSession])); |
| 618 | mockSecretStorageStore.mockClear(); |
| 619 | |
| 620 | // Import and create provider |
| 621 | const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); |
| 622 | const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); |
| 623 | |
| 624 | // Wait for promises to resolve |
| 625 | await new Promise(process.nextTick); |
| 626 | |
| 627 | // Check that a non-empty session array was stored (session was preserved) |
| 628 | const storeCall = mockSecretStorageStore.mock.calls[0]; |
| 629 | expect(storeCall[0]).toBe("workos.sessions"); |
| 630 | expect(JSON.parse(storeCall[1])).toHaveLength(1); // Should contain one session |
| 631 | |
| 632 | // Restore originals |
| 633 | global.setTimeout = originalSetTimeout; |
| 634 | global.setInterval = originalSetInterval; |
| 635 | Date.now = originalDateNow; |
| 636 | |
| 637 | // Clean up provider |
| 638 | if (provider._refreshInterval) { |
| 639 | clearInterval(provider._refreshInterval); |
| 640 | provider._refreshInterval = null; |
| 641 | } |
| 642 | }); |
| 643 | |
| 644 | it("should remove expired tokens when refresh fails with a 401 error", async () => { |
| 645 | // Mock Date.now to return a time that makes tokens appear expired |
| 646 | const originalDateNow = Date.now; |
| 647 | const futureTime = Date.now() + 7200000; // 2 hours in the future |
| 648 | Date.now = vi.fn(() => futureTime); |
| 649 | |
| 650 | // Setup with an expired token |
| 651 | const expiredToken = createJwt({ expired: true }); |
| 652 | const expiredSession = { |
| 653 | id: "expired-id", |
| 654 | accessToken: expiredToken, |
| 655 | refreshToken: "expired-refresh-token", |
| 656 | expiresInMs: 3600000, |
| 657 | account: { label: "Expired User", id: "expired@example.com" }, |
| 658 | scopes: [], |
| 659 | loginNeeded: false, |
| 660 | }; |
| 661 | |
| 662 | // Setup fetch mock |
| 663 | const fetchMock = fetch as any; |
| 664 | fetchMock.mockClear(); |
| 665 | |
| 666 | // Create mock objects |
| 667 | const mockUriHandler = { event: new EventEmitter(), handleCallback: vi.fn() }; |
| 668 | const mockContext = { |
| 669 | secrets: { store: vi.fn(), get: vi.fn() }, |
| 670 | subscriptions: [], |
| 671 | }; |
| 672 | |
| 673 | // Mock setInterval |
| 674 | const originalSetInterval = global.setInterval; |
| 675 | global.setInterval = vi.fn().mockReturnValue(123 as any); |
| 676 | |
| 677 | // Refresh will fail with network error |
| 678 | fetchMock.mockRejectedValueOnce(new Error("401")); |
| 679 | |
| 680 | // Setup storage |
| 681 | mockSecretStorageGet.mockResolvedValue(JSON.stringify([expiredSession])); |
| 682 | mockSecretStorageStore.mockClear(); |
| 683 | |
| 684 | // Import and create provider |
| 685 | const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); |
| 686 | const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); |
| 687 | |
| 688 | // Wait for promises to resolve |
| 689 | await new Promise(process.nextTick); |
| 690 | |
| 691 | // Check that an empty session array was stored (session was removed) |
| 692 | const storeCall = mockSecretStorageStore.mock.calls[0]; |
| 693 | expect(storeCall[0]).toBe("workos.sessions"); |
| 694 | expect(JSON.parse(storeCall[1])).toHaveLength(0); // Should be empty |
| 695 | |
| 696 | // Restore originals |
| 697 | global.setInterval = originalSetInterval; |
| 698 | Date.now = originalDateNow; |
| 699 | |
| 700 | // Clean up provider |
| 701 | if (provider._refreshInterval) { |
| 702 | clearInterval(provider._refreshInterval); |
| 703 | provider._refreshInterval = null; |
| 704 | } |
| 705 | }); |
| 706 | |
| 707 | it("should implement exponential backoff for failed refresh attempts", async () => { |
| 708 | // Setup existing sessions with a valid token |
| 709 | const validToken = createJwt({ expired: false }); |
| 710 | const mockSession = { |
| 711 | id: "test-id", |
| 712 | accessToken: validToken, |
| 713 | refreshToken: "refresh-token", |
| 714 | expiresInMs: 300000, // 5 minutes |
| 715 | account: { label: "Test User", id: "user@example.com" }, |
| 716 | scopes: [], |
| 717 | loginNeeded: false, |
| 718 | }; |
| 719 | |
| 720 | // Setup fetch mock |
| 721 | const fetchMock = fetch as any; |
| 722 | fetchMock.mockClear(); |
| 723 | |
| 724 | // Setup repeated network errors followed by success |
| 725 | fetchMock.mockRejectedValueOnce(new Error("Network error 1")); |
| 726 | fetchMock.mockRejectedValueOnce(new Error("Network error 2")); |
| 727 | fetchMock.mockResolvedValueOnce({ |
| 728 | ok: true, |
| 729 | json: async () => ({ |
| 730 | accessToken: createJwt({ expired: false }), |
| 731 | refreshToken: "new-refresh-token", |
| 732 | }), |
| 733 | text: async () => "", |
| 734 | }); |
| 735 | |
| 736 | // Create a mock UriHandler |
| 737 | const mockUriHandler = { |
| 738 | event: new EventEmitter(), |
| 739 | handleCallback: vi.fn(), |
| 740 | }; |
| 741 | |
| 742 | // Create a mock ExtensionContext |
| 743 | const mockContext = { |
| 744 | secrets: { |
| 745 | store: vi.fn(), |
| 746 | get: vi.fn(), |
| 747 | }, |
| 748 | subscriptions: [], |
| 749 | }; |
| 750 | |
| 751 | // Mock setInterval to prevent continuous refreshes |
| 752 | const originalSetInterval = global.setInterval; |
| 753 | global.setInterval = vi.fn().mockReturnValue(123 as any); |
| 754 | |
| 755 | // Track setTimeout calls |
| 756 | const setTimeoutSpy = vi.spyOn(global, "setTimeout"); |
| 757 | |
| 758 | // Set up our SecretStorage mock to return the session |
| 759 | mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); |
| 760 | |
| 761 | // Import WorkOsAuthProvider after setting up all mocks |
| 762 | const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); |
| 763 | |
| 764 | // Create provider instance - this will automatically call refreshSessions |
| 765 | const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); |
| 766 | |
| 767 | // Wait for all promises to resolve for the initial refresh attempt |
| 768 | await new Promise(process.nextTick); |
| 769 | |
| 770 | // Verify the first fetch attempt was made |
| 771 | expect(fetchMock).toHaveBeenCalledTimes(1); |
| 772 | |
| 773 | // Trigger first retry |
| 774 | vi.advanceTimersByTime(1000); // Initial backoff |
| 775 | await new Promise(process.nextTick); |
| 776 | |
| 777 | // Verify the second fetch attempt was made |
| 778 | expect(fetchMock).toHaveBeenCalledTimes(2); |
| 779 | |
| 780 | // Trigger second retry |
| 781 | vi.advanceTimersByTime(2000); // Double the backoff |
| 782 | await new Promise(process.nextTick); |
| 783 | |
| 784 | // Verify the third fetch attempt was made |
| 785 | expect(fetchMock).toHaveBeenCalledTimes(3); |
| 786 | |
| 787 | // Verify setTimeout was called with increasing delays |
| 788 | expect(setTimeoutSpy).toHaveBeenCalledTimes(2); |
| 789 | |
| 790 | // Check that the backoff periods increased |
| 791 | const firstDelay = setTimeoutSpy.mock.calls[0][1]; |
| 792 | const secondDelay = setTimeoutSpy.mock.calls[1][1]; |
| 793 | |
| 794 | // Check that backoff increased |
| 795 | expect(secondDelay).toBeGreaterThan(firstDelay); |
| 796 | |
| 797 | // Restore setInterval |
| 798 | global.setInterval = originalSetInterval; |
| 799 | |
| 800 | // Clean up |
| 801 | if (provider._refreshInterval) { |
| 802 | clearInterval(provider._refreshInterval); |
| 803 | provider._refreshInterval = null; |
| 804 | } |
| 805 | }); |