Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/publish-npm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion scripts/release/native-launcher.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand All @@ -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
Expand Down
54 changes: 37 additions & 17 deletions src/commands/manifest/bazel/process.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 })
Expand All @@ -424,30 +422,48 @@ 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<void> {
// 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(
launcher,
`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()' : ''}
`,
)
Expand Down Expand Up @@ -498,10 +514,14 @@ async function waitForExit(pid: number): Promise<boolean> {
}

async function waitForFile(file: string): Promise<void> {
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', () => {
Expand Down
9 changes: 4 additions & 5 deletions src/sea/bootstrap.mts
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,10 @@ async function smokeTest(): Promise<void> {
.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 {
Expand Down
1 change: 0 additions & 1 deletion src/sea/paths/coana.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
32 changes: 18 additions & 14 deletions src/sea/stage/coana.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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 },
)
}
Expand All @@ -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`)
Expand All @@ -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.',
)
}

Expand Down
31 changes: 24 additions & 7 deletions src/utils/api-timeout.integration.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -133,17 +135,23 @@ async function generateLocalhostCertificate(
new Promise<void>((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()}`,
),
)
}
Expand All @@ -153,7 +161,9 @@ async function generateLocalhostCertificate(
'req',
'-new',
'-newkey',
'rsa:2048',
'ec',
'-pkeyopt',
'ec_paramgen_curve:P-256',
'-nodes',
'-sha256',
'-subj',
Expand Down Expand Up @@ -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'),
Expand Down Expand Up @@ -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) {
Expand All @@ -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 () => {
Expand Down
8 changes: 4 additions & 4 deletions src/utils/api.mts
Original file line number Diff line number Diff line change
Expand Up @@ -843,9 +843,9 @@ export async function sendApiRequest<T>(
__proto__: null,
...options,
} as SendApiRequestOptions
const { spinner } = constants
const spinner = description ? constants.spinner : undefined

if (description) {
if (spinner) {
spinner.start(`Requesting ${description} from API...`)
}

Expand All @@ -867,13 +867,13 @@ export async function sendApiRequest<T>(
`${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}.`,
)
Expand Down
38 changes: 37 additions & 1 deletion src/utils/coana-release.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
Expand Down
Loading
Loading