|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 BadLabs |
| 3 | + * |
| 4 | + * Use of this software is governed by the Business Source License 1.1 included in the file LICENSE.txt. |
| 5 | + * |
| 6 | + * As of the Change Date specified in that file, in accordance with the Business Source License, use of this software will be governed by the Apache License, version 2.0. |
| 7 | + */ |
| 8 | + |
| 9 | +import { subtle } from 'node:crypto' |
| 10 | +import { setTimeout as sleep } from 'node:timers/promises' |
| 11 | +import { describe, expect, it, vi } from 'vitest' |
| 12 | +import { ExecutionContext } from '../execution-context' |
| 13 | + |
| 14 | +describe('execution context', () => { |
| 15 | + it('has the same ECDH keypair after multiple calls', async () => { |
| 16 | + const abortController = new AbortController() |
| 17 | + const ctx = new ExecutionContext('', abortController) |
| 18 | + |
| 19 | + const expected = await ctx.getECDHKeyPair() |
| 20 | + const actual = await ctx.getECDHKeyPair() |
| 21 | + |
| 22 | + expect(actual).toStrictEqual(expected) |
| 23 | + }) |
| 24 | + |
| 25 | + it('has the same ECDH keypair for concurrent calls', async () => { |
| 26 | + const originalGenerateKey = subtle.generateKey.bind(subtle) |
| 27 | + |
| 28 | + vi.spyOn(subtle, 'generateKey').mockImplementation(async (...args) => { |
| 29 | + // Introduce a delay to simulate async operation and increase the chance of race condition |
| 30 | + await sleep(10) |
| 31 | + return originalGenerateKey(...args) |
| 32 | + }) |
| 33 | + |
| 34 | + try { |
| 35 | + const abortController = new AbortController() |
| 36 | + const ctx = new ExecutionContext('', abortController) |
| 37 | + |
| 38 | + const results = await Promise.all([ |
| 39 | + ctx.getECDHKeyPair(), |
| 40 | + ctx.getECDHKeyPair(), |
| 41 | + ctx.getECDHKeyPair(), |
| 42 | + ctx.getECDHKeyPair(), |
| 43 | + ctx.getECDHKeyPair(), |
| 44 | + ]) |
| 45 | + |
| 46 | + const expected = await subtle.exportKey('raw', results[0].publicKey) |
| 47 | + for (let i = 1; i < results.length; i++) { |
| 48 | + const actual = await subtle.exportKey('raw', results[i].publicKey) |
| 49 | + expect(actual).toStrictEqual(expected) |
| 50 | + } |
| 51 | + } finally { |
| 52 | + vi.spyOn(subtle, 'generateKey').mockRestore() |
| 53 | + } |
| 54 | + }) |
| 55 | +}) |
0 commit comments