import { expect, test } from 'vitest' import { signLocalExecuteWasmGrant } from '#worker/package-runtime/local-execute-package-wasm-grant.ts' import type { ApiError } from './errors.ts' import { handleLocalExecutePackageWasmRoute } from './local-execute-package-wasm-route.ts' const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) const sha256 = '93a44bbb96c751218e4c00d479e4c14358122a389acca16205b1e4d0dc5f9476' function testEnv(denied: Array = []) { return { SECRET_STORE_KEY: 'test-secret-store-key-0123456789abcdef', PACKAGE_WASM: { get: async () => ({ arrayBuffer: async () => bytes.slice().buffer }), }, BUNDLE_ARTIFACTS_KV: { list: async (options: { prefix?: string }) => ({ keys: denied.map((sha) => ({ name: `${options.prefix ?? ''}${sha}` })), list_complete: true, }), }, } as unknown as Env } async function request(env: Env, token: string | null, sha = sha256) { const url = new URL(`https://kody.test/v1/local-execute/package-wasm/${sha}`) return await handleLocalExecutePackageWasmRoute({ env, url, request: new Request(url, { headers: token ? { 'Kody-Package-Wasm-Grant': token } : {}, }), }) } async function grantFor(env: Env, sha = sha256) { return await signLocalExecuteWasmGrant({ env, sha256: sha, subject: { org: 'org-1', actor: null }, }) } test('a package-graph grant downloads the Wasm bytes it names', async () => { const env = testEnv() const response = await request(env, await grantFor(env)) expect(response.status).toBe(200) expect(response.headers.get('content-type')).toBe('application/wasm') expect(response.headers.get('cache-control')).toBe('private, no-store') expect(new Uint8Array(await response.arrayBuffer())).toEqual(bytes) }) test('a hash alone, or a grant for another hash, does not download Wasm', async () => { const env = testEnv() for (const token of [null, sha256, await grantFor(env, 'f'.repeat(64))]) { await expect(request(env, token)).rejects.toMatchObject({ status: 401, code: 'unauthorized', } satisfies Partial) } }) test('a blocked hash is not served even with a grant', async () => { const env = testEnv([sha256]) await expect(request(env, await grantFor(env))).rejects.toMatchObject({ status: 404, }) })