From 9fedd80de6a1f2b7162bb186696014543aa94d21 Mon Sep 17 00:00:00 2001 From: Oskar Haarklou Veileborg Date: Thu, 3 Dec 2026 15:16:22 +0100 Subject: [PATCH 1/5] feat(coana): download the Coana CLI through SOCKET_COANA_MIRROR_URL Machines that can't reach storage.googleapis.com can mirror Coana's bucket, for example with an Artifactory remote repository, and set SOCKET_COANA_MIRROR_URL to it. Each signed URL for the cli component then has its https://storage.googleapis.com/socket-coana-cli/ prefix replaced with the mirror's URL, keeping the signature, including the URL requested anew after a 4xx. Coana, which inherits the variable, follows the same rule for its own components. A signed URL outside the bucket is refused rather than fetched from GCS. A mirror URL that isn't https, or that has a query or fragment, is refused before the API is asked, without echoing the value. socket-cli downloads over https only, so unlike Coana it doesn't accept an http mirror. --- CHANGELOG.md | 1 + README.md | 3 + src/utils/coana-release.test.mts | 160 ++++++++++++++++++++++++++++++- src/utils/coana/release.mts | 76 ++++++++++++++- 4 files changed, 235 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 947a2c1c3..53ee1e2fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ### Added +- Download the Coana CLI on networks that can't reach `storage.googleapis.com`: set `SOCKET_COANA_MIRROR_URL` to an https mirror of Socket's download bucket, such as an Artifactory remote repository. - Catch reachability analyses that stop early: with `--reach-incomplete-analysis-as-error`, `socket scan create --reach` and `socket scan reach` report a vulnerability whose analysis hit the timeout or memory limit before finding a reachable path as an analysis error instead of unreachable. ### Changed diff --git a/README.md b/README.md index 42e827b2a..2248b0985 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,8 @@ Full application reachability (`socket scan reach`, `socket scan create --reach` The engine comes from Socket, not npm, so an npm mirror or registry proxy does not cover the engine download. The registry row does not apply when your dependencies are already installed in the scanned directory, for example a `node_modules` directory from an earlier `npm ci`. +**When `storage.googleapis.com` is blocked**, mirror `https://storage.googleapis.com/socket-coana-cli/`, for example with an Artifactory generic remote repository that has "Propagate Query Params" turned on, and set `SOCKET_COANA_MIRROR_URL` to the mirror's https URL. The engine is then downloaded from the mirror, with the same paths and signed query strings as in the bucket. Coana versions that support the variable download their analyzers through it too. + The engine is cached in `$XDG_CACHE_HOME/socket/coana` (`~/.cache/socket/coana` by default). Persist that directory between CI runs to skip the download; with a warm cache, `storage.googleapis.com` is not contacted. **Behind an HTTP(S) proxy**, set `NODE_USE_ENV_PROXY=1` along with `HTTPS_PROXY`. The CLI does not currently route its own requests through `HTTPS_PROXY` or `SOCKET_CLI_API_PROXY`, and fails with `getaddrinfo EAI_AGAIN api.socket.dev`. `NODE_USE_ENV_PROXY=1` (Node.js 22.21 or later) makes Node.js send them through the proxy: @@ -176,6 +178,7 @@ Supports version 2 format with `projectIgnorePaths` for excluding files from rep - `SOCKET_CLI_ORG_SLUG` - Socket organization slug - `SOCKET_CLI_SOCKET_PATCH_PATH` - Path to an executable socket-patch binary for standalone builds - `SOCKET_CLI_VIEW_ALL_RISKS` - Show all npm/npx risks +- `SOCKET_COANA_MIRROR_URL` - https mirror to download the reachability engine from; see [Network access](#network-access) ### See also diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index d672796c5..7571e1f0b 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -4,7 +4,8 @@ * Test Coverage: * - spawnCoana: runs cli-wrapper.mjs from the cache with the caller's args, * cwd and environment, sets the variables Coana reads, leaves the user's - * API token variables out, and surfaces a failing run's output. + * API token variables out, and surfaces a failing run's output. Downloads + * through the mirror that SOCKET_COANA_MIRROR_URL names. * * Testing Approach: * A fake cli-wrapper.mjs is installed into a temporary cache with the real @@ -85,6 +86,10 @@ async function runFake( return JSON.parse(result.data) as FakeRun } +function signedUrl(signature: string): string { + return `https://storage.googleapis.com/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=${signature}` +} + describe('spawnCoana', () => { const savedXdgCacheHome = process.env['XDG_CACHE_HOME'] let tmpDir: string @@ -315,6 +320,159 @@ describe('spawnCoana', () => { expect(run.args).toEqual(['run', '.']) }) + describe('through SOCKET_COANA_MIRROR_URL', () => { + const MIRROR_URL = 'https://mirror.test/socket-coana-cli' + let tarball: Buffer + + /** + * Runs Coana from an empty cache. The Socket API answers with `signedUrls` + * in turn, and downloads with `statuses` in turn, then with the tarball. + */ + async function runFromMirror({ + mirrorUrl = MIRROR_URL, + signedUrls, + statuses = [], + }: { + mirrorUrl?: string + signedUrls: string[] + statuses?: number[] + }) { + vi.stubEnv( + 'XDG_CACHE_HOME', + await fs.mkdtemp(path.join(tmpDir, 'mirror-cache-')), + ) + vi.stubEnv('SOCKET_COANA_MIRROR_URL', mirrorUrl) + const pendingUrls = [...signedUrls] + const pendingStatuses = [...statuses] + const sha256 = createHash('sha256').update(tarball).digest('hex') + const request = vi + .spyOn(api, 'sendApiRequest') + .mockImplementation(async () => ({ + ok: true, + data: { + version: VERSION, + components: { + cli: { sha256, size: tarball.length, url: pendingUrls.shift() }, + }, + }, + })) + const download = vi + .spyOn(api, 'apiFetch') + .mockImplementation(async () => { + const status = pendingStatuses.shift() + return status === undefined + ? new Response(new Uint8Array(tarball)) + : new Response(null, { status }) + }) + const result = await spawnCoana(['run', '.'], 'acme', { + coanaVersion: VERSION, + stdio: 'pipe', + }) + return { + downloads: download.mock.calls.map(call => call[0]), + requests: request.mock.calls.length, + result, + } + } + + beforeAll(async () => { + const fixture = path.join(tmpDir, 'mirror-fixture') + const archive = path.join(tmpDir, 'mirror.tar.gz') + await fs.mkdir(fixture) + await fs.writeFile(coanaCliWrapperPath(fixture), FAKE_CLI_WRAPPER) + await createTar({ cwd: fixture, file: archive, gzip: true }, [ + COANA_CLI_WRAPPER_FILENAME, + ]) + tarball = await fs.readFile(archive) + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it("replaces the bucket's prefix with the mirror's URL and keeps the signature", async () => { + const { downloads, result } = await runFromMirror({ + signedUrls: [signedUrl('first')], + }) + + expect(result.ok).toBe(true) + expect(downloads).toEqual([ + 'https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=first', + ]) + }) + + it('rewrites the URL it requests anew after the mirror refuses one', async () => { + const { downloads, requests, result } = await runFromMirror({ + signedUrls: [signedUrl('first'), signedUrl('second')], + statuses: [403], + }) + + expect(result.ok).toBe(true) + expect(requests).toBe(2) + expect(downloads).toEqual([ + 'https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=first', + 'https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=second', + ]) + }) + + it("names the mirror's host when a download fails", async () => { + const { result } = await runFromMirror({ + signedUrls: [signedUrl('first')], + statuses: [500], + }) + + expect(result).toEqual({ + ok: false, + message: `Failed to download the Coana CLI ${VERSION}`, + cause: 'mirror.test responded with status 500.', + }) + }) + + it.for([ + 'https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz?X-Goog-Signature=secret', + 'https://storage.googleapis.com/socket-coana-cli/../another-bucket/objects/SHA.tar.gz?X-Goog-Signature=secret', + 'https://storage.googleapis.com/socket-coana-cli/%2e%2e/another-bucket/objects/SHA.tar.gz?X-Goog-Signature=secret', + ])( + 'refuses %s, outside the bucket, without showing its signature', + async url => { + const { downloads, result } = await runFromMirror({ signedUrls: [url] }) + + expect(result).toEqual({ + ok: false, + message: 'Socket API error', + cause: `Socket provided the Coana CLI ${VERSION} at https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz, outside https://storage.googleapis.com/socket-coana-cli/, which SOCKET_COANA_MIRROR_URL mirrors`, + }) + expect(downloads).toEqual([]) + }, + ) + + it.for([ + 'not a URL', + 'http://mirror.test/', + 'ftp://mirror.test/', + 'https://mirror.test/?token=secret', + 'https://mirror.test/#secret', + 'https://mirror.test/?', + 'https://mirror.test/#', + ])( + 'refuses %s before asking Socket, without showing it', + async mirrorUrl => { + const { requests, result } = await runFromMirror({ + mirrorUrl, + signedUrls: [], + }) + + expect(result).toEqual({ + ok: false, + message: `Failed to get the Coana CLI ${VERSION}`, + cause: + 'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.', + }) + expect(requests).toBe(0) + }, + ) + }) + 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/src/utils/coana/release.mts b/src/utils/coana/release.mts index 3f71a3df2..f7d9d07f0 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -71,6 +71,12 @@ type CoanaComponent = { type CoanaDownload = { ok: true } | { ok: false; status: number } +/** + * The URL to download a signed URL from, or `undefined` when it lies outside + * the bucket that SOCKET_COANA_MIRROR_URL mirrors. + */ +type CoanaDownloadUrl = (signedUrl: string) => string | undefined + type CoanaSpawnOptions = { coanaVersion?: string | undefined cwd?: string | URL | undefined @@ -83,6 +89,8 @@ type CoanaSpawnOptions = { } const CACHE_NOT_WRITABLE_EXIT_CODE = 3 +// SOCKET_COANA_MIRROR_URL replaces this prefix of the signed URLs. +const COANA_BUCKET_URL = 'https://storage.googleapis.com/socket-coana-cli/' const COMPONENT = 'cli' const NOT_CACHED_EXIT_CODE = 4 const SHA256_REGEXP = /^[0-9a-f]{64}$/ @@ -243,9 +251,20 @@ async function getCoanaCliDir( } } const orgSlug = org.data + const downloadUrl = parseCoanaMirror(process.env['SOCKET_COANA_MIRROR_URL']) + if (!downloadUrl) { + // The value may carry credentials. + return { + ok: false, + message: `Failed to get the Coana CLI ${versionSpec}`, + cause: + 'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.', + } + } const artifacts = await requestArtifacts( exactVersion ?? versionSpec, orgSlug, + downloadUrl, ) if (!artifacts.ok) { return artifacts @@ -266,7 +285,7 @@ async function getCoanaCliDir( } try { return withVersion( - await installComponent(artifacts.data, orgSlug, env), + await installComponent(artifacts.data, orgSlug, downloadUrl, env), artifacts.data.version, ) } finally { @@ -294,6 +313,7 @@ async function getCoanaCliDir( async function installComponent( artifacts: CoanaArtifacts, orgSlug: string, + downloadUrl: CoanaDownloadUrl, env: NodeJS.ProcessEnv, ): Promise> { return await withTmpDir('socket-coana-cli-', async extractDir => { @@ -302,7 +322,11 @@ async function installComponent( // A 4xx means the signed URL expired or was otherwise refused. if (!download.ok && download.status >= 400 && download.status < 500) { // Pin the new request to the resolved version, which a range is not. - const renewed = await requestArtifacts(current.version, orgSlug) + const renewed = await requestArtifacts( + current.version, + orgSlug, + downloadUrl, + ) if (!renewed.ok) { return renewed } @@ -313,7 +337,7 @@ async function installComponent( return { ok: false, message: `Failed to download the Coana CLI ${current.version}`, - cause: `The download host responded with status ${download.status}.`, + cause: `${new URL(current.cli.url).host} responded with status ${download.status}.`, } } return cacheResultToCResult( @@ -353,9 +377,40 @@ function parseCoanaArtifacts(value: unknown): CoanaArtifacts | undefined { return { cli: { sha256, size, url }, version } } +/** + * Where to download signed URLs from, given SOCKET_COANA_MIRROR_URL's value, + * or `undefined` when the value is invalid. "Downloading through a mirror" in + * coana-package-manager's packages/cli/docs/gcs-releases.md specifies the rule. + * The mirror must be https, the only protocol apiFetch speaks. + */ +function parseCoanaMirror( + value: string | undefined, +): CoanaDownloadUrl | undefined { + if (!value) { + return signedUrl => signedUrl + } + if (!URL.canParse(value)) { + return undefined + } + const { href, protocol } = new URL(value) + // `search` and `hash` are empty for a bare `?` or `#`. + if (protocol !== 'https:' || /[?#]/.test(href)) { + return undefined + } + const base = href.endsWith('/') ? href : `${href}/` + return signedUrl => { + // Normalized first, so that `..` segments can't climb out of the bucket. + const normalized = new URL(signedUrl).href + return normalized.startsWith(COANA_BUCKET_URL) + ? base + normalized.slice(COANA_BUCKET_URL.length) + : undefined + } +} + async function requestArtifacts( versionSpec: string, orgSlug: string, + downloadUrl: CoanaDownloadUrl, ): Promise> { const result = await sendApiRequest( `orgs/${encodeURIComponent(orgSlug)}/coana-cli/artifacts`, @@ -376,7 +431,20 @@ async function requestArtifacts( cause: `Unexpected response to a request for the Coana CLI ${versionSpec}`, } } - return { ok: true, data: artifacts } + const url = downloadUrl(artifacts.cli.url) + if (url === undefined) { + // Leaves out the query, which holds the signature. + const { origin, pathname } = new URL(artifacts.cli.url) + return { + ok: false, + message: 'Socket API error', + cause: `Socket provided the Coana CLI ${versionSpec} at ${origin}${pathname}, outside ${COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors`, + } + } + return { + ok: true, + data: { ...artifacts, cli: { ...artifacts.cli, url } }, + } } /** From 691211716b7c5a98f3f0a48c1c1d53ec8ce223c7 Mon Sep 17 00:00:00 2001 From: Oskar Haarklou Veileborg Date: Fri, 4 Dec 2026 08:52:08 +0100 Subject: [PATCH 2/5] refactor(coana): simplify the mirror URL rewrite Parse the signed URL once into a URL, and have the mirror rule throw its errors so that the existing catch reports them as failures to get the Coana CLI. installComponent takes the request function instead of the org slug and mirror rule. The tests share one tarball fixture and API response. --- src/utils/coana-release.test.mts | 93 ++++++++++++---------------- src/utils/coana/release.mts | 102 +++++++++++++------------------ 2 files changed, 80 insertions(+), 115 deletions(-) diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 7571e1f0b..5f9b7edd1 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -92,8 +92,23 @@ function signedUrl(signature: string): string { describe('spawnCoana', () => { const savedXdgCacheHome = process.env['XDG_CACHE_HOME'] + let tarball: Buffer + let tarballSha256: string let tmpDir: string + /** The Socket API's answer to a request for `version` of the tarball at `url`. */ + function artifactsResponse(version: string, url: string) { + return { + ok: true as const, + data: { + version, + components: { + cli: { sha256: tarballSha256, size: tarball.length, url }, + }, + }, + } + } + beforeAll(async () => { tmpDir = await fs.realpath( await fs.mkdtemp(path.join(os.tmpdir(), 'socket-coana-release-')), @@ -112,6 +127,15 @@ describe('spawnCoana', () => { ) }), ) + const fixture = path.join(tmpDir, 'download-fixture') + const archive = path.join(tmpDir, 'coana.tar.gz') + await fs.mkdir(fixture) + await fs.writeFile(coanaCliWrapperPath(fixture), FAKE_CLI_WRAPPER) + await createTar({ cwd: fixture, file: archive, gzip: true }, [ + COANA_CLI_WRAPPER_FILENAME, + ]) + tarball = await fs.readFile(archive) + tarballSha256 = createHash('sha256').update(tarball).digest('hex') }) afterEach(() => { @@ -135,14 +159,6 @@ describe('spawnCoana', () => { }) it('downloads and runs Coana on the first SEA invocation', async () => { - const archive = path.join(tmpDir, 'coana.tar.gz') - const fixture = path.join(tmpDir, 'download-fixture') - await fs.mkdir(fixture) - await fs.writeFile(coanaCliWrapperPath(fixture), FAKE_CLI_WRAPPER) - await createTar({ cwd: fixture, file: archive, gzip: true }, [ - COANA_CLI_WRAPPER_FILENAME, - ]) - const bytes = await fs.readFile(archive) const version = '1.2.4' const url = 'https://example.test/coana.tar.gz' const sea = vi.spyOn(seaRuntime, 'isSea').mockReturnValue(true) @@ -159,22 +175,12 @@ describe('spawnCoana', () => { }) return { code: 0, signal: null, stdout: result.stdout } }) - const request = vi.spyOn(api, 'sendApiRequest').mockResolvedValue({ - ok: true, - data: { - version, - components: { - cli: { - sha256: createHash('sha256').update(bytes).digest('hex'), - size: bytes.length, - url, - }, - }, - }, - }) + const request = vi + .spyOn(api, 'sendApiRequest') + .mockResolvedValue(artifactsResponse(version, url)) const download = vi .spyOn(api, 'apiFetch') - .mockResolvedValue(new Response(new Uint8Array(bytes))) + .mockResolvedValue(new Response(new Uint8Array(tarball))) try { const options = { coanaVersion: version, cwd: tmpDir } expect((await runFake(options)).args).toEqual(['run', '.']) @@ -322,7 +328,6 @@ describe('spawnCoana', () => { describe('through SOCKET_COANA_MIRROR_URL', () => { const MIRROR_URL = 'https://mirror.test/socket-coana-cli' - let tarball: Buffer /** * Runs Coana from an empty cache. The Socket API answers with `signedUrls` @@ -342,28 +347,19 @@ describe('spawnCoana', () => { await fs.mkdtemp(path.join(tmpDir, 'mirror-cache-')), ) vi.stubEnv('SOCKET_COANA_MIRROR_URL', mirrorUrl) - const pendingUrls = [...signedUrls] - const pendingStatuses = [...statuses] - const sha256 = createHash('sha256').update(tarball).digest('hex') const request = vi .spyOn(api, 'sendApiRequest') - .mockImplementation(async () => ({ - ok: true, - data: { - version: VERSION, - components: { - cli: { sha256, size: tarball.length, url: pendingUrls.shift() }, - }, - }, - })) + .mockRejectedValue(new Error('Unexpected request')) + for (const url of signedUrls) { + request.mockResolvedValueOnce(artifactsResponse(VERSION, url)) + } + // A body can be read only once, so each download gets a new Response. const download = vi .spyOn(api, 'apiFetch') - .mockImplementation(async () => { - const status = pendingStatuses.shift() - return status === undefined - ? new Response(new Uint8Array(tarball)) - : new Response(null, { status }) - }) + .mockImplementation(async () => new Response(new Uint8Array(tarball))) + for (const status of statuses) { + download.mockResolvedValueOnce(new Response(null, { status })) + } const result = await spawnCoana(['run', '.'], 'acme', { coanaVersion: VERSION, stdio: 'pipe', @@ -375,17 +371,6 @@ describe('spawnCoana', () => { } } - beforeAll(async () => { - const fixture = path.join(tmpDir, 'mirror-fixture') - const archive = path.join(tmpDir, 'mirror.tar.gz') - await fs.mkdir(fixture) - await fs.writeFile(coanaCliWrapperPath(fixture), FAKE_CLI_WRAPPER) - await createTar({ cwd: fixture, file: archive, gzip: true }, [ - COANA_CLI_WRAPPER_FILENAME, - ]) - tarball = await fs.readFile(archive) - }) - afterEach(() => { vi.restoreAllMocks() }) @@ -439,8 +424,8 @@ describe('spawnCoana', () => { expect(result).toEqual({ ok: false, - message: 'Socket API error', - cause: `Socket provided the Coana CLI ${VERSION} at https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz, outside https://storage.googleapis.com/socket-coana-cli/, which SOCKET_COANA_MIRROR_URL mirrors`, + message: `Failed to get the Coana CLI ${VERSION}`, + cause: `Socket provided the Coana CLI at https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz, outside https://storage.googleapis.com/socket-coana-cli/, which SOCKET_COANA_MIRROR_URL mirrors`, }) expect(downloads).toEqual([]) }, diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index f7d9d07f0..91ba8bdf3 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -47,6 +47,7 @@ import { resolveDefaultApiToken, } from '../sdk.mts' import { spawn } from '../spawn.mts' +import { parseUrl } from '../url.mts' import type { CResult } from '../../types.mts' import type { SpawnOptions } from '../spawn.mts' @@ -66,16 +67,16 @@ type CoanaCacheResult = { type CoanaComponent = { sha256: string size: number - url: string + url: URL } type CoanaDownload = { ok: true } | { ok: false; status: number } /** - * The URL to download a signed URL from, or `undefined` when it lies outside - * the bucket that SOCKET_COANA_MIRROR_URL mirrors. + * The URL to download a signed URL from. Throws when it lies outside the + * bucket that SOCKET_COANA_MIRROR_URL mirrors. */ -type CoanaDownloadUrl = (signedUrl: string) => string | undefined +type CoanaDownloadUrl = (signedUrl: URL) => URL type CoanaSpawnOptions = { coanaVersion?: string | undefined @@ -177,7 +178,7 @@ async function downloadComponent( component: CoanaComponent, destDir: string, ): Promise { - const response = await apiFetch(component.url, { + const response = await apiFetch(component.url.href, { headers: { 'User-Agent': getCliUserAgent() }, }) if (!response.ok || !response.body) { @@ -252,20 +253,9 @@ async function getCoanaCliDir( } const orgSlug = org.data const downloadUrl = parseCoanaMirror(process.env['SOCKET_COANA_MIRROR_URL']) - if (!downloadUrl) { - // The value may carry credentials. - return { - ok: false, - message: `Failed to get the Coana CLI ${versionSpec}`, - cause: - 'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.', - } - } - const artifacts = await requestArtifacts( - exactVersion ?? versionSpec, - orgSlug, - downloadUrl, - ) + const request = (spec: string) => + requestArtifacts(spec, orgSlug, downloadUrl) + const artifacts = await request(exactVersion ?? versionSpec) if (!artifacts.ok) { return artifacts } @@ -285,7 +275,7 @@ async function getCoanaCliDir( } try { return withVersion( - await installComponent(artifacts.data, orgSlug, downloadUrl, env), + await installComponent(artifacts.data, request, env), artifacts.data.version, ) } finally { @@ -312,8 +302,7 @@ async function getCoanaCliDir( async function installComponent( artifacts: CoanaArtifacts, - orgSlug: string, - downloadUrl: CoanaDownloadUrl, + request: (versionSpec: string) => Promise>, env: NodeJS.ProcessEnv, ): Promise> { return await withTmpDir('socket-coana-cli-', async extractDir => { @@ -322,11 +311,7 @@ async function installComponent( // A 4xx means the signed URL expired or was otherwise refused. if (!download.ok && download.status >= 400 && download.status < 500) { // Pin the new request to the resolved version, which a range is not. - const renewed = await requestArtifacts( - current.version, - orgSlug, - downloadUrl, - ) + const renewed = await request(current.version) if (!renewed.ok) { return renewed } @@ -337,7 +322,7 @@ async function installComponent( return { ok: false, message: `Failed to download the Coana CLI ${current.version}`, - cause: `${new URL(current.cli.url).host} responded with status ${download.status}.`, + cause: `${current.cli.url.host} responded with status ${download.status}.`, } } return cacheResultToCResult( @@ -359,6 +344,7 @@ function parseCoanaArtifacts(value: unknown): CoanaArtifacts | undefined { size?: unknown url?: unknown } + const parsedUrl = typeof url === 'string' ? parseUrl(url) : null if ( typeof version !== 'string' || !semver.valid(version) || @@ -367,43 +353,44 @@ function parseCoanaArtifacts(value: unknown): CoanaArtifacts | undefined { typeof size !== 'number' || !Number.isSafeInteger(size) || size <= 0 || - typeof url !== 'string' || // apiFetch speaks only https. - !url.startsWith('https://') || - !URL.canParse(url) + parsedUrl?.protocol !== 'https:' ) { return undefined } - return { cli: { sha256, size, url }, version } + return { cli: { sha256, size, url: parsedUrl }, version } } /** - * Where to download signed URLs from, given SOCKET_COANA_MIRROR_URL's value, - * or `undefined` when the value is invalid. "Downloading through a mirror" in + * Where to download signed URLs from, given SOCKET_COANA_MIRROR_URL's value. + * Throws when the value is invalid. "Downloading through a mirror" in * coana-package-manager's packages/cli/docs/gcs-releases.md specifies the rule. * The mirror must be https, the only protocol apiFetch speaks. */ -function parseCoanaMirror( - value: string | undefined, -): CoanaDownloadUrl | undefined { +function parseCoanaMirror(value: string | undefined): CoanaDownloadUrl { if (!value) { return signedUrl => signedUrl } - if (!URL.canParse(value)) { - return undefined - } - const { href, protocol } = new URL(value) + const mirrorUrl = parseUrl(value) // `search` and `hash` are empty for a bare `?` or `#`. - if (protocol !== 'https:' || /[?#]/.test(href)) { - return undefined + if (mirrorUrl?.protocol !== 'https:' || /[?#]/.test(mirrorUrl.href)) { + // Leaves out the value, which may carry credentials. + throw new Error( + 'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.', + ) } - const base = href.endsWith('/') ? href : `${href}/` - return signedUrl => { - // Normalized first, so that `..` segments can't climb out of the bucket. - const normalized = new URL(signedUrl).href - return normalized.startsWith(COANA_BUCKET_URL) - ? base + normalized.slice(COANA_BUCKET_URL.length) - : undefined + const base = mirrorUrl.href.endsWith('/') + ? mirrorUrl.href + : `${mirrorUrl.href}/` + return ({ href, origin, pathname }) => { + // `href` is normalized, so `..` segments can't climb out of the bucket. + if (!href.startsWith(COANA_BUCKET_URL)) { + // Leaves out the query, which holds the signature. + throw new Error( + `Socket provided the Coana CLI at ${origin}${pathname}, outside ${COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors`, + ) + } + return new URL(base + href.slice(COANA_BUCKET_URL.length)) } } @@ -431,19 +418,12 @@ async function requestArtifacts( cause: `Unexpected response to a request for the Coana CLI ${versionSpec}`, } } - const url = downloadUrl(artifacts.cli.url) - if (url === undefined) { - // Leaves out the query, which holds the signature. - const { origin, pathname } = new URL(artifacts.cli.url) - return { - ok: false, - message: 'Socket API error', - cause: `Socket provided the Coana CLI ${versionSpec} at ${origin}${pathname}, outside ${COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors`, - } - } return { ok: true, - data: { ...artifacts, cli: { ...artifacts.cli, url } }, + data: { + ...artifacts, + cli: { ...artifacts.cli, url: downloadUrl(artifacts.cli.url) }, + }, } } From 7507e67a2cbf18ce27e318da635d9e53000e9d23 Mon Sep 17 00:00:00 2001 From: Oskar Haarklou Veileborg Date: Fri, 4 Dec 2026 09:32:43 +0100 Subject: [PATCH 3/5] docs(coana): tighten the mirror rewrite comments --- src/utils/coana-release.test.mts | 1 - src/utils/coana/release.mts | 12 ++++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 5f9b7edd1..f1956cc49 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -96,7 +96,6 @@ describe('spawnCoana', () => { let tarballSha256: string let tmpDir: string - /** The Socket API's answer to a request for `version` of the tarball at `url`. */ function artifactsResponse(version: string, url: string) { return { ok: true as const, diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index 91ba8bdf3..3d1940a6e 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -73,8 +73,8 @@ type CoanaComponent = { type CoanaDownload = { ok: true } | { ok: false; status: number } /** - * The URL to download a signed URL from. Throws when it lies outside the - * bucket that SOCKET_COANA_MIRROR_URL mirrors. + * The URL to download a signed URL from. Throws when SOCKET_COANA_MIRROR_URL + * is set and the signed URL lies outside the bucket it mirrors. */ type CoanaDownloadUrl = (signedUrl: URL) => URL @@ -364,8 +364,8 @@ function parseCoanaArtifacts(value: unknown): CoanaArtifacts | undefined { /** * Where to download signed URLs from, given SOCKET_COANA_MIRROR_URL's value. * Throws when the value is invalid. "Downloading through a mirror" in - * coana-package-manager's packages/cli/docs/gcs-releases.md specifies the rule. - * The mirror must be https, the only protocol apiFetch speaks. + * coana-package-manager's packages/cli/docs/gcs-releases.md specifies the rule, + * which allows http too. apiFetch speaks only https. */ function parseCoanaMirror(value: string | undefined): CoanaDownloadUrl { if (!value) { @@ -374,7 +374,7 @@ function parseCoanaMirror(value: string | undefined): CoanaDownloadUrl { const mirrorUrl = parseUrl(value) // `search` and `hash` are empty for a bare `?` or `#`. if (mirrorUrl?.protocol !== 'https:' || /[?#]/.test(mirrorUrl.href)) { - // Leaves out the value, which may carry credentials. + // The value may carry credentials. throw new Error( 'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.', ) @@ -385,7 +385,7 @@ function parseCoanaMirror(value: string | undefined): CoanaDownloadUrl { return ({ href, origin, pathname }) => { // `href` is normalized, so `..` segments can't climb out of the bucket. if (!href.startsWith(COANA_BUCKET_URL)) { - // Leaves out the query, which holds the signature. + // The query holds the signature. throw new Error( `Socket provided the Coana CLI at ${origin}${pathname}, outside ${COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors`, ) From fbe7a91abdde5b4b9303bcc417fbfe755c4302d0 Mon Sep 17 00:00:00 2001 From: Oskar Haarklou Veileborg Date: Fri, 4 Dec 2026 09:34:32 +0100 Subject: [PATCH 4/5] docs: drop the Coana mirror paragraph from the README --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 2248b0985..344aed052 100644 --- a/README.md +++ b/README.md @@ -131,8 +131,6 @@ Full application reachability (`socket scan reach`, `socket scan create --reach` The engine comes from Socket, not npm, so an npm mirror or registry proxy does not cover the engine download. The registry row does not apply when your dependencies are already installed in the scanned directory, for example a `node_modules` directory from an earlier `npm ci`. -**When `storage.googleapis.com` is blocked**, mirror `https://storage.googleapis.com/socket-coana-cli/`, for example with an Artifactory generic remote repository that has "Propagate Query Params" turned on, and set `SOCKET_COANA_MIRROR_URL` to the mirror's https URL. The engine is then downloaded from the mirror, with the same paths and signed query strings as in the bucket. Coana versions that support the variable download their analyzers through it too. - The engine is cached in `$XDG_CACHE_HOME/socket/coana` (`~/.cache/socket/coana` by default). Persist that directory between CI runs to skip the download; with a warm cache, `storage.googleapis.com` is not contacted. **Behind an HTTP(S) proxy**, set `NODE_USE_ENV_PROXY=1` along with `HTTPS_PROXY`. The CLI does not currently route its own requests through `HTTPS_PROXY` or `SOCKET_CLI_API_PROXY`, and fails with `getaddrinfo EAI_AGAIN api.socket.dev`. `NODE_USE_ENV_PROXY=1` (Node.js 22.21 or later) makes Node.js send them through the proxy: @@ -178,7 +176,7 @@ Supports version 2 format with `projectIgnorePaths` for excluding files from rep - `SOCKET_CLI_ORG_SLUG` - Socket organization slug - `SOCKET_CLI_SOCKET_PATCH_PATH` - Path to an executable socket-patch binary for standalone builds - `SOCKET_CLI_VIEW_ALL_RISKS` - Show all npm/npx risks -- `SOCKET_COANA_MIRROR_URL` - https mirror to download the reachability engine from; see [Network access](#network-access) +- `SOCKET_COANA_MIRROR_URL` - https mirror to download the reachability engine from ### See also From 6990e9ebfb566e76e39641bef45cfb03a9300439 Mon Sep 17 00:00:00 2001 From: Oskar Haarklou Veileborg Date: Fri, 4 Dec 2026 11:30:41 +0100 Subject: [PATCH 5/5] fix(coana): check the mirror only when a download is certain Parse SOCKET_COANA_MIRROR_URL and rewrite the signed URL only after the resolved version missed the cache, so a stale value or a URL outside the bucket no longer breaks a run that needs no download. An invalid value is an InputError. Downloads get a 60 s inactivity timeout, so a stalled mirror can't hang the run, and a failed download names the host it went to. --- src/utils/coana-release.test.mts | 86 +++++++++++++++------- src/utils/coana/release.mts | 120 ++++++++++++++++--------------- 2 files changed, 126 insertions(+), 80 deletions(-) diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index f1956cc49..4a4b35bd8 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -330,16 +330,17 @@ describe('spawnCoana', () => { /** * Runs Coana from an empty cache. The Socket API answers with `signedUrls` - * in turn, and downloads with `statuses` in turn, then with the tarball. + * in turn. Downloads fail with `failures` in turn, a status or a thrown + * error, then answer with the tarball. */ async function runFromMirror({ + failures = [], mirrorUrl = MIRROR_URL, signedUrls, - statuses = [], }: { + failures?: Array mirrorUrl?: string signedUrls: string[] - statuses?: number[] }) { vi.stubEnv( 'XDG_CACHE_HOME', @@ -356,8 +357,14 @@ describe('spawnCoana', () => { const download = vi .spyOn(api, 'apiFetch') .mockImplementation(async () => new Response(new Uint8Array(tarball))) - for (const status of statuses) { - download.mockResolvedValueOnce(new Response(null, { status })) + for (const failure of failures) { + if (typeof failure === 'number') { + download.mockResolvedValueOnce( + new Response(null, { status: failure }), + ) + } else { + download.mockRejectedValueOnce(failure) + } } const result = await spawnCoana(['run', '.'], 'acme', { coanaVersion: VERSION, @@ -387,8 +394,8 @@ describe('spawnCoana', () => { it('rewrites the URL it requests anew after the mirror refuses one', async () => { const { downloads, requests, result } = await runFromMirror({ + failures: [403], signedUrls: [signedUrl('first'), signedUrl('second')], - statuses: [403], }) expect(result.ok).toBe(true) @@ -401,8 +408,8 @@ describe('spawnCoana', () => { it("names the mirror's host when a download fails", async () => { const { result } = await runFromMirror({ + failures: [500], signedUrls: [signedUrl('first')], - statuses: [500], }) expect(result).toEqual({ @@ -412,6 +419,39 @@ describe('spawnCoana', () => { }) }) + it("names the mirror's host when it can't be reached, with an idle timeout", async () => { + const { result } = await runFromMirror({ + failures: [new Error('connect ECONNREFUSED 192.0.2.1:443')], + signedUrls: [signedUrl('first')], + }) + + expect(result).toEqual({ + ok: false, + message: `Failed to get the Coana CLI ${VERSION}`, + cause: + 'Downloading from mirror.test failed: connect ECONNREFUSED 192.0.2.1:443', + }) + expect(api.apiFetch).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ timeout: 60_000 }), + ) + }) + + it('ignores an invalid value and a URL outside the bucket when the resolved version is cached', async () => { + vi.stubEnv('SOCKET_COANA_MIRROR_URL', 'http://mirror.test/') + vi.spyOn(api, 'sendApiRequest').mockResolvedValue( + artifactsResponse(VERSION, 'https://example.test/coana.tar.gz'), + ) + const download = vi + .spyOn(api, 'apiFetch') + .mockRejectedValue(new Error('Unexpected download')) + + const run = await runFake({ coanaVersion: '^1.2.0' }) + + expect(run.args).toEqual(['run', '.']) + expect(download).not.toHaveBeenCalled() + }) + it.for([ 'https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz?X-Goog-Signature=secret', 'https://storage.googleapis.com/socket-coana-cli/../another-bucket/objects/SHA.tar.gz?X-Goog-Signature=secret', @@ -424,7 +464,8 @@ describe('spawnCoana', () => { expect(result).toEqual({ ok: false, message: `Failed to get the Coana CLI ${VERSION}`, - cause: `Socket provided the Coana CLI at https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz, outside https://storage.googleapis.com/socket-coana-cli/, which SOCKET_COANA_MIRROR_URL mirrors`, + cause: + 'Socket provided the Coana CLI at https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz, outside https://storage.googleapis.com/socket-coana-cli/, which SOCKET_COANA_MIRROR_URL mirrors.', }) expect(downloads).toEqual([]) }, @@ -438,23 +479,20 @@ describe('spawnCoana', () => { 'https://mirror.test/#secret', 'https://mirror.test/?', 'https://mirror.test/#', - ])( - 'refuses %s before asking Socket, without showing it', - async mirrorUrl => { - const { requests, result } = await runFromMirror({ - mirrorUrl, - signedUrls: [], - }) + ])('refuses %s without showing it', async mirrorUrl => { + const { downloads, result } = await runFromMirror({ + mirrorUrl, + signedUrls: [signedUrl('first')], + }) - expect(result).toEqual({ - ok: false, - message: `Failed to get the Coana CLI ${VERSION}`, - cause: - 'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.', - }) - expect(requests).toBe(0) - }, - ) + expect(result).toEqual({ + ok: false, + message: `Failed to get the Coana CLI ${VERSION}`, + cause: + 'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.', + }) + expect(downloads).toEqual([]) + }) }) it('surfaces captured stdout when stderr is empty (Coana logs some failures to stdout)', async () => { diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index 3d1940a6e..88718319f 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -37,7 +37,7 @@ import { } from '../../sea/runtime.mts' import { apiFetch, sendApiRequest } from '../api.mts' import { debugDir, debugFn } from '../debug.mts' -import { errorMessage } from '../errors.mts' +import { InputError, errorMessage } from '../errors.mts' import { withTmpDir } from '../fs.mts' import { logger } from '../logger.mts' import { @@ -93,6 +93,8 @@ const CACHE_NOT_WRITABLE_EXIT_CODE = 3 // SOCKET_COANA_MIRROR_URL replaces this prefix of the signed URLs. const COANA_BUCKET_URL = 'https://storage.googleapis.com/socket-coana-cli/' const COMPONENT = 'cli' +// Bounds a stalled download without capping a slow one that still progresses. +const DOWNLOAD_IDLE_TIMEOUT_MS = 60_000 const NOT_CACHED_EXIT_CODE = 4 const SHA256_REGEXP = /^[0-9a-f]{64}$/ const TOKEN_VARIABLES: ReadonlySet = new Set([ @@ -171,53 +173,64 @@ 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. + * Stream `component`'s tarball from `url` into `destDir`, checking its size and + * sha256 on the way. The tarball holds only regular files, so anything else is + * dropped. A thrown error names `url`'s host. */ async function downloadComponent( + url: URL, component: CoanaComponent, destDir: string, ): Promise { - const response = await apiFetch(component.url.href, { - headers: { 'User-Agent': getCliUserAgent() }, - }) - if (!response.ok || !response.body) { - await response.body?.cancel() - debugFn('error', `Coana CLI download failed with ${response.status}`) - return { ok: false, status: response.status } + try { + return await receive() + } catch (e) { + throw new Error(`Downloading from ${url.host} failed: ${errorMessage(e)}`) } - const hash = createHash('sha256') - let received = 0 - const body = Readable.from(response.body) - async function* receiveArchive(): AsyncGenerator { - for await (const chunk of body as AsyncIterable) { - received += chunk.length - if (received > component.size) { - throw new Error( - `The Coana CLI tarball is larger than the expected ${component.size} bytes`, - ) + + async function receive(): Promise { + const response = await apiFetch(url.href, { + headers: { 'User-Agent': getCliUserAgent() }, + timeout: DOWNLOAD_IDLE_TIMEOUT_MS, + }) + if (!response.ok || !response.body) { + await response.body?.cancel() + debugFn('error', `Coana CLI download failed with ${response.status}`) + return { ok: false, status: response.status } + } + const hash = createHash('sha256') + let received = 0 + const body = Readable.from(response.body) + async function* receiveArchive(): AsyncGenerator { + for await (const chunk of body as AsyncIterable) { + received += chunk.length + if (received > component.size) { + throw new Error( + `The Coana CLI tarball is larger than the expected ${component.size} bytes`, + ) + } + hash.update(chunk) + yield chunk } - hash.update(chunk) - yield chunk } + await extractTar({ + input: receiveArchive(), + cwd: destDir, + filter: (_path, entry) => + entry.type === 'Directory' || entry.type === 'File', + // Run as root, tar would otherwise give the shared cache the archive's + // owners. + preserveOwner: false, + strict: true, + }) + const sha256 = hash.digest('hex') + if (received !== component.size || sha256 !== component.sha256) { + throw new Error( + `The Coana CLI tarball does not match its checksum (expected ${component.size} bytes with sha256 ${component.sha256}, got ${received} bytes with sha256 ${sha256})`, + ) + } + return { ok: true } } - await extractTar({ - input: receiveArchive(), - cwd: destDir, - filter: (_path, entry) => - entry.type === 'Directory' || entry.type === 'File', - // Run as root, tar would otherwise give the shared cache the archive's - // owners. - preserveOwner: false, - strict: true, - }) - const sha256 = hash.digest('hex') - if (received !== component.size || sha256 !== component.sha256) { - throw new Error( - `The Coana CLI tarball does not match its checksum (expected ${component.size} bytes with sha256 ${component.sha256}, got ${received} bytes with sha256 ${sha256})`, - ) - } - return { ok: true } } type CoanaCliDir = { dir: string; version: string } @@ -252,9 +265,7 @@ async function getCoanaCliDir( } } const orgSlug = org.data - const downloadUrl = parseCoanaMirror(process.env['SOCKET_COANA_MIRROR_URL']) - const request = (spec: string) => - requestArtifacts(spec, orgSlug, downloadUrl) + const request = (spec: string) => requestArtifacts(spec, orgSlug) const artifacts = await request(exactVersion ?? versionSpec) if (!artifacts.ok) { return artifacts @@ -265,6 +276,7 @@ async function getCoanaCliDir( return cached } } + const downloadUrl = parseCoanaMirror(env['SOCKET_COANA_MIRROR_URL']) const downloading = `Downloading the Coana CLI ${artifacts.data.version}...` const spinning = spinner?.isSpinning ? spinner : undefined const previousText = spinning?.text @@ -275,7 +287,7 @@ async function getCoanaCliDir( } try { return withVersion( - await installComponent(artifacts.data, request, env), + await installComponent(artifacts.data, request, downloadUrl, env), artifacts.data.version, ) } finally { @@ -303,11 +315,13 @@ async function getCoanaCliDir( async function installComponent( artifacts: CoanaArtifacts, request: (versionSpec: string) => Promise>, + downloadUrl: CoanaDownloadUrl, env: NodeJS.ProcessEnv, ): Promise> { return await withTmpDir('socket-coana-cli-', async extractDir => { let current = artifacts - let download = await downloadComponent(current.cli, extractDir) + let url = downloadUrl(current.cli.url) + let download = await downloadComponent(url, current.cli, extractDir) // A 4xx means the signed URL expired or was otherwise refused. if (!download.ok && download.status >= 400 && download.status < 500) { // Pin the new request to the resolved version, which a range is not. @@ -316,13 +330,14 @@ async function installComponent( return renewed } current = renewed.data - download = await downloadComponent(current.cli, extractDir) + url = downloadUrl(current.cli.url) + download = await downloadComponent(url, current.cli, extractDir) } if (!download.ok) { return { ok: false, message: `Failed to download the Coana CLI ${current.version}`, - cause: `${current.cli.url.host} responded with status ${download.status}.`, + cause: `${url.host} responded with status ${download.status}.`, } } return cacheResultToCResult( @@ -375,7 +390,7 @@ function parseCoanaMirror(value: string | undefined): CoanaDownloadUrl { // `search` and `hash` are empty for a bare `?` or `#`. if (mirrorUrl?.protocol !== 'https:' || /[?#]/.test(mirrorUrl.href)) { // The value may carry credentials. - throw new Error( + throw new InputError( 'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.', ) } @@ -387,7 +402,7 @@ function parseCoanaMirror(value: string | undefined): CoanaDownloadUrl { if (!href.startsWith(COANA_BUCKET_URL)) { // The query holds the signature. throw new Error( - `Socket provided the Coana CLI at ${origin}${pathname}, outside ${COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors`, + `Socket provided the Coana CLI at ${origin}${pathname}, outside ${COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors.`, ) } return new URL(base + href.slice(COANA_BUCKET_URL.length)) @@ -397,7 +412,6 @@ function parseCoanaMirror(value: string | undefined): CoanaDownloadUrl { async function requestArtifacts( versionSpec: string, orgSlug: string, - downloadUrl: CoanaDownloadUrl, ): Promise> { const result = await sendApiRequest( `orgs/${encodeURIComponent(orgSlug)}/coana-cli/artifacts`, @@ -418,13 +432,7 @@ async function requestArtifacts( cause: `Unexpected response to a request for the Coana CLI ${versionSpec}`, } } - return { - ok: true, - data: { - ...artifacts, - cli: { ...artifacts.cli, url: downloadUrl(artifacts.cli.url) }, - }, - } + return { ok: true, data: artifacts } } /**