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..344aed052 100644 --- a/README.md +++ b/README.md @@ -176,6 +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 also diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index d672796c5..4a4b35bd8 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,10 +86,28 @@ 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 tarball: Buffer + let tarballSha256: string let tmpDir: string + 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-')), @@ -107,6 +126,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(() => { @@ -130,14 +158,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) @@ -154,22 +174,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', '.']) @@ -315,6 +325,176 @@ describe('spawnCoana', () => { expect(run.args).toEqual(['run', '.']) }) + describe('through SOCKET_COANA_MIRROR_URL', () => { + const MIRROR_URL = 'https://mirror.test/socket-coana-cli' + + /** + * Runs Coana from an empty cache. The Socket API answers with `signedUrls` + * 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, + }: { + failures?: Array + mirrorUrl?: string + signedUrls: string[] + }) { + vi.stubEnv( + 'XDG_CACHE_HOME', + await fs.mkdtemp(path.join(tmpDir, 'mirror-cache-')), + ) + vi.stubEnv('SOCKET_COANA_MIRROR_URL', mirrorUrl) + const request = vi + .spyOn(api, 'sendApiRequest') + .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 () => new Response(new Uint8Array(tarball))) + 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, + stdio: 'pipe', + }) + return { + downloads: download.mock.calls.map(call => call[0]), + requests: request.mock.calls.length, + result, + } + } + + 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({ + failures: [403], + signedUrls: [signedUrl('first'), signedUrl('second')], + }) + + 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({ + failures: [500], + signedUrls: [signedUrl('first')], + }) + + expect(result).toEqual({ + ok: false, + message: `Failed to download the Coana CLI ${VERSION}`, + cause: 'mirror.test responded with status 500.', + }) + }) + + 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', + '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: `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([]) + }, + ) + + 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 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(downloads).toEqual([]) + }) + }) + 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..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 { @@ -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,11 +67,17 @@ 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. Throws when SOCKET_COANA_MIRROR_URL + * is set and the signed URL lies outside the bucket it mirrors. + */ +type CoanaDownloadUrl = (signedUrl: URL) => URL + type CoanaSpawnOptions = { coanaVersion?: string | undefined cwd?: string | URL | undefined @@ -83,7 +90,11 @@ 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' +// 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([ @@ -162,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, { - 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 } @@ -243,10 +265,8 @@ async function getCoanaCliDir( } } const orgSlug = org.data - const artifacts = await requestArtifacts( - exactVersion ?? versionSpec, - orgSlug, - ) + const request = (spec: string) => requestArtifacts(spec, orgSlug) + const artifacts = await request(exactVersion ?? versionSpec) if (!artifacts.ok) { return artifacts } @@ -256,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 @@ -266,7 +287,7 @@ async function getCoanaCliDir( } try { return withVersion( - await installComponent(artifacts.data, orgSlug, env), + await installComponent(artifacts.data, request, downloadUrl, env), artifacts.data.version, ) } finally { @@ -293,27 +314,30 @@ async function getCoanaCliDir( async function installComponent( artifacts: CoanaArtifacts, - orgSlug: string, + 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. - const renewed = await requestArtifacts(current.version, orgSlug) + const renewed = await request(current.version) if (!renewed.ok) { 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: `The download host responded with status ${download.status}.`, + cause: `${url.host} responded with status ${download.status}.`, } } return cacheResultToCResult( @@ -335,6 +359,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) || @@ -343,14 +368,45 @@ 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. + * Throws when the value is invalid. "Downloading through a mirror" in + * 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) { + return signedUrl => signedUrl + } + const mirrorUrl = parseUrl(value) + // `search` and `hash` are empty for a bare `?` or `#`. + if (mirrorUrl?.protocol !== 'https:' || /[?#]/.test(mirrorUrl.href)) { + // The value may carry credentials. + throw new InputError( + 'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.', + ) + } + 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)) { + // 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.`, + ) + } + return new URL(base + href.slice(COANA_BUCKET_URL.length)) + } } async function requestArtifacts(