Skip to content

Commit 1413d21

Browse files
feat(coana): download the Coana CLI through SOCKET_COANA_MIRROR_URL (#1825)
* 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. * 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. * docs(coana): tighten the mirror rewrite comments * docs: drop the Coana mirror paragraph from the README * 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.
1 parent b17b3cf commit 1413d21

4 files changed

Lines changed: 315 additions & 77 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
77
## [Unreleased]
88

99
### Added
10+
- 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.
1011
- 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.
1112
- Scan many repositories with `--dynamic-sbom-inference` without a `socket.json` in each: `--dynamic-sbom-inference-ignore-unresolved` tolerates unresolved dependencies in every build. A build that cannot be loaded, for example over a missing imported Maven BOM, still fails.
1213

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ Supports version 2 format with `projectIgnorePaths` for excluding files from rep
176176
- `SOCKET_CLI_ORG_SLUG` - Socket organization slug
177177
- `SOCKET_CLI_SOCKET_PATCH_PATH` - Path to an executable socket-patch binary for standalone builds
178178
- `SOCKET_CLI_VIEW_ALL_RISKS` - Show all npm/npx risks
179+
- `SOCKET_COANA_MIRROR_URL` - https mirror to download the reachability engine from
179180

180181
### See also
181182

‎src/utils/coana-release.test.mts‎

Lines changed: 203 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
* Test Coverage:
55
* - spawnCoana: runs cli-wrapper.mjs from the cache with the caller's args,
66
* cwd and environment, sets the variables Coana reads, leaves the user's
7-
* API token variables out, and surfaces a failing run's output.
7+
* API token variables out, and surfaces a failing run's output. Downloads
8+
* through the mirror that SOCKET_COANA_MIRROR_URL names.
89
*
910
* Testing Approach:
1011
* A fake cli-wrapper.mjs is installed into a temporary cache with the real
@@ -85,10 +86,28 @@ async function runFake(
8586
return JSON.parse(result.data) as FakeRun
8687
}
8788

89+
function signedUrl(signature: string): string {
90+
return `https://storage.googleapis.com/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=${signature}`
91+
}
92+
8893
describe('spawnCoana', () => {
8994
const savedXdgCacheHome = process.env['XDG_CACHE_HOME']
95+
let tarball: Buffer
96+
let tarballSha256: string
9097
let tmpDir: string
9198

99+
function artifactsResponse(version: string, url: string) {
100+
return {
101+
ok: true as const,
102+
data: {
103+
version,
104+
components: {
105+
cli: { sha256: tarballSha256, size: tarball.length, url },
106+
},
107+
},
108+
}
109+
}
110+
92111
beforeAll(async () => {
93112
tmpDir = await fs.realpath(
94113
await fs.mkdtemp(path.join(os.tmpdir(), 'socket-coana-release-')),
@@ -107,6 +126,15 @@ describe('spawnCoana', () => {
107126
)
108127
}),
109128
)
129+
const fixture = path.join(tmpDir, 'download-fixture')
130+
const archive = path.join(tmpDir, 'coana.tar.gz')
131+
await fs.mkdir(fixture)
132+
await fs.writeFile(coanaCliWrapperPath(fixture), FAKE_CLI_WRAPPER)
133+
await createTar({ cwd: fixture, file: archive, gzip: true }, [
134+
COANA_CLI_WRAPPER_FILENAME,
135+
])
136+
tarball = await fs.readFile(archive)
137+
tarballSha256 = createHash('sha256').update(tarball).digest('hex')
110138
})
111139

112140
afterEach(() => {
@@ -130,14 +158,6 @@ describe('spawnCoana', () => {
130158
})
131159

132160
it('downloads and runs Coana on the first SEA invocation', async () => {
133-
const archive = path.join(tmpDir, 'coana.tar.gz')
134-
const fixture = path.join(tmpDir, 'download-fixture')
135-
await fs.mkdir(fixture)
136-
await fs.writeFile(coanaCliWrapperPath(fixture), FAKE_CLI_WRAPPER)
137-
await createTar({ cwd: fixture, file: archive, gzip: true }, [
138-
COANA_CLI_WRAPPER_FILENAME,
139-
])
140-
const bytes = await fs.readFile(archive)
141161
const version = '1.2.4'
142162
const url = 'https://example.test/coana.tar.gz'
143163
const sea = vi.spyOn(seaRuntime, 'isSea').mockReturnValue(true)
@@ -154,22 +174,12 @@ describe('spawnCoana', () => {
154174
})
155175
return { code: 0, signal: null, stdout: result.stdout }
156176
})
157-
const request = vi.spyOn(api, 'sendApiRequest').mockResolvedValue({
158-
ok: true,
159-
data: {
160-
version,
161-
components: {
162-
cli: {
163-
sha256: createHash('sha256').update(bytes).digest('hex'),
164-
size: bytes.length,
165-
url,
166-
},
167-
},
168-
},
169-
})
177+
const request = vi
178+
.spyOn(api, 'sendApiRequest')
179+
.mockResolvedValue(artifactsResponse(version, url))
170180
const download = vi
171181
.spyOn(api, 'apiFetch')
172-
.mockResolvedValue(new Response(new Uint8Array(bytes)))
182+
.mockResolvedValue(new Response(new Uint8Array(tarball)))
173183
try {
174184
const options = { coanaVersion: version, cwd: tmpDir }
175185
expect((await runFake(options)).args).toEqual(['run', '.'])
@@ -315,6 +325,176 @@ describe('spawnCoana', () => {
315325
expect(run.args).toEqual(['run', '.'])
316326
})
317327

328+
describe('through SOCKET_COANA_MIRROR_URL', () => {
329+
const MIRROR_URL = 'https://mirror.test/socket-coana-cli'
330+
331+
/**
332+
* Runs Coana from an empty cache. The Socket API answers with `signedUrls`
333+
* in turn. Downloads fail with `failures` in turn, a status or a thrown
334+
* error, then answer with the tarball.
335+
*/
336+
async function runFromMirror({
337+
failures = [],
338+
mirrorUrl = MIRROR_URL,
339+
signedUrls,
340+
}: {
341+
failures?: Array<number | Error>
342+
mirrorUrl?: string
343+
signedUrls: string[]
344+
}) {
345+
vi.stubEnv(
346+
'XDG_CACHE_HOME',
347+
await fs.mkdtemp(path.join(tmpDir, 'mirror-cache-')),
348+
)
349+
vi.stubEnv('SOCKET_COANA_MIRROR_URL', mirrorUrl)
350+
const request = vi
351+
.spyOn(api, 'sendApiRequest')
352+
.mockRejectedValue(new Error('Unexpected request'))
353+
for (const url of signedUrls) {
354+
request.mockResolvedValueOnce(artifactsResponse(VERSION, url))
355+
}
356+
// A body can be read only once, so each download gets a new Response.
357+
const download = vi
358+
.spyOn(api, 'apiFetch')
359+
.mockImplementation(async () => new Response(new Uint8Array(tarball)))
360+
for (const failure of failures) {
361+
if (typeof failure === 'number') {
362+
download.mockResolvedValueOnce(
363+
new Response(null, { status: failure }),
364+
)
365+
} else {
366+
download.mockRejectedValueOnce(failure)
367+
}
368+
}
369+
const result = await spawnCoana(['run', '.'], 'acme', {
370+
coanaVersion: VERSION,
371+
stdio: 'pipe',
372+
})
373+
return {
374+
downloads: download.mock.calls.map(call => call[0]),
375+
requests: request.mock.calls.length,
376+
result,
377+
}
378+
}
379+
380+
afterEach(() => {
381+
vi.restoreAllMocks()
382+
})
383+
384+
it("replaces the bucket's prefix with the mirror's URL and keeps the signature", async () => {
385+
const { downloads, result } = await runFromMirror({
386+
signedUrls: [signedUrl('first')],
387+
})
388+
389+
expect(result.ok).toBe(true)
390+
expect(downloads).toEqual([
391+
'https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=first',
392+
])
393+
})
394+
395+
it('rewrites the URL it requests anew after the mirror refuses one', async () => {
396+
const { downloads, requests, result } = await runFromMirror({
397+
failures: [403],
398+
signedUrls: [signedUrl('first'), signedUrl('second')],
399+
})
400+
401+
expect(result.ok).toBe(true)
402+
expect(requests).toBe(2)
403+
expect(downloads).toEqual([
404+
'https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=first',
405+
'https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=second',
406+
])
407+
})
408+
409+
it("names the mirror's host when a download fails", async () => {
410+
const { result } = await runFromMirror({
411+
failures: [500],
412+
signedUrls: [signedUrl('first')],
413+
})
414+
415+
expect(result).toEqual({
416+
ok: false,
417+
message: `Failed to download the Coana CLI ${VERSION}`,
418+
cause: 'mirror.test responded with status 500.',
419+
})
420+
})
421+
422+
it("names the mirror's host when it can't be reached, with an idle timeout", async () => {
423+
const { result } = await runFromMirror({
424+
failures: [new Error('connect ECONNREFUSED 192.0.2.1:443')],
425+
signedUrls: [signedUrl('first')],
426+
})
427+
428+
expect(result).toEqual({
429+
ok: false,
430+
message: `Failed to get the Coana CLI ${VERSION}`,
431+
cause:
432+
'Downloading from mirror.test failed: connect ECONNREFUSED 192.0.2.1:443',
433+
})
434+
expect(api.apiFetch).toHaveBeenCalledWith(
435+
expect.any(String),
436+
expect.objectContaining({ timeout: 60_000 }),
437+
)
438+
})
439+
440+
it('ignores an invalid value and a URL outside the bucket when the resolved version is cached', async () => {
441+
vi.stubEnv('SOCKET_COANA_MIRROR_URL', 'http://mirror.test/')
442+
vi.spyOn(api, 'sendApiRequest').mockResolvedValue(
443+
artifactsResponse(VERSION, 'https://example.test/coana.tar.gz'),
444+
)
445+
const download = vi
446+
.spyOn(api, 'apiFetch')
447+
.mockRejectedValue(new Error('Unexpected download'))
448+
449+
const run = await runFake({ coanaVersion: '^1.2.0' })
450+
451+
expect(run.args).toEqual(['run', '.'])
452+
expect(download).not.toHaveBeenCalled()
453+
})
454+
455+
it.for([
456+
'https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz?X-Goog-Signature=secret',
457+
'https://storage.googleapis.com/socket-coana-cli/../another-bucket/objects/SHA.tar.gz?X-Goog-Signature=secret',
458+
'https://storage.googleapis.com/socket-coana-cli/%2e%2e/another-bucket/objects/SHA.tar.gz?X-Goog-Signature=secret',
459+
])(
460+
'refuses %s, outside the bucket, without showing its signature',
461+
async url => {
462+
const { downloads, result } = await runFromMirror({ signedUrls: [url] })
463+
464+
expect(result).toEqual({
465+
ok: false,
466+
message: `Failed to get the Coana CLI ${VERSION}`,
467+
cause:
468+
'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.',
469+
})
470+
expect(downloads).toEqual([])
471+
},
472+
)
473+
474+
it.for([
475+
'not a URL',
476+
'http://mirror.test/',
477+
'ftp://mirror.test/',
478+
'https://mirror.test/?token=secret',
479+
'https://mirror.test/#secret',
480+
'https://mirror.test/?',
481+
'https://mirror.test/#',
482+
])('refuses %s without showing it', async mirrorUrl => {
483+
const { downloads, result } = await runFromMirror({
484+
mirrorUrl,
485+
signedUrls: [signedUrl('first')],
486+
})
487+
488+
expect(result).toEqual({
489+
ok: false,
490+
message: `Failed to get the Coana CLI ${VERSION}`,
491+
cause:
492+
'SOCKET_COANA_MIRROR_URL must be an https URL without a query or fragment.',
493+
})
494+
expect(downloads).toEqual([])
495+
})
496+
})
497+
318498
it('surfaces captured stdout when stderr is empty (Coana logs some failures to stdout)', async () => {
319499
const result = await spawnCoana(['fail'], 'acme', {
320500
coanaVersion: VERSION,

0 commit comments

Comments
 (0)