import { personIdFromStored } from '@kody-internal/shared/owner-person-ids.ts' import { DatabaseSync } from 'node:sqlite' import { quoteSqlString } from '@kody-internal/shared/sql-literals.ts' import { expect, test, vi } from 'vitest' import { createMcpCallerContext } from '#mcp/context.ts' import { assertWorkerModulesWasmAllowed, hydrateWasmModuleRecords, writeWasmModuleRecord, } from '#worker/package-runtime/package-wasm-modules.ts' import { sha256Hex } from '#worker/publish-offload/module-hashes.ts' import { applyAllMigrations } from '#worker/test-support/apply-all-migrations.ts' import { createD1FromSqlite } from '#worker/test-support/create-d1-from-sqlite.ts' import { createMemoryKvNamespace } from '#worker/test-support/memory-kv.ts' import { testStableUserIdFromEmail } from '#worker/test-support/stable-user-id.ts' import { denyPackageWasmSha256s, loadPackageWasmDeniedSha256s, packageWasmDenylistKvPrefix, } from '#worker/package-runtime/package-wasm-denylist.ts' import { adminPackageWasmAllowCapability, adminPackageWasmDenyCapability, adminPackageWasmDenylistCapability, } from './admin-package-wasm-denylist.ts' function createContext(roles: Array, env: Env) { const stableUserId = testStableUserIdFromEmail('admin@example.com') return { env, callerContext: createMcpCallerContext({ source: { kind: 'mcp-oauth' }, baseUrl: 'https://example.com', user: { userId: personIdFromStored(stableUserId), email: 'admin@example.com', displayName: 'admin', roles, }, }), } } test('a denied Wasm sha256 stops publish writes and running modules until it is allowed again', async () => { const sqlite = new DatabaseSync(':memory:') applyAllMigrations( sqlite, new URL('../../../../migrations/', import.meta.url), ) sqlite.exec(` INSERT INTO users (username, email, stable_user_id, password_hash) VALUES ('opslead', 'admin@example.com', ${quoteSqlString( testStableUserIdFromEmail('admin@example.com'), )}, 'hash'); `) const env = { APP_DB: createD1FromSqlite(sqlite), BUNDLE_ARTIFACTS_KV: createMemoryKvNamespace().kv, } as Env const bytes = new Uint8Array([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]).buffer const sha256 = await sha256Hex(bytes) const stored: Parameters[0]['records'] = {} await writeWasmModuleRecord({ env, bytes, records: stored }) const hydrate = () => hydrateWasmModuleRecords({ env, records: stored, shas: [sha256], readArtifactRecords: async () => null, }) expect((await hydrate()).get(sha256)?.byteLength).toBe(8) await expect( adminPackageWasmDenyCapability.handler( { sha256s: [sha256], reason: 'malware' }, createContext(['user'], env), ), ).rejects.toThrow('lacks required role "admin"') const adminCtx = createContext(['admin'], env) const denied = await adminPackageWasmDenyCapability.handler( { sha256s: [sha256], reason: 'malware' }, adminCtx, ) expect(denied.added).toEqual([sha256]) expect(denied.denylist).toEqual([ expect.objectContaining({ sha256, reason: 'malware' }), ]) // Storage reads still work so a replacement publish can load the old version. expect((await hydrate()).get(sha256)?.byteLength).toBe(8) const warmModules = { 'index.js': 'export default {}', [`.__kody_wasm__/${sha256}.wasm`]: { wasm: bytes }, } await expect( assertWorkerModulesWasmAllowed(env, warmModules), ).rejects.toThrow(`Package Wasm module ${sha256} is blocked.`) await expect( writeWasmModuleRecord({ env, bytes, records: {} }), ).rejects.toThrow('is blocked') const allowed = await adminPackageWasmAllowCapability.handler( { sha256s: [sha256] }, adminCtx, ) expect(allowed.removed).toEqual([sha256]) expect(allowed.restored).toEqual([ expect.objectContaining({ sha256, reason: 'malware' }), ]) expect( (await adminPackageWasmDenylistCapability.handler({}, adminCtx)).denylist, ).toEqual([]) expect((await hydrate()).get(sha256)?.byteLength).toBe(8) await assertWorkerModulesWasmAllowed(env, warmModules) }) test('a deny that reads a stale list keeps entries written elsewhere', async () => { const { kv, store } = createMemoryKvNamespace() const earlier = 'a'.repeat(64) store.set( `${packageWasmDenylistKvPrefix}${earlier}`, JSON.stringify({ sha256: earlier, reason: 'first', deniedAt: '2026-11-28T00:00:00.000Z', deniedBy: 'admin', }), ) const staleKv = { ...kv, get: kv.get.bind(kv), put: kv.put.bind(kv), delete: kv.delete.bind(kv), list: async () => ({ keys: [], list_complete: true, cacheStatus: null }), } as unknown as KVNamespace await denyPackageWasmSha256s({ env: { BUNDLE_ARTIFACTS_KV: staleKv }, sha256s: ['b'.repeat(64)], reason: 'second', deniedBy: 'admin', }) expect([...store.keys()].sort()).toEqual([ `${packageWasmDenylistKvPrefix}${earlier}`, `${packageWasmDenylistKvPrefix}${'b'.repeat(64)}`, ]) }) test('runtime denylist checks read key names only', async () => { const { kv } = createMemoryKvNamespace() const env = { BUNDLE_ARTIFACTS_KV: kv } const sha256 = 'c'.repeat(64) await denyPackageWasmSha256s({ env, sha256s: [sha256], reason: 'malware', deniedBy: 'admin', }) const get = vi.spyOn(kv, 'get') expect(await loadPackageWasmDeniedSha256s(env)).toEqual(new Set([sha256])) expect(get).not.toHaveBeenCalled() })