import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { Actor, Run } from '@wishforge/contracts'; import { Authenticator } from '../apps/api/src/auth.js'; import { ControlPlane } from '../apps/api/src/domain/control-plane.js'; import { Services } from '../apps/api/src/http.js'; import { ServiceTokens } from '../apps/api/src/service-tokens.js'; import { MemoryStore } from './helpers/memory-store.js'; import { internalFetch } from './helpers/internal-fetch.js'; const env = { NODE_ENV: 'test', WF_DISPATCH_TENANTS: 'alpha', WF_INTERNAL_TOKEN_KEY: 'internal-token-signing-key-for-tests-only', WF_WORKER_TOKEN: 'coordinator-static-token-for-tests-only', WF_VERIFIER_TOKEN: 'retired-static-verifier-token-for-tests', WF_DEPLOYER_TOKEN: 'deployer-static-token-for-tests-only', }; const owner: Actor = { tenantId: 'alpha', userId: 'owner', role: 'owner', kind: 'human' }; let services: Services; let store: MemoryStore; let runId: string; let call: (token: string, route: string, body?: unknown, tenant?: string) => Promise; beforeEach(async () => { store = new MemoryStore(); store.seed('alpha'); store.seed('beta'); services = new Services(new ControlPlane(store, env)); const project = await services.control.createProject(owner, { name: 'Scope' }); runId = ( await services.control.submit( owner, project.id, { goal: 'Scope fixture', acceptanceCriteria: ['It works'], provider: 'codex' }, 'scope-wish-0001', ) ).run_id; const fetcher = internalFetch(services); call = (token, route, body, tenant = 'alpha') => fetcher(`http://127.0.0.1:4000/internal${route}`, { method: body === undefined ? 'GET' : 'POST', headers: { authorization: `Bearer ${token}`, 'x-wishforge-tenant': tenant, 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body), }); }); describe('internal service identities', () => { it('limits the coordinator to state, waits and repairs', async () => { expect((await call(env.WF_WORKER_TOKEN, `/runs/${runId}/state`)).status).toBe(200); for (const [route, body] of [ [`/runs/${runId}/context`, undefined], [`/runs/${runId}/lease`, { workerId: 'coordinator' }], [`/runs/${runId}/transition`, { leaseToken: 1, stage: 'plan', status: 'running', message: 'x' }], ['/evidence', { runId }], ] as const) expect((await call(env.WF_WORKER_TOKEN, route, body)).status).toBe(403); }); it('limits the deployer to leasing a run and requesting its release', async () => { expect((await call(env.WF_DEPLOYER_TOKEN, `/runs/${runId}/context`)).status).toBe(403); expect((await call(env.WF_DEPLOYER_TOKEN, `/runs/${runId}/wait`, { reason: 'deployment' })).status).toBe(403); // Allowed route; the run is waiting, so the lease itself is refused by the domain rules. const lease = await call(env.WF_DEPLOYER_TOKEN, `/runs/${runId}/lease`, { workerId: 'deployer' }); expect(lease.status).toBe(409); expect(await lease.json()).toMatchObject({ error: { code: 'RUN_NOT_RUNNABLE' } }); }); it('accepts no static verifier, foreign tenants or another run’s token', async () => { expect((await call(env.WF_VERIFIER_TOKEN, `/runs/${runId}/state`)).status).toBe(401); expect((await call(env.WF_WORKER_TOKEN, `/runs/${runId}/state`, undefined, 'beta')).status).toBe(403); const scoped = await new ServiceTokens(env.WF_INTERNAL_TOKEN_KEY).issue('alpha', 'another-run', 'worker', 'g1'); expect((await call(scoped, `/runs/${runId}/context`)).status).toBe(401); }); it('retires an execution token once a newer generation is pending, and authenticates without the write lock', async () => { const auth = new Authenticator(store, env); const generation = 'generation-0001'; const set = (change: (run: Run) => void) => store.transaction('alpha', async tx => { const run = (await tx.get('run', runId))!; change(run); await tx.put('run', run); }); // What the dispatcher does when it starts the pending generation. await set(run => { run.status = 'queued'; run.executionGeneration = run.pendingStartId = generation; }); const token = await new ServiceTokens(env.WF_INTERNAL_TOKEN_KEY).issue('alpha', runId, 'worker', generation); const locks = vi.spyOn(store, 'transaction'); expect(await auth.internal(`Bearer ${token}`, 'alpha')).toMatchObject({ runId, credentialId: generation }); await expect(auth.internal(`Bearer ${'x'.repeat(40)}`, 'alpha')).rejects.toMatchObject({ code: 'UNAUTHENTICATED' }); // Neither lookup may hold the tenant's write lock, which serializes every change of the tenant. expect(locks).not.toHaveBeenCalled(); locks.mockRestore(); // Continuing queues the next generation; until the dispatcher starts it, the old one is already gone. await set(run => { run.pendingStartId = 'generation-0002'; }); await expect(auth.internal(`Bearer ${token}`, 'alpha')).rejects.toMatchObject({ code: 'UNAUTHENTICATED' }); }); it('rejects malformed bodies with the API error envelope', async () => { const response = await call(env.WF_DEPLOYER_TOKEN, `/runs/${runId}/lease`, { workerId: '' }); expect(response.status).toBe(400); expect(await response.json()).toMatchObject({ error: { code: 'INVALID_INPUT' } }); }); });