From 826a079d7915d376e20b2e9ceead02f5738df5d8 Mon Sep 17 00:00:00 2001 From: jdalton Date: Tue, 24 Nov 2026 20:27:06 -0500 Subject: [PATCH] fix(cli): require an explicit org for Coana builds --- .github/workflows/publish-npm.yml | 3 +- scripts/release/native-launcher.cjs | 2 +- src/commands/manifest/bazel/process.test.mts | 54 +++++++++++++------ src/sea/bootstrap.mts | 9 ++-- src/sea/paths/coana.mts | 1 - src/sea/stage/coana.mts | 32 ++++++----- src/utils/api-timeout.integration.test.mts | 31 ++++++++--- src/utils/api.mts | 8 +-- src/utils/coana-release.test.mts | 38 ++++++++++++- src/utils/coana/release.mts | 57 +++++++++++++++----- 10 files changed, 172 insertions(+), 63 deletions(-) diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index 40315d659..6fa0e7b3e 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -323,10 +323,11 @@ jobs: NODE_OPTIONS: ${{ runner.os == 'macOS' && '--max-old-space-size=4096' || '' }} SOCKET_CLI_API_TOKEN: ${{ startsWith(needs.verify.outputs.version, '2.') && !startsWith(matrix.target, 'win32-') && secrets.SOCKET_API_TOKEN_FOR_CLI_AND_SFW || '' }} # zizmor: ignore[secrets-outside-env] SOCKET_CLI_COANA_REQUIRED: ${{ startsWith(needs.verify.outputs.version, '2.') && '1' || '0' }} + SOCKET_CLI_ORG_SLUG: SocketDev shell: bash run: | pnpm build:sea - unset SOCKET_CLI_API_TOKEN + unset SOCKET_CLI_API_TOKEN SOCKET_CLI_ORG_SLUG pnpm test:sea - name: Pack verified platform binary diff --git a/scripts/release/native-launcher.cjs b/scripts/release/native-launcher.cjs index 64b741eb1..ab3dc2308 100644 --- a/scripts/release/native-launcher.cjs +++ b/scripts/release/native-launcher.cjs @@ -32,7 +32,6 @@ if (process.platform !== 'win32' && process.execve) { // Preserve the PID a service supervisor signals when cancelling a scan. process.execve(binary, [binary, ...args], process.env) } -const child = spawn(binary, args, { stdio: 'inherit' }) // Older Unix Node versions need a forwarding wrapper. Windows console // control events already reach the attached native child. const signals = @@ -41,6 +40,7 @@ const forward = signal => child.kill(signal) for (const signal of signals) { process.on(signal, forward) } +const child = spawn(binary, args, { stdio: 'inherit' }) child.on('error', error => { console.error(error.message) process.exitCode = 1 diff --git a/src/commands/manifest/bazel/process.test.mts b/src/commands/manifest/bazel/process.test.mts index e1e4829c2..37b73e406 100644 --- a/src/commands/manifest/bazel/process.test.mts +++ b/src/commands/manifest/bazel/process.test.mts @@ -16,7 +16,7 @@ import path from 'node:path' import { setTimeout as sleep } from 'node:timers/promises' import cmdShim from 'cmd-shim' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { resolveBazelBinary } from './bin-detect.mts' import { @@ -406,11 +406,9 @@ if (args.includes('info')) { process.stdout.write(${JSON.stringify(`install_base it('stops what a launcher started when the timeout expires', async () => { const record = writeParentLauncher({ detached: false }) - await expect( - spawnBazel(launcher, [], { cwd, timeout: 500 }), - ).rejects.toBeInstanceOf(BazelTimeoutError) + await expireLauncherTimeout(record) expect(await waitForExit(readChildPid(record))).toBe(true) - }) + }, 30_000) it('stops what a launcher started when cancelled', async () => { const record = writeParentLauncher({ detached: false }) @@ -424,22 +422,38 @@ if (args.includes('info')) { process.stdout.write(${JSON.stringify(`install_base it('settles a timeout when an escaped process keeps the output open', async () => { const record = writeParentLauncher({ detached: true }) - const startedAt = Date.now() try { - await expect( - spawnBazel(launcher, [], { cwd, timeout: 500 }), - ).rejects.toBeInstanceOf(BazelTimeoutError) - expect(Date.now() - startedAt).toBeLessThan(15_000) + await expireLauncherTimeout(record) } finally { - const pid = readChildPid(record) - if (isAlive(pid)) { - process.kill(pid, 'SIGKILL') + if (existsSync(record)) { + const pid = readChildPid(record) + if (isAlive(pid)) { + process.kill(pid, 'SIGKILL') + } + // Windows can report process exit before inherited handles release the cwd. + expect(await waitForExit(pid)).toBe(true) } - // Windows can report process exit before inherited handles release the cwd. - expect(await waitForExit(pid)).toBe(true) } }, 30_000) + async function expireLauncherTimeout(record: string): Promise { + // Give the real launcher time to report its child before firing the timeout. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const result = spawnBazel(launcher, [], { cwd, timeout: 500 }).catch( + (e: unknown) => e, + ) + try { + await waitForFile(record) + } finally { + try { + await vi.runAllTimersAsync() + } finally { + vi.useRealTimers() + } + } + expect(await result).toBeInstanceOf(BazelTimeoutError) + } + function writeParentLauncher(options: { detached: boolean }): string { const record = path.join(cwd, 'child.pid') writeFileSync( @@ -447,7 +461,9 @@ if (args.includes('info')) { process.stdout.write(${JSON.stringify(`install_base `const { spawn } = require('node:child_process') const fs = require('node:fs') const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { detached: ${options.detached}, stdio: 'inherit' }) -fs.writeFileSync(${JSON.stringify(record)}, String(child.pid)) +const record = ${JSON.stringify(record)} +fs.writeFileSync(record + '.tmp', String(child.pid)) +fs.renameSync(record + '.tmp', record) ${options.detached ? 'child.unref()' : ''} `, ) @@ -498,10 +514,14 @@ async function waitForExit(pid: number): Promise { } async function waitForFile(file: string): Promise { - while (!existsSync(file)) { + const deadline = Date.now() + 10_000 + while (!existsSync(file) && Date.now() < deadline) { // eslint-disable-next-line no-await-in-loop await sleep(50) } + if (!existsSync(file)) { + throw new Error('Bazel test launcher did not report its child PID') + } } describe('splitBazelFlags', () => { diff --git a/src/sea/bootstrap.mts b/src/sea/bootstrap.mts index 960a992b2..73028976f 100644 --- a/src/sea/bootstrap.mts +++ b/src/sea/bootstrap.mts @@ -72,11 +72,10 @@ async function smokeTest(): Promise { .then(stat => stat.isFile()), true, ) - assert.equal( - await fs - .stat(path.join(__dirname, SEA_COANA_VFS_PATHS.analyzers, 'repos')) - .then(stat => stat.isDirectory()), - true, + assert.ok( + (await fs.readdir(path.join(__dirname, SEA_COANA_VFS_PATHS.analyzers))) + .length > 0, + 'Missing embedded Coana analyzers', ) const node = await getBundledTool('coana-node') try { diff --git a/src/sea/paths/coana.mts b/src/sea/paths/coana.mts index b5d286bb5..141fadbb6 100644 --- a/src/sea/paths/coana.mts +++ b/src/sea/paths/coana.mts @@ -20,7 +20,6 @@ export function seaCoanaPaths(root: string) { manifest: fromRoot(SEA_COANA_VFS_PATHS.manifest), node: fromRoot(SEA_COANA_VFS_PATHS.node), nodeDigest: fromRoot(SEA_COANA_VFS_PATHS.nodeDigest), - repos: path.join(fromRoot(SEA_COANA_VFS_PATHS.analyzers), 'repos'), root: directory, } } diff --git a/src/sea/stage/coana.mts b/src/sea/stage/coana.mts index a3c7f6222..097dfdde1 100644 --- a/src/sea/stage/coana.mts +++ b/src/sea/stage/coana.mts @@ -7,10 +7,9 @@ import { pipeline } from 'node:stream/promises' import { x as extractTar } from 'tar' -import { getDefaultOrgSlug } from '../../commands/ci/fetch-default-org-slug.mts' import { COANA_CLI_VERSION } from '../../constants.mts' import { apiFetch, sendApiRequest } from '../../utils/api.mts' -import { envAsBoolean } from '../../utils/env.mts' +import { envAsBoolean, envAsString } from '../../utils/env.mts' import { errorMessage } from '../../utils/errors.mts' import { SEA_COANA_VFS_PATHS, seaCoanaPaths } from '../paths/coana.mts' @@ -218,18 +217,16 @@ export async function stageCoana( return undefined } - const org = await getDefaultOrgSlug() - if (!org.ok) { - throw new Error( - `Coana ${COANA_CLI_VERSION} download failed. Where: organization lookup. Saw: ${org.message}${org.cause ? ` (${org.cause})` : ''}; wanted: a default organization with Coana reachability access. Fix: check the build token and its organization access.`, - ) + const org = envAsString(process.env['SOCKET_CLI_ORG_SLUG']) + if (!org) { + throw new Error('Set SOCKET_CLI_ORG_SLUG to embed Coana in the SEA build.') } let artifacts: CoanaArtifacts try { - artifacts = await fetchArtifacts(org.data) + artifacts = await fetchArtifacts(org) } catch (error) { throw new Error( - `Could not fetch Coana ${COANA_CLI_VERSION} artifacts for ${org.data}: ${errorMessage(error)}. Check that the build token can access Coana artifacts for this organization.`, + `Could not fetch Coana ${COANA_CLI_VERSION} artifacts for ${org}: ${errorMessage(error)}. Check that the build token can access Coana artifacts for this organization.`, { cause: error }, ) } @@ -240,7 +237,7 @@ export async function stageCoana( const paths = seaCoanaPaths(stageRoot) try { await fs.mkdir(paths.root, { recursive: true }) - const componentEntries = await Promise.all( + const componentResults = await Promise.allSettled( COMPONENTS.map(async name => { const component = artifacts.components[name]! const archive = path.join(temporaryDirectory, `${name}.tar.gz`) @@ -254,13 +251,20 @@ export async function stageCoana( ] as const }), ) - const componentDigests = Object.fromEntries(componentEntries) + const componentDigests = Object.fromEntries( + componentResults.map(result => { + if (result.status === 'rejected') { + throw result.reason + } + return result.value + }), + ) const cli = await fs.stat(paths.cliWrapper).catch(() => undefined) - const repos = await fs.stat(paths.repos).catch(() => undefined) - if (!cli?.isFile() || !repos?.isDirectory()) { + const analyzers = await fs.readdir(paths.analyzers) + if (!cli?.isFile() || analyzers.length === 0) { throw new Error( - 'Coana archives do not contain cli-wrapper.mjs and analyzer repos/', + 'Coana archives must contain cli-wrapper.mjs and analyzer files.', ) } diff --git a/src/utils/api-timeout.integration.test.mts b/src/utils/api-timeout.integration.test.mts index 73891a946..14b4aba7e 100644 --- a/src/utils/api-timeout.integration.test.mts +++ b/src/utils/api-timeout.integration.test.mts @@ -41,6 +41,8 @@ let isolatedHome = '' let certificatePath = '' // Milliseconds: this sets a three-minute lifetime for the test certificate. const TEST_CERT_VALIDITY_MS = 3 * 60 * 1000 +const OPENSSL_TIMEOUT_MS = 15_000 +const SETUP_TIMEOUT_MS = 2 * OPENSSL_TIMEOUT_MS + 10_000 function handleRequest( request: IncomingMessage, @@ -133,17 +135,23 @@ async function generateLocalhostCertificate( new Promise((resolve, reject) => { const openssl = spawn('openssl', args, { cwd: workingDirectory, - stdio: 'ignore', + stdio: ['ignore', 'ignore', 'pipe'], + timeout: OPENSSL_TIMEOUT_MS, windowsHide: true, }) + let stderr = '' + openssl.stderr.setEncoding('utf8') + openssl.stderr.on('data', (chunk: string) => { + stderr += chunk + }) openssl.once('error', reject) - openssl.once('close', code => { + openssl.once('close', (code, signal) => { if (code === 0) { resolve() } else { reject( new Error( - `OpenSSL failed to create the test certificate (${code})`, + `OpenSSL ${args[0]} failed (${code ?? signal}): ${stderr.trim()}`, ), ) } @@ -153,7 +161,9 @@ async function generateLocalhostCertificate( 'req', '-new', '-newkey', - 'rsa:2048', + 'ec', + '-pkeyopt', + 'ec_paramgen_curve:P-256', '-nodes', '-sha256', '-subj', @@ -286,7 +296,7 @@ describe('v1 direct Socket API timeout configuration', () => { '[ localhost ]', 'basicConstraints = critical,CA:FALSE', 'subjectAltName = DNS:localhost,IP:127.0.0.1', - 'keyUsage = critical,digitalSignature,keyEncipherment', + 'keyUsage = critical,digitalSignature', 'extendedKeyUsage = serverAuth', '', ].join('\n'), @@ -336,7 +346,7 @@ describe('v1 direct Socket API timeout configuration', () => { apiFetch = api.apiFetch queryApi = api.queryApiSafeTextWithStatus sendApiRequest = api.sendApiRequest - }) + }, SETUP_TIMEOUT_MS) afterAll(async () => { for (const timer of responseTimers) { @@ -349,7 +359,14 @@ describe('v1 direct Socket API timeout configuration', () => { }) } vi.unstubAllEnvs() - rmSync(isolatedHome, { force: true, recursive: true }) + if (isolatedHome) { + rmSync(isolatedHome, { + force: true, + recursive: true, + maxRetries: 5, + retryDelay: 100, + }) + } }) it('applies configured timeout to direct GET and POST requests', async () => { diff --git a/src/utils/api.mts b/src/utils/api.mts index 8c169a250..1894337e3 100644 --- a/src/utils/api.mts +++ b/src/utils/api.mts @@ -843,9 +843,9 @@ export async function sendApiRequest( __proto__: null, ...options, } as SendApiRequestOptions - const { spinner } = constants + const spinner = description ? constants.spinner : undefined - if (description) { + if (spinner) { spinner.start(`Requesting ${description} from API...`) } @@ -867,13 +867,13 @@ export async function sendApiRequest( `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${path}`, fetchOptions, ) - if (description) { + if (spinner) { spinner.successAndStop( `Received Socket API response (after requesting ${description}).`, ) } } catch (e) { - if (description) { + if (spinner) { spinner.failAndStop( `An error was thrown while requesting ${description}.`, ) diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 442a58258..8c975fab8 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -32,8 +32,9 @@ import { import { spawn } from './spawn.mts' import constants, { SOCKET_CLI_API_TOKEN_VARIABLES } from '../constants.mts' -import { spawnCoana } from './coana/release.mts' +import { copyCoanaVfsDirectory, spawnCoana } from './coana/release.mts' import { overrideCachedConfig, resetConfigForTesting } from './config.mts' +import { withTmpDir } from './fs.mts' import { getCliUserAgent, getDefaultApiBaseUrl, @@ -42,6 +43,41 @@ import { const VERSION = '1.2.3' +describe('copyCoanaVfsDirectory', () => { + it('copies regular files and directories without following symlinks', async () => { + await withTmpDir('socket-coana-copy-', async root => { + const source = path.join(root, 'source') + const destination = path.join(root, 'destination') + const tools = path.join(source, 'tools', 'analyzers') + await fs.mkdir(tools, { recursive: true }) + await fs.mkdir(path.join(source, 'empty')) + await fs.writeFile(path.join(source, 'cli-wrapper.mjs'), 'wrapper') + await fs.writeFile(path.join(tools, 'analyzer.br'), 'analyzer') + if (process.platform !== 'win32') { + await fs.symlink('tools', path.join(source, 'tools-link')) + await fs.symlink('cli-wrapper.mjs', path.join(source, 'wrapper-link')) + } + + await copyCoanaVfsDirectory(source, destination) + + expect((await fs.readdir(destination)).sort()).toEqual([ + 'cli-wrapper.mjs', + 'empty', + 'tools', + ]) + expect( + await fs.readFile(path.join(destination, 'cli-wrapper.mjs'), 'utf8'), + ).toBe('wrapper') + expect( + await fs.readFile( + path.join(destination, 'tools', 'analyzers', 'analyzer.br'), + 'utf8', + ), + ).toBe('analyzer') + }) + }) +}) + // Prints what it was run with, or fails the way Coana does for some errors. const FAKE_CLI_WRAPPER = ` const args = process.argv.slice(2) diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index f04b8a95c..676240198 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -91,7 +91,9 @@ const TOKEN_VARIABLES: ReadonlySet = new Set([ 'SOCKET_CLI_CONFIG', ]) -function cacheResultToCResult(result: CoanaCacheResult): CResult { +export function cacheResultToCResult( + result: CoanaCacheResult, +): CResult { if (result.exitCode === 0) { return { ok: true, data: result.stdout } } @@ -119,7 +121,7 @@ function cacheResultToCResult(result: CoanaCacheResult): CResult { * The registry's `spawn` spreads `process.env` under the env it is given, so * they are set to `undefined`, which Node drops. */ -function coanaUserEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { +export function coanaUserEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const out: NodeJS.ProcessEnv = {} for (const key of Object.keys(env)) { out[key] = @@ -135,7 +137,7 @@ function coanaUserEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { * Build a CResult error from a thrown spawn error, preserving exit code, * signal, and stderr context. */ -function coanaSpawnErrorResult(e: unknown): CResult { +export function coanaSpawnErrorResult(e: unknown): CResult { const stderr = (e as any)?.stderr const stdout = (e as any)?.stdout const exitCode = (e as any)?.code @@ -165,7 +167,7 @@ function coanaSpawnErrorResult(e: unknown): CResult { * Stream `component`'s tarball into `destDir`, checking its size and sha256 on * the way. The tarball holds only regular files, so anything else is dropped. */ -async function downloadComponent( +export async function downloadComponent( component: CoanaComponent, destDir: string, ): Promise { @@ -221,7 +223,7 @@ async function downloadComponent( * version or a range, downloading it into the cache when the cache lacks it. * `env` reaches the cache script, which reads `XDG_CACHE_HOME` from it. */ -async function getCoanaCliDir( +export async function getCoanaCliDir( versionSpec: string, org: CResult, env: NodeJS.ProcessEnv, @@ -289,7 +291,7 @@ async function getCoanaCliDir( } } -async function installComponent( +export async function installComponent( artifacts: CoanaArtifacts, orgSlug: string, env: NodeJS.ProcessEnv, @@ -323,7 +325,9 @@ async function installComponent( }) } -function parseCoanaArtifacts(value: unknown): CoanaArtifacts | undefined { +export function parseCoanaArtifacts( + value: unknown, +): CoanaArtifacts | undefined { const { components, version } = (value ?? {}) as { components?: unknown version?: unknown @@ -351,7 +355,7 @@ function parseCoanaArtifacts(value: unknown): CoanaArtifacts | undefined { return { cli: { sha256, size, url }, version } } -async function requestArtifacts( +export async function requestArtifacts( versionSpec: string, orgSlug: string, ): Promise> { @@ -381,7 +385,7 @@ async function requestArtifacts( * Run the vendored cache script, which prints only a directory to stdout. * Throws only when Node itself cannot be spawned. */ -async function runCoanaCache( +export async function runCoanaCache( args: string[], env: NodeJS.ProcessEnv, ): Promise { @@ -420,7 +424,37 @@ async function runCoanaCache( } } -async function cacheEmbeddedCoana( +export async function copyCoanaVfsDirectory( + source: string, + destination: string, +): Promise { + // fs.cp resolves real paths, which the SEA filesystem does not provide. + const pending = [{ source, destination }] + while (pending.length > 0) { + const { destination: destinationDir, source: sourceDir } = pending.pop()! + // eslint-disable-next-line no-await-in-loop -- Create the directory before copying its files. + await fs.mkdir(destinationDir) + // eslint-disable-next-line no-await-in-loop -- Read one directory at a time. + const names = await fs.readdir(sourceDir) + for (let index = 0, { length } = names; index < length; index += 1) { + const name = names[index]! + const from = path.join(sourceDir, name) + const to = path.join(destinationDir, name) + // eslint-disable-next-line no-await-in-loop -- Skip symlinks before copying. + const stat = await fs.lstat(from) + if (stat.isDirectory()) { + pending.push({ source: from, destination: to }) + } else if (stat.isFile()) { + // eslint-disable-next-line no-await-in-loop -- Read and write one file at a time. + await fs.writeFile(to, await fs.readFile(from), { + mode: stat.mode & 0o777, + }) + } + } + } +} + +export async function cacheEmbeddedCoana( env: NodeJS.ProcessEnv, ): Promise<{ cliPath: string; analyzersPath: string }> { const manifest = JSON.parse( @@ -454,14 +488,13 @@ async function cacheEmbeddedCoana( 'socket-coana-embedded-', async source => { const extracted = path.join(source, 'component') - await fs.cp( + await copyCoanaVfsDirectory( getEmbeddedVfsPath( component === 'cli' ? SEA_COANA_VFS_PATHS.cli : SEA_COANA_VFS_PATHS.analyzers, ), extracted, - { recursive: true }, ) return await runCoanaCache( ['install', COANA_CLI_VERSION, component, sha256, extracted],