Skip to content
Draft
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 @@ -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
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down
160 changes: 159 additions & 1 deletion src/utils/coana-release.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
76 changes: 72 additions & 4 deletions src/utils/coana/release.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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}$/
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -294,6 +313,7 @@ async function getCoanaCliDir(
async function installComponent(
artifacts: CoanaArtifacts,
orgSlug: string,
downloadUrl: CoanaDownloadUrl,
env: NodeJS.ProcessEnv,
): Promise<CResult<string>> {
return await withTmpDir('socket-coana-cli-', async extractDir => {
Expand All @@ -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
}
Expand All @@ -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(
Expand Down Expand Up @@ -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<CResult<CoanaArtifacts>> {
const result = await sendApiRequest<unknown>(
`orgs/${encodeURIComponent(orgSlug)}/coana-cli/artifacts`,
Expand All @@ -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 } },
}
}

/**
Expand Down
Loading