Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
226 changes: 203 additions & 23 deletions 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,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-')),
Expand All @@ -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(() => {
Expand All @@ -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)
Expand All @@ -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', '.'])
Expand Down Expand Up @@ -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<number | Error>
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,
Expand Down
Loading
Loading