|
| 1 | +import { spawn } from 'node:child_process' |
| 2 | +import { X509Certificate } from 'node:crypto' |
| 3 | +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' |
| 4 | +import { createServer } from 'node:https' |
| 5 | +import { tmpdir } from 'node:os' |
| 6 | +import { join } from 'node:path' |
| 7 | + |
| 8 | +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' |
| 9 | + |
| 10 | +import type { IncomingMessage, ServerResponse } from 'node:http' |
| 11 | +import type { Server as HttpsServer } from 'node:https' |
| 12 | +import type { AddressInfo } from 'node:net' |
| 13 | + |
| 14 | +type RequestObservation = { |
| 15 | + authorization: string | undefined |
| 16 | + body: string |
| 17 | + closed: Promise<void> |
| 18 | + method: string | undefined |
| 19 | + path: string | undefined |
| 20 | + resolveClosed: () => void |
| 21 | +} |
| 22 | + |
| 23 | +const requestWaiters = new Map< |
| 24 | + string, |
| 25 | + (observation: RequestObservation) => void |
| 26 | +>() |
| 27 | +const responseTimers = new Set<ReturnType<typeof setTimeout>>() |
| 28 | +const observations: RequestObservation[] = [] |
| 29 | +let server: HttpsServer | undefined |
| 30 | +let apiFetch: typeof import('./api.mts').apiFetch |
| 31 | +let queryApi: typeof import('./api.mts').queryApiSafeTextWithStatus |
| 32 | +let sendApiRequest: typeof import('./api.mts').sendApiRequest |
| 33 | +let baseUrl = '' |
| 34 | +let isolatedHome = '' |
| 35 | +let certificatePath = '' |
| 36 | +const TEST_CERT_VALIDITY_MS = 3 * 60 * 1000 |
| 37 | + |
| 38 | +function handleRequest( |
| 39 | + request: IncomingMessage, |
| 40 | + response: ServerResponse, |
| 41 | +): void { |
| 42 | + const pathname = new URL(request.url ?? '/', 'https://127.0.0.1').pathname |
| 43 | + const closeHandler: { resolve?: () => void } = {} |
| 44 | + const observation: RequestObservation = { |
| 45 | + authorization: request.headers['authorization'], |
| 46 | + body: '', |
| 47 | + closed: new Promise(resolve => { |
| 48 | + closeHandler.resolve = resolve |
| 49 | + }), |
| 50 | + method: request.method, |
| 51 | + path: pathname, |
| 52 | + resolveClosed: () => { |
| 53 | + closeHandler.resolve?.() |
| 54 | + }, |
| 55 | + } |
| 56 | + observations.push(observation) |
| 57 | + requestWaiters.get(pathname)?.(observation) |
| 58 | + requestWaiters.delete(pathname) |
| 59 | + |
| 60 | + const chunks: Buffer[] = [] |
| 61 | + request.on('data', (chunk: Buffer | string) => { |
| 62 | + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)) |
| 63 | + }) |
| 64 | + request.on('end', () => { |
| 65 | + observation.body = Buffer.concat(chunks).toString('utf8') |
| 66 | + if (pathname === '/redirect-302' || pathname === '/redirect-307') { |
| 67 | + response.writeHead(pathname === '/redirect-302' ? 302 : 307, { |
| 68 | + location: '/delay-headers', |
| 69 | + }) |
| 70 | + response.end() |
| 71 | + return |
| 72 | + } |
| 73 | + const complete = () => { |
| 74 | + responseTimers.delete(timer) |
| 75 | + if (!response.destroyed) { |
| 76 | + response.end(pathname === '/gap' ? 'firstsecond' : '{"ok":true}') |
| 77 | + } |
| 78 | + } |
| 79 | + let delay = 0 |
| 80 | + if (pathname === '/delay-headers') { |
| 81 | + delay = 220 |
| 82 | + } else if (pathname === '/idle-body') { |
| 83 | + response.writeHead(200, { 'content-type': 'application/json' }) |
| 84 | + response.flushHeaders() |
| 85 | + response.write('{"ok":') |
| 86 | + delay = 220 |
| 87 | + } else if ( |
| 88 | + pathname === '/explicit' || |
| 89 | + pathname === '/gap' || |
| 90 | + pathname === '/unset-gap' |
| 91 | + ) { |
| 92 | + delay = 180 |
| 93 | + } |
| 94 | + const timer = setTimeout(complete, delay) |
| 95 | + responseTimers.add(timer) |
| 96 | + }) |
| 97 | + response.on('close', () => { |
| 98 | + observation.resolveClosed() |
| 99 | + }) |
| 100 | +} |
| 101 | + |
| 102 | +function waitForRequest(pathname: string): Promise<RequestObservation> { |
| 103 | + return new Promise(resolve => { |
| 104 | + requestWaiters.set(pathname, resolve) |
| 105 | + }) |
| 106 | +} |
| 107 | + |
| 108 | +function generateLocalhostCertificate( |
| 109 | + certificatePath: string, |
| 110 | + keyPath: string, |
| 111 | +): Promise<void> { |
| 112 | + const notAfter = new Date(Date.now() + TEST_CERT_VALIDITY_MS) |
| 113 | + const notAfterOpenSsl = [ |
| 114 | + notAfter.getUTCFullYear(), |
| 115 | + String(notAfter.getUTCMonth() + 1).padStart(2, '0'), |
| 116 | + String(notAfter.getUTCDate()).padStart(2, '0'), |
| 117 | + String(notAfter.getUTCHours()).padStart(2, '0'), |
| 118 | + String(notAfter.getUTCMinutes()).padStart(2, '0'), |
| 119 | + String(notAfter.getUTCSeconds()).padStart(2, '0'), |
| 120 | + 'Z', |
| 121 | + ].join('') |
| 122 | + return new Promise((resolve, reject) => { |
| 123 | + const openssl = spawn( |
| 124 | + 'openssl', |
| 125 | + [ |
| 126 | + 'req', |
| 127 | + '-x509', |
| 128 | + '-newkey', |
| 129 | + 'rsa:2048', |
| 130 | + '-nodes', |
| 131 | + '-sha256', |
| 132 | + '-not_after', |
| 133 | + notAfterOpenSsl, |
| 134 | + '-subj', |
| 135 | + '/CN=localhost', |
| 136 | + '-addext', |
| 137 | + 'subjectAltName=DNS:localhost,IP:127.0.0.1', |
| 138 | + '-addext', |
| 139 | + 'basicConstraints=critical,CA:FALSE', |
| 140 | + '-addext', |
| 141 | + 'keyUsage=critical,digitalSignature,keyEncipherment', |
| 142 | + '-addext', |
| 143 | + 'extendedKeyUsage=serverAuth', |
| 144 | + '-keyout', |
| 145 | + keyPath, |
| 146 | + '-out', |
| 147 | + certificatePath, |
| 148 | + ], |
| 149 | + { stdio: 'ignore', windowsHide: true }, |
| 150 | + ) |
| 151 | + openssl.once('error', reject) |
| 152 | + openssl.once('close', code => { |
| 153 | + if (code === 0) { |
| 154 | + resolve() |
| 155 | + } else { |
| 156 | + reject( |
| 157 | + new Error(`OpenSSL failed to create the test certificate (${code})`), |
| 158 | + ) |
| 159 | + } |
| 160 | + }) |
| 161 | + }) |
| 162 | +} |
| 163 | + |
| 164 | +async function listen(): Promise<void> { |
| 165 | + if (!server) { |
| 166 | + throw new Error('Loopback HTTPS fixture is not initialized') |
| 167 | + } |
| 168 | + await new Promise<void>(resolve => { |
| 169 | + server.listen(0, '127.0.0.1', resolve) |
| 170 | + }) |
| 171 | + const address = server.address() |
| 172 | + if (address === null || typeof address === 'string') { |
| 173 | + throw new Error('Loopback fixture did not receive a TCP address') |
| 174 | + } |
| 175 | + baseUrl = `https://127.0.0.1:${address.port}` |
| 176 | +} |
| 177 | + |
| 178 | +function runUnsetTimeoutChild(): Promise<string> { |
| 179 | + const source = [ |
| 180 | + "const { queryApiSafeTextWithStatus } = await import('./src/utils/api.mts')", |
| 181 | + "const result = await queryApiSafeTextWithStatus('unset-gap')", |
| 182 | + 'process.stdout.write(JSON.stringify({ ok: result.ok }))', |
| 183 | + ].join('; ') |
| 184 | + return new Promise((resolve, reject) => { |
| 185 | + const child = spawn( |
| 186 | + process.execPath, |
| 187 | + ['--input-type=module', '--eval', source], |
| 188 | + { |
| 189 | + cwd: process.cwd(), |
| 190 | + env: { |
| 191 | + PATH: process.env['PATH'] ?? '', |
| 192 | + HOME: isolatedHome, |
| 193 | + XDG_CONFIG_HOME: join(isolatedHome, 'config'), |
| 194 | + XDG_DATA_HOME: join(isolatedHome, 'data'), |
| 195 | + SOCKET_CLI_CONFIG: '{}', |
| 196 | + SOCKET_CLI_API_BASE_URL: baseUrl, |
| 197 | + SOCKET_CLI_API_TOKEN: 'sktsec_abc123abc123abc123abc123', |
| 198 | + SOCKET_CLI_API_PROXY: '', |
| 199 | + HTTPS_PROXY: '', |
| 200 | + https_proxy: '', |
| 201 | + HTTP_PROXY: '', |
| 202 | + http_proxy: '', |
| 203 | + SSL_CERT_FILE: certificatePath, |
| 204 | + NODE_EXTRA_CA_CERTS: '', |
| 205 | + }, |
| 206 | + }, |
| 207 | + ) |
| 208 | + let stdout = '' |
| 209 | + let stderr = '' |
| 210 | + const watchdog = setTimeout(() => { |
| 211 | + child.kill() |
| 212 | + reject(new Error('Unset-timeout child exceeded its watchdog')) |
| 213 | + }, 3_000) |
| 214 | + child.stdout.setEncoding('utf8') |
| 215 | + child.stderr.setEncoding('utf8') |
| 216 | + child.stdout.on('data', (chunk: string) => { |
| 217 | + stdout += chunk |
| 218 | + }) |
| 219 | + child.stderr.on('data', (chunk: string) => { |
| 220 | + stderr += chunk |
| 221 | + }) |
| 222 | + child.on('error', error => { |
| 223 | + clearTimeout(watchdog) |
| 224 | + reject(error) |
| 225 | + }) |
| 226 | + child.on('close', code => { |
| 227 | + clearTimeout(watchdog) |
| 228 | + if (code === 0) { |
| 229 | + resolve(stdout) |
| 230 | + } else { |
| 231 | + reject(new Error(`Unset-timeout child exited ${code}: ${stderr}`)) |
| 232 | + } |
| 233 | + }) |
| 234 | + }) |
| 235 | +} |
| 236 | + |
| 237 | +describe('v1 direct Socket API timeout configuration', () => { |
| 238 | + beforeAll(async () => { |
| 239 | + isolatedHome = mkdtempSync(join(tmpdir(), 'socket-api-timeout-')) |
| 240 | + certificatePath = join(isolatedHome, 'direct-api-timeout-cert.pem') |
| 241 | + const keyPath = join(isolatedHome, 'direct-api-timeout-key.pem') |
| 242 | + // Generate a disposable, localhost-only leaf certificate. Its private key |
| 243 | + // stays in the temporary test directory and is removed in afterAll. |
| 244 | + await generateLocalhostCertificate(certificatePath, keyPath) |
| 245 | + const certificate = readFileSync(certificatePath) |
| 246 | + const remainingValidityMs = |
| 247 | + Date.parse(new X509Certificate(certificate).validTo) - Date.now() |
| 248 | + if ( |
| 249 | + remainingValidityMs <= 0 || |
| 250 | + remainingValidityMs > TEST_CERT_VALIDITY_MS |
| 251 | + ) { |
| 252 | + throw new Error( |
| 253 | + 'OpenSSL generated a test certificate with an invalid lifetime', |
| 254 | + ) |
| 255 | + } |
| 256 | + server = createServer( |
| 257 | + { |
| 258 | + cert: certificate, |
| 259 | + key: readFileSync(keyPath), |
| 260 | + }, |
| 261 | + handleRequest, |
| 262 | + ) |
| 263 | + vi.stubEnv('HOME', isolatedHome) |
| 264 | + vi.stubEnv('XDG_CONFIG_HOME', join(isolatedHome, 'config')) |
| 265 | + vi.stubEnv('XDG_DATA_HOME', join(isolatedHome, 'data')) |
| 266 | + vi.stubEnv('SOCKET_CLI_CONFIG', '{}') |
| 267 | + vi.stubEnv('SOCKET_CLI_API_TIMEOUT', '70') |
| 268 | + vi.stubEnv('SOCKET_CLI_API_TOKEN', 'sktsec_abc123abc123abc123abc123') |
| 269 | + vi.stubEnv('SOCKET_CLI_API_PROXY', '') |
| 270 | + vi.stubEnv('HTTPS_PROXY', '') |
| 271 | + vi.stubEnv('https_proxy', '') |
| 272 | + vi.stubEnv('HTTP_PROXY', '') |
| 273 | + vi.stubEnv('http_proxy', '') |
| 274 | + vi.stubEnv('SSL_CERT_FILE', certificatePath) |
| 275 | + vi.stubEnv('NODE_EXTRA_CA_CERTS', '') |
| 276 | + await listen() |
| 277 | + vi.stubEnv('SOCKET_CLI_API_BASE_URL', baseUrl) |
| 278 | + const api = await import('./api.mts') |
| 279 | + apiFetch = api.apiFetch |
| 280 | + queryApi = api.queryApiSafeTextWithStatus |
| 281 | + sendApiRequest = api.sendApiRequest |
| 282 | + }) |
| 283 | + |
| 284 | + afterAll(async () => { |
| 285 | + for (const timer of responseTimers) { |
| 286 | + clearTimeout(timer) |
| 287 | + } |
| 288 | + if (server) { |
| 289 | + server.closeAllConnections() |
| 290 | + await new Promise<void>(resolve => { |
| 291 | + server?.close(() => resolve()) |
| 292 | + }) |
| 293 | + } |
| 294 | + vi.unstubAllEnvs() |
| 295 | + rmSync(isolatedHome, { force: true, recursive: true }) |
| 296 | + }) |
| 297 | + |
| 298 | + it('applies configured timeout to direct GET and POST requests', async () => { |
| 299 | + const observedGet = waitForRequest('/delay-headers') |
| 300 | + const getResult = await queryApi('delay-headers') |
| 301 | + expect(getResult.ok).toBe(false) |
| 302 | + if (!getResult.ok) { |
| 303 | + expect(getResult.message).toBe('API request failed') |
| 304 | + expect(getResult.cause).toContain('timed out after 70 ms') |
| 305 | + } |
| 306 | + const getRequest = await observedGet |
| 307 | + await getRequest.closed |
| 308 | + expect(getRequest.method).toBe('GET') |
| 309 | + |
| 310 | + const observedPost = waitForRequest('/delay-headers') |
| 311 | + const postResult = await sendApiRequest('delay-headers', { |
| 312 | + method: 'POST', |
| 313 | + body: { source: 'synthetic' }, |
| 314 | + }) |
| 315 | + expect(postResult.ok).toBe(false) |
| 316 | + if (!postResult.ok) { |
| 317 | + expect(postResult.message).toBe('API request failed') |
| 318 | + expect(postResult.cause).toContain('timed out after 70 ms') |
| 319 | + } |
| 320 | + const postRequest = await observedPost |
| 321 | + await postRequest.closed |
| 322 | + expect(postRequest.method).toBe('POST') |
| 323 | + expect(postRequest.body).toBe('{"source":"synthetic"}') |
| 324 | + expect(postRequest.authorization).toBeTruthy() |
| 325 | + }) |
| 326 | + |
| 327 | + it('destroys an idle response body with a typed timeout error', async () => { |
| 328 | + const observedRequest = waitForRequest('/idle-body') |
| 329 | + const response = await apiFetch(`${baseUrl}/idle-body`, { timeout: 70 }) |
| 330 | + await expect(response.text()).rejects.toMatchObject({ code: 'ETIMEDOUT' }) |
| 331 | + const observed = await observedRequest |
| 332 | + await observed.closed |
| 333 | + }) |
| 334 | + |
| 335 | + it('allows normal completion within the configured timeout', async () => { |
| 336 | + const observedGet = waitForRequest('/quick') |
| 337 | + const getResult = await queryApi('quick') |
| 338 | + expect(getResult.ok).toBe(true) |
| 339 | + await observedGet |
| 340 | + |
| 341 | + const observedPost = waitForRequest('/quick') |
| 342 | + const postResult = await sendApiRequest('quick', { |
| 343 | + method: 'POST', |
| 344 | + body: { source: 'synthetic' }, |
| 345 | + }) |
| 346 | + expect(postResult).toEqual({ ok: true, data: { ok: true } }) |
| 347 | + const postRequest = await observedPost |
| 348 | + expect(postRequest.body).toBe('{"source":"synthetic"}') |
| 349 | + }) |
| 350 | + |
| 351 | + it('keeps raw API requests without a timeout when the setting is unset', async () => { |
| 352 | + const observedRequest = waitForRequest('/unset-gap') |
| 353 | + const childResult = await runUnsetTimeoutChild() |
| 354 | + expect(childResult).toBe('{"ok":true}') |
| 355 | + const observed = await observedRequest |
| 356 | + await observed.closed |
| 357 | + }) |
| 358 | + |
| 359 | + it('does not apply the API setting to raw fetches and preserves explicit timeout overrides', async () => { |
| 360 | + const observedGap = waitForRequest('/gap') |
| 361 | + const gapResponse = await apiFetch(`${baseUrl}/gap`) |
| 362 | + expect(await gapResponse.text()).toBe('firstsecond') |
| 363 | + await observedGap |
| 364 | + |
| 365 | + const observedExplicit = waitForRequest('/explicit') |
| 366 | + const explicitResponse = await apiFetch(`${baseUrl}/explicit`, { |
| 367 | + timeout: 300, |
| 368 | + }) |
| 369 | + expect(await explicitResponse.text()).toBe('{"ok":true}') |
| 370 | + await observedExplicit |
| 371 | + }) |
| 372 | + |
| 373 | + it.each(['/redirect-302', '/redirect-307'] as const)( |
| 374 | + 'propagates timeout through %s redirects', |
| 375 | + async path => { |
| 376 | + const observedRedirect = waitForRequest(path) |
| 377 | + const observedTarget = waitForRequest('/delay-headers') |
| 378 | + const options = |
| 379 | + path === '/redirect-307' |
| 380 | + ? { method: 'POST', body: '{"source":"synthetic"}', timeout: 70 } |
| 381 | + : { timeout: 70 } |
| 382 | + await expect( |
| 383 | + apiFetch(`${baseUrl}${path}`, options), |
| 384 | + ).rejects.toMatchObject({ code: 'ETIMEDOUT' }) |
| 385 | + const redirectRequest = await observedRedirect |
| 386 | + const targetRequest = await observedTarget |
| 387 | + await targetRequest.closed |
| 388 | + expect(redirectRequest.method).toBe( |
| 389 | + path === '/redirect-307' ? 'POST' : 'GET', |
| 390 | + ) |
| 391 | + expect(targetRequest.method).toBe( |
| 392 | + path === '/redirect-307' ? 'POST' : 'GET', |
| 393 | + ) |
| 394 | + expect(targetRequest.body).toBe( |
| 395 | + path === '/redirect-307' ? '{"source":"synthetic"}' : '', |
| 396 | + ) |
| 397 | + }, |
| 398 | + ) |
| 399 | +}) |
0 commit comments