Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- `--dynamic-sbom-inference` builds a Gradle or sbt build nested in another build on its own as well, so the projects only its own settings include are no longer missed.
- Maven Socket facts honor artifact types that build extensions define, so they no longer list dependencies Maven doesn't resolve, or fetch files under the wrong extension.
- Maven Socket facts no longer drop dependencies whose scope Maven 3 doesn't define, such as Maven 4's `compile-only` or `none`.
- Your Socket API token, whether from `socket login` or the environment, and the other settings socket-cli passes to Coana no longer reach the build tools and package managers Coana runs.

## [1.15.0](https://github.com/SocketDev/socket-cli/releases/tag/v1.15.0) - 2026-11-12

Expand Down
1 change: 0 additions & 1 deletion src/commands/scan/handle-create-new-scan.mts
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,6 @@ async function createNewScan(
spinner.start()

const reachResult = await performReachabilityAnalysis({
branchName,
cwd,
factsOnlyTypes,
orgSlug,
Expand Down
15 changes: 1 addition & 14 deletions src/commands/scan/perform-reachability-analysis.mts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ export type ReachabilityOptions = {
}

export type ReachabilityAnalysisOptions = {
branchName?: string | undefined
cwd?: string | undefined
// Purl types whose artifacts Coana takes only from facts files.
factsOnlyTypes?: FactsOnlyTypes | undefined
Expand Down Expand Up @@ -83,7 +82,6 @@ export async function performReachabilityAnalysis(
options: ReachabilityAnalysisOptions,
): Promise<CResult<ReachabilityAnalysisResult>> {
const {
branchName,
cwd = process.cwd(),
factsOnlyTypes,
orgSlug,
Expand Down Expand Up @@ -276,17 +274,6 @@ export async function performReachabilityAnalysis(
...(sidecarPath ? ['--compute-artifacts-sidecar', sidecarPath] : []),
]

// Build environment variables.
const coanaEnv: Record<string, string> = {}
// do not pass default repo and branch name to coana to avoid mixing
// buckets (cached configuration) from projects that are likely very different.
if (repoName && repoName !== constants.SOCKET_DEFAULT_REPOSITORY) {
coanaEnv['SOCKET_REPO_NAME'] = repoName
}
if (branchName && branchName !== constants.SOCKET_DEFAULT_BRANCH) {
coanaEnv['SOCKET_BRANCH_NAME'] = branchName
}

// In machine-readable modes (--json/--markdown) the final payload is written
// to stdout by the output layer. Coana streams progress/logs over stdout
// under `inherit`, which would corrupt that payload, so redirect the child's
Expand All @@ -300,7 +287,7 @@ export async function performReachabilityAnalysis(
const coanaResult = await spawnCoana(coanaArgs, orgSlug, {
coanaVersion: reachabilityOptions.reachVersion,
cwd,
env: coanaEnv,
repoName,
spinner,
stdio: coanaStdio,
})
Expand Down
17 changes: 15 additions & 2 deletions src/commands/scan/perform-reachability-analysis.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating',
})
})

describe('performReachabilityAnalysis stdio routing by output kind', () => {
describe('performReachabilityAnalysis spawn options', () => {
let scanCwd: string

beforeEach(() => {
Expand All @@ -428,7 +428,7 @@ describe('performReachabilityAnalysis stdio routing by output kind', () => {
})
mockHasEnterpriseOrgPlan.mockReturnValue(true)
mockSpawnCoana.mockResolvedValue({ ok: true, data: '' })
scanCwd = mkdtempSync(path.join(tmpdir(), 'socket-rea-stdio-'))
scanCwd = mkdtempSync(path.join(tmpdir(), 'socket-rea-spawn-'))
writeFileSync(
path.join(scanCwd, '.socket.facts.json'),
JSON.stringify({ components: [] }),
Expand All @@ -439,6 +439,19 @@ describe('performReachabilityAnalysis stdio routing by output kind', () => {
rmSync(scanCwd, { force: true, recursive: true })
})

it('passes the repository name', async () => {
await performReachabilityAnalysis({
cwd: scanCwd,
orgSlug: TEST_ORG_SLUG,
packagePaths: TEST_PACKAGE_PATHS,
reachabilityOptions: makeReachabilityOptions(),
repoName: 'repo',
target: scanCwd,
})

expect(mockSpawnCoana.mock.calls[0]![2].repoName).toBe('repo')
})

it('inherits stdio in text output mode', async () => {
await performReachabilityAnalysis({
cwd: scanCwd,
Expand Down
17 changes: 12 additions & 5 deletions src/constants.mts
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,14 @@ const REPORT_LEVEL_MONITOR = 'monitor'
const REPORT_LEVEL_WARN = 'warn'
const REQUIREMENTS_TXT = 'requirements.txt'
const SOCKET_CLI_ACCEPT_RISKS = 'SOCKET_CLI_ACCEPT_RISKS'
// The variables socket-cli reads the Socket API token from, first one first.
const SOCKET_CLI_API_TOKEN_VARIABLES = [
'SOCKET_CLI_API_TOKEN',
// TODO: Remove legacy environment variable names.
'SOCKET_CLI_API_KEY',
'SOCKET_SECURITY_API_TOKEN',
'SOCKET_SECURITY_API_KEY',
] as const
const SOCKET_CLI_BIN_NAME = 'socket'
const SOCKET_CLI_ISSUES_URL = 'https://github.com/SocketDev/socket-cli/issues'
const SOCKET_CLI_SHADOW_ACCEPT_RISKS = 'SOCKET_CLI_SHADOW_ACCEPT_RISKS'
Expand Down Expand Up @@ -632,11 +640,9 @@ const LAZY_ENV = () => {
// Set the Socket API token.
// https://github.com/SocketDev/socket-cli?tab=readme-ov-file#environment-variables
SOCKET_CLI_API_TOKEN:
envAsString(env['SOCKET_CLI_API_TOKEN']) ||
// TODO: Remove legacy environment variable names.
envAsString(env['SOCKET_CLI_API_KEY']) ||
envAsString(env['SOCKET_SECURITY_API_TOKEN']) ||
envAsString(env['SOCKET_SECURITY_API_KEY']),
SOCKET_CLI_API_TOKEN_VARIABLES.map(name => envAsString(env[name])).find(
Boolean,
) ?? '',
// A JSON stringified Socket configuration object.
SOCKET_CLI_CONFIG: envAsString(env['SOCKET_CLI_CONFIG']),
// The git config user.email used by Socket CLI.
Expand Down Expand Up @@ -1251,6 +1257,7 @@ export {
SCAN_TYPE_SOCKET,
SCAN_TYPE_SOCKET_TIER1,
SOCKET_CLI_ACCEPT_RISKS,
SOCKET_CLI_API_TOKEN_VARIABLES,
SOCKET_CLI_BIN_NAME,
SOCKET_CLI_ISSUES_URL,
SOCKET_CLI_SHADOW_ACCEPT_RISKS,
Expand Down
107 changes: 61 additions & 46 deletions src/utils/coana-release.mts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ import { getDefaultOrgSlug } from '../commands/ci/fetch-default-org-slug.mts'
import constants, {
COANA_CLI_VERSION,
ERROR_UNABLE_RESOLVE_ORG,
SOCKET_CLI_API_TOKEN_VARIABLES,
} from '../constants.mts'
import { apiFetch, sendApiRequest } from './api.mts'
import { getErrorCause } from './errors.mts'
import { withTmpDir } from './fs.mts'
import {
getCliUserAgent,
getDefaultApiBaseUrl,
getDefaultProxyUrl,
resolveDefaultApiToken,
} from './sdk.mts'
Expand Down Expand Up @@ -65,7 +67,7 @@ type CoanaDownload = { ok: true } | { ok: false; status: number }
type CoanaSpawnOptions = {
coanaVersion?: string | undefined
cwd?: string | URL | undefined
env?: Record<string, string | undefined> | undefined
repoName?: string | undefined
spinner?: Spinner | undefined
stdio?: SpawnOptions['stdio'] | undefined
}
Expand All @@ -75,6 +77,10 @@ const COANA_CACHE_SCRIPT = 'coana-cache.mjs'
const COMPONENT = 'cli'
const NOT_CACHED_EXIT_CODE = 4
const SHA256_REGEXP = /^[0-9a-f]{64}$/
const TOKEN_VARIABLES: ReadonlySet<string> = new Set([
...SOCKET_CLI_API_TOKEN_VARIABLES,
'SOCKET_CLI_CONFIG',
])

function cacheResultToCResult(result: CoanaCacheResult): CResult<string> {
if (result.exitCode === 0) {
Expand All @@ -91,6 +97,30 @@ function cacheResultToCResult(result: CoanaCacheResult): CResult<string> {
}
}

/**
* The user's `env` for Coana, without:
* - the `npm_package_*` variables that npm, pnpm and yarn classic set for each
* leaf of the cwd's package.json. Coana doesn't read them, and in a large
* monorepo they can push argv and env past ARG_MAX, so that the spawn fails
* with E2BIG.
* - the variables socket-cli reads the API token from, and SOCKET_CLI_CONFIG,
* which can carry one. Coana gets the token from socket-cli, and would pass
* them on to the tools it runs.
*
* 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 {
const out: NodeJS.ProcessEnv = {}
for (const key of Object.keys(env)) {
out[key] =
key.startsWith('npm_package_') || TOKEN_VARIABLES.has(key)
? undefined
: env[key]
}
return out
}

/**
* Build a CResult error from a thrown spawn error, preserving exit code,
* signal, and stderr context.
Expand Down Expand Up @@ -369,28 +399,15 @@ async function runCoanaCache(
}
}

/**
* `env` without the `npm_package_*` variables that npm, pnpm and yarn classic
* set for each leaf of the cwd's package.json. Coana doesn't read them, and in
* a large monorepo they can push argv and env past ARG_MAX, so that the spawn
* fails with E2BIG.
*
* The registry's `spawn` spreads `process.env` under the env it is given, so
* they are set to `undefined`, which Node drops.
*/
function withoutNpmPackageEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
const out: NodeJS.ProcessEnv = {}
for (const key of Object.keys(env)) {
out[key] = key.startsWith('npm_package_') ? undefined : env[key]
}
return out
}

/**
* Run the Coana CLI, downloading it into the cache that Coana and the Socket
* CLIs share when the cache lacks the version. Returns a CResult with Coana's
* stdout.
*
* Coana runs in the user's environment, less what coanaUserEnv leaves out, plus
* the variables socket-cli sets for it. Coana passes its environment on to the
* build tools it runs, after removing the variables it reads.
*
* If SOCKET_CLI_COANA_LOCAL_PATH environment variable is set, uses the local
* Coana CLI at that path instead.
*/
Expand All @@ -402,7 +419,7 @@ export async function spawnCoana(
const {
coanaVersion,
cwd,
env: spawnEnv,
repoName,
spinner,
stdio = 'inherit',
} = {
Expand Down Expand Up @@ -434,51 +451,49 @@ export async function spawnCoana(
}
}

const mixinsEnv: Record<string, string> = {
SOCKET_CLI_VERSION: constants.ENV.INLINED_SOCKET_CLI_VERSION,
// Forwarded to the Coana CLI so it can append our product token to its
// outbound axios User-Agent header.
SOCKET_CALLER_USER_AGENT: getCliUserAgent(),
}
let defaultApiToken: string | undefined
let apiToken: string | undefined
try {
defaultApiToken = await resolveDefaultApiToken()
apiToken = await resolveDefaultApiToken()
} catch (error) {
return {
ok: false,
message: 'Socket authentication failed',
cause: error instanceof Error ? error.message : String(error),
}
}
if (defaultApiToken) {
mixinsEnv['SOCKET_CLI_API_TOKEN'] = defaultApiToken
}

const org: CResult<string> = orgSlug
? { ok: true, data: orgSlug }
: await getDefaultOrgSlug()
if (org.ok) {
mixinsEnv['SOCKET_ORG_SLUG'] = org.data
const socketCliVariables: Record<string, string | undefined> = {
SOCKET_CALLER_USER_AGENT: getCliUserAgent(),
SOCKET_CLI_API_BASE_URL: getDefaultApiBaseUrl(),
SOCKET_CLI_API_PROXY: getDefaultProxyUrl(),
SOCKET_CLI_API_TOKEN: apiToken,
SOCKET_CLI_VERSION: constants.ENV.INLINED_SOCKET_CLI_VERSION,
SOCKET_ORG_SLUG: org.ok ? org.data : undefined,
// The default name would mix the cached configuration of unrelated
// projects.
SOCKET_REPO_NAME:
repoName && repoName !== constants.SOCKET_DEFAULT_REPOSITORY
? repoName
: undefined,
}

const proxyUrl = getDefaultProxyUrl()
if (proxyUrl) {
mixinsEnv['SOCKET_CLI_API_PROXY'] = proxyUrl
const userEnv = coanaUserEnv(process.env)
const env = { ...userEnv }
for (const { 0: name, 1: value } of Object.entries(socketCliVariables)) {
// Unset ones leave the user's own, except SOCKET_CLI_API_TOKEN, which
// coanaUserEnv removed: with no token from socket-cli, Coana gets none.
if (value !== undefined) {
env[name] = value
}
}

const finalEnv = withoutNpmPackageEnv({
...process.env,
...constants.processEnv,
...mixinsEnv,
...spawnEnv,
})

let scriptPath = localPath
if (!scriptPath) {
const coanaDirCResult = await getCoanaCliDir(
coanaVersion || COANA_CLI_VERSION,
org,
finalEnv,
userEnv,
spinner,
)
if (!coanaDirCResult.ok) {
Expand All @@ -493,7 +508,7 @@ export async function spawnCoana(
const spawnResult = await spawn(
isBinary ? scriptPath : constants.execPath,
isBinary ? args : [scriptPath, ...args],
{ cwd, env: finalEnv, spinner, stdio },
{ cwd, env, spinner, stdio },
)
return { ok: true, data: String(spawnResult.stdout) }
} catch (e) {
Expand Down
Loading
Loading