From 549e452977b167826225bc445b96a7ffeff2529b Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 15:02:44 +0100 Subject: [PATCH] Keep the Socket API token out of the tools Coana runs Coana passes its environment on to the build tools and package managers it runs. It now removes the variables it reads (the API token, organization, API base URL, proxy, User-Agent, CLI version and repository name) at startup, so socket-cli sets only those for it. socket-cli also leaves out the other variables it reads the token from (SOCKET_SECURITY_API_TOKEN, SOCKET_SECURITY_API_KEY, SOCKET_CLI_API_KEY) and SOCKET_CLI_CONFIG, which can carry one; Coana reads none of them. It no longer adds its own normalised settings (constants.processEnv) to Coana's environment, nor the branch name, which Coana does not read. --- CHANGELOG.md | 1 + src/commands/scan/handle-create-new-scan.mts | 1 - .../scan/perform-reachability-analysis.mts | 15 +-- .../perform-reachability-analysis.test.mts | 17 ++- src/constants.mts | 17 ++- src/utils/coana-release.mts | 107 ++++++++++-------- src/utils/coana-release.test.mts | 95 +++++++++++++--- test/utils.mts | 35 +++--- 8 files changed, 189 insertions(+), 99 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07b54ebbb4..a29e95799a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index d13c8a38e3..7e3171cca2 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -337,7 +337,6 @@ async function createNewScan( spinner.start() const reachResult = await performReachabilityAnalysis({ - branchName, cwd, factsOnlyTypes, orgSlug, diff --git a/src/commands/scan/perform-reachability-analysis.mts b/src/commands/scan/perform-reachability-analysis.mts index 9e57bc1a0a..582ddb5c74 100644 --- a/src/commands/scan/perform-reachability-analysis.mts +++ b/src/commands/scan/perform-reachability-analysis.mts @@ -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 @@ -83,7 +82,6 @@ export async function performReachabilityAnalysis( options: ReachabilityAnalysisOptions, ): Promise> { const { - branchName, cwd = process.cwd(), factsOnlyTypes, orgSlug, @@ -276,17 +274,6 @@ export async function performReachabilityAnalysis( ...(sidecarPath ? ['--compute-artifacts-sidecar', sidecarPath] : []), ] - // Build environment variables. - const coanaEnv: Record = {} - // 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 @@ -300,7 +287,7 @@ export async function performReachabilityAnalysis( const coanaResult = await spawnCoana(coanaArgs, orgSlug, { coanaVersion: reachabilityOptions.reachVersion, cwd, - env: coanaEnv, + repoName, spinner, stdio: coanaStdio, }) diff --git a/src/commands/scan/perform-reachability-analysis.test.mts b/src/commands/scan/perform-reachability-analysis.test.mts index 82add0f187..df1c474e81 100644 --- a/src/commands/scan/perform-reachability-analysis.test.mts +++ b/src/commands/scan/perform-reachability-analysis.test.mts @@ -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(() => { @@ -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: [] }), @@ -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, diff --git a/src/constants.mts b/src/constants.mts index 107d6bf200..443973984e 100644 --- a/src/constants.mts +++ b/src/constants.mts @@ -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' @@ -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. @@ -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, diff --git a/src/utils/coana-release.mts b/src/utils/coana-release.mts index 773f16d94d..b570d6ecbd 100644 --- a/src/utils/coana-release.mts +++ b/src/utils/coana-release.mts @@ -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' @@ -65,7 +67,7 @@ type CoanaDownload = { ok: true } | { ok: false; status: number } type CoanaSpawnOptions = { coanaVersion?: string | undefined cwd?: string | URL | undefined - env?: Record | undefined + repoName?: string | undefined spinner?: Spinner | undefined stdio?: SpawnOptions['stdio'] | undefined } @@ -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 = new Set([ + ...SOCKET_CLI_API_TOKEN_VARIABLES, + 'SOCKET_CLI_CONFIG', +]) function cacheResultToCResult(result: CoanaCacheResult): CResult { if (result.exitCode === 0) { @@ -91,6 +97,30 @@ function cacheResultToCResult(result: CoanaCacheResult): CResult { } } +/** + * 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. @@ -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. */ @@ -402,7 +419,7 @@ export async function spawnCoana( const { coanaVersion, cwd, - env: spawnEnv, + repoName, spinner, stdio = 'inherit', } = { @@ -434,15 +451,9 @@ export async function spawnCoana( } } - const mixinsEnv: Record = { - 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, @@ -450,35 +461,39 @@ export async function spawnCoana( cause: error instanceof Error ? error.message : String(error), } } - if (defaultApiToken) { - mixinsEnv['SOCKET_CLI_API_TOKEN'] = defaultApiToken - } - const org: CResult = orgSlug ? { ok: true, data: orgSlug } : await getDefaultOrgSlug() - if (org.ok) { - mixinsEnv['SOCKET_ORG_SLUG'] = org.data + const socketCliVariables: Record = { + 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) { @@ -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) { diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index f7454f0392..b922640b86 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -3,7 +3,8 @@ * * Test Coverage: * - spawnCoana: runs cli-wrapper.mjs from the cache with the caller's args, - * cwd and environment, and surfaces a failing run's output. + * cwd and environment, sets the variables Coana reads, leaves the user's + * API token variables out, and surfaces a failing run's output. * * Testing Approach: * A fake cli-wrapper.mjs is installed into a temporary cache with the real @@ -19,13 +20,26 @@ import { promises as fs } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from 'vitest' import { spawn } from '@socketsecurity/registry/lib/spawn' -import constants from '../constants.mts' +import constants, { SOCKET_CLI_API_TOKEN_VARIABLES } from '../constants.mts' import { spawnCoana } from './coana-release.mts' -import { getCliUserAgent } from './sdk.mts' +import { overrideCachedConfig, resetConfigForTesting } from './config.mts' +import { + getCliUserAgent, + getDefaultApiBaseUrl, + resolveDefaultApiToken, +} from './sdk.mts' const VERSION = '1.2.3' @@ -88,6 +102,10 @@ describe('spawnCoana', () => { ) }) + afterEach(() => { + vi.unstubAllEnvs() + }) + afterAll(async () => { if (savedXdgCacheHome === undefined) { delete process.env['XDG_CACHE_HOME'] @@ -121,19 +139,70 @@ describe('spawnCoana', () => { } }) - it('sets SOCKET_ORG_SLUG and SOCKET_CALLER_USER_AGENT, which options.env overrides', async () => { + it('sets the variables Coana reads', async () => { + overrideCachedConfig(JSON.stringify({ apiToken: 'socket-cli-token' })) + try { + const apiToken = await resolveDefaultApiToken() + expect(apiToken).toBeTruthy() + + const { env } = await runFake({ repoName: 'repo' }) + + expect(env).toMatchObject({ + SOCKET_CALLER_USER_AGENT: getCliUserAgent(), + SOCKET_CLI_API_BASE_URL: getDefaultApiBaseUrl(), + SOCKET_CLI_API_TOKEN: apiToken, + SOCKET_CLI_VERSION: constants.ENV.INLINED_SOCKET_CLI_VERSION, + SOCKET_ORG_SLUG: 'acme', + SOCKET_REPO_NAME: 'repo', + }) + } finally { + resetConfigForTesting() + } + }) + + it.for([ + { name: 'names no repository', repoName: undefined }, + { + name: 'names the default repository', + repoName: 'socket-default-repository', + }, + ])( + "leaves the user's SOCKET_REPO_NAME when socket-cli $name", + async ({ repoName }) => { + vi.stubEnv('SOCKET_REPO_NAME', 'users-repo') + + const { env } = await runFake({ repoName }) + + expect(env['SOCKET_REPO_NAME']).toBe('users-repo') + }, + ) + + it("doesn't add constants.processEnv to Coana's environment", async () => { + // Set for every socket-cli process. + expect(constants.processEnv['SOCKET_CLI_GIT_USER_NAME']).toBeTruthy() + const { env } = await runFake() - expect(env['SOCKET_ORG_SLUG']).toBe('acme') - expect(env['SOCKET_CALLER_USER_AGENT']).toBe(getCliUserAgent()) - const overridden = await runFake({ - env: { SOCKET_CALLER_USER_AGENT: 'custom-caller-agent/1.0.0' }, - }) - expect(overridden.env['SOCKET_CALLER_USER_AGENT']).toBe( - 'custom-caller-agent/1.0.0', - ) + expect(env['SOCKET_CLI_GIT_USER_NAME']).toBeUndefined() }) + // Coana gets the token as SOCKET_CLI_API_TOKEN. + it.for([ + ...SOCKET_CLI_API_TOKEN_VARIABLES.filter( + name => name !== 'SOCKET_CLI_API_TOKEN', + ).map(name => ({ name, value: 'users-token' })), + { name: 'SOCKET_CLI_CONFIG', value: '{"apiToken":"users-token"}' }, + ])( + "leaves the user's $name out of Coana's environment", + async ({ name, value }) => { + vi.stubEnv(name, value) + + const { env } = await runFake() + + expect(env[name]).toBeUndefined() + }, + ) + it('surfaces captured stdout when stderr is empty (Coana logs some failures to stdout)', async () => { const result = await spawnCoana(['fail'], 'acme', { coanaVersion: VERSION, diff --git a/test/utils.mts b/test/utils.mts index aa3e882eec..b4bc7242cc 100644 --- a/test/utils.mts +++ b/test/utils.mts @@ -11,6 +11,7 @@ import constants, { COANA_CLI_VERSION, FLAG_HELP, FLAG_VERSION, + SOCKET_CLI_API_TOKEN_VARIABLES, } from '../src/constants.mts' const __filename = fileURLToPath(import.meta.url) @@ -26,6 +27,12 @@ const __dirname = path.dirname(__filename) // eslint-disable-next-line no-control-regex const asciiUnsafeRegexp = /[\u0000-\u0007\u0009\u000b-\u001f\u0080-\uffff]/g +const SOCKET_AUTH_VARIABLES: ReadonlySet = new Set([ + ...SOCKET_CLI_API_TOKEN_VARIABLES, + 'SOCKET_CLI_API_BASE_URL', + 'SOCKET_CLI_ORG_SLUG', +]) + // Note: The fixture directory is in the same directory as this utils file. export const testPath = __dirname @@ -106,6 +113,14 @@ function normalizeEnvironmentPaths(str: string): string { }, str) } +function withoutSocketAuthEnv( + env: NodeJS.ProcessEnv, +): Record { + return Object.fromEntries( + Object.entries(env).filter(entry => !SOCKET_AUTH_VARIABLES.has(entry[0])), + ) +} + function toAsciiSafeString(str: string): string { return str.replace(asciiUnsafeRegexp, m => { const code = m.charCodeAt(0) @@ -208,24 +223,8 @@ export async function spawnSocketCli( } as SpawnOptions try { // Exclude Socket auth credentials to ensure tests run unauthenticated. - const { - SOCKET_CLI_API_BASE_URL: unusedApiBaseUrl, - SOCKET_CLI_API_KEY: unusedCliApiKey, - SOCKET_CLI_API_TOKEN: unusedCliApiToken, - SOCKET_CLI_ORG_SLUG: unusedOrgSlug, - SOCKET_SECURITY_API_KEY: unusedApiKey, - SOCKET_SECURITY_API_TOKEN: unusedSecurityApiToken, - ...cleanEnv - } = process.env - const { - SOCKET_CLI_API_BASE_URL: unusedProcessApiBaseUrl, - SOCKET_CLI_API_KEY: unusedProcessCliApiKey, - SOCKET_CLI_API_TOKEN: unusedProcessCliApiToken, - SOCKET_CLI_ORG_SLUG: unusedProcessOrgSlug, - SOCKET_SECURITY_API_KEY: unusedProcessApiKey, - SOCKET_SECURITY_API_TOKEN: unusedProcessSecurityApiToken, - ...cleanProcessEnv - } = constants.processEnv + const cleanEnv = withoutSocketAuthEnv(process.env) + const cleanProcessEnv = withoutSocketAuthEnv(constants.processEnv) const nativeBinary = process.env['SOCKET_CLI_NATIVE_TEST_BINARY'] const nativeStage = process.env['SOCKET_CLI_NATIVE_TEST_STAGE'] const executionEnv = {