- Looking up a run-scoped token or a runner token ran in a write transaction, which holds the tenant's advisory lock: anyone with a long enough token could tie up every change of the tenant, and each executor heartbeat, event and meter took that lock just to authenticate. The lookups now only read. - Continuing or answering a run queues a new generation, but until the dispatcher started it, the old generation's token still worked and could even lease the run again for the new requirement revision. A generation now stops acting as soon as a newer one is pending. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
157 lines
7.9 KiB
TypeScript
157 lines
7.9 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
import type { Actor, Project, 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<Response>;
|
||
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>('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' } });
|
||
});
|
||
});
|
||
|
||
describe('IDE gateway authorization', () => {
|
||
it('starts a session from the user token and rechecks the granted user, seeing revocation', async () => {
|
||
const devUser = '11111111-1111-4111-8111-111111111111';
|
||
const gatewayEnv = {
|
||
...env,
|
||
WF_DISPATCH_TENANTS: 'demo',
|
||
WF_DEV_AUTH_TOKEN: 'development-user-token-for-tests-only',
|
||
WF_WORKSPACE_GATEWAY_BASE: 'http://127.0.0.1:4400',
|
||
WF_WORKSPACE_GATEWAY_TOKEN: 'workspace-gateway-token-for-tests-only',
|
||
WF_WORKSPACE_GATEWAY_TENANT_ID: 'demo',
|
||
};
|
||
const store = new MemoryStore();
|
||
store.seed('demo');
|
||
await store.transaction('demo', tx => tx.putMembership({ userId: devUser, role: 'developer', active: true }));
|
||
const gatewayServices = new Services(new ControlPlane(store, gatewayEnv));
|
||
const demoOwner: Actor = { tenantId: 'demo', userId: 'owner', role: 'owner', kind: 'human' };
|
||
const project = await gatewayServices.control.createProject(demoOwner, { name: 'IDE' });
|
||
await store.transaction('demo', async tx => {
|
||
const current = (await tx.get<Project>('project', project.id))!;
|
||
await tx.put('project', { ...current, memberIds: [...current.memberIds, devUser] });
|
||
await tx.put('workspace', {
|
||
id: 'workspace-1',
|
||
tenantId: 'demo',
|
||
version: 1,
|
||
createdAt: new Date().toISOString(),
|
||
updatedAt: new Date().toISOString(),
|
||
projectId: project.id,
|
||
status: 'ready',
|
||
upstreamUrl: 'http://127.0.0.1:4300/',
|
||
});
|
||
});
|
||
const fetcher = internalFetch(gatewayServices);
|
||
const authorize = (body: unknown) =>
|
||
fetcher('http://127.0.0.1:4000/internal/workspaces/workspace-1/authorize', {
|
||
method: 'POST',
|
||
headers: {
|
||
authorization: `Bearer ${gatewayEnv.WF_WORKSPACE_GATEWAY_TOKEN}`,
|
||
'x-wishforge-tenant': 'demo',
|
||
'content-type': 'application/json',
|
||
},
|
||
body: JSON.stringify(body),
|
||
});
|
||
const first = await authorize({ userToken: gatewayEnv.WF_DEV_AUTH_TOKEN, operation: 'edit' });
|
||
expect(first.status).toBe(200);
|
||
expect((await first.json()).data).toMatchObject({ userId: devUser, role: 'developer', workspaceId: 'workspace-1' });
|
||
expect((await authorize({ userId: devUser, operation: 'terminal' })).status).toBe(200);
|
||
expect((await authorize({ userId: devUser, userToken: 'x', operation: 'edit' })).status).toBe(400);
|
||
await store.transaction('demo', tx => tx.putMembership({ userId: devUser, role: 'developer', active: false }));
|
||
expect((await authorize({ userId: devUser, operation: 'edit' })).status).toBe(403);
|
||
});
|
||
});
|