wishforge-ide/tests/internal-auth.test.ts
eust-w da1cfcea13 🔥 Remove the cloud IDE
The cluster never ran Theia or the IDE gateway, so every workspace stayed
"未配置" forever. The feature is gone instead of half-present:

- API: workspace, launch and lifecycle endpoints, the gateway identity and
  its internal routes, the dispatcher's workspace provisioning and the
  lifecycle worker. Migration 003 deletes stored workspaces and settles
  their pending outbox items.
- Provisioner: workspace provisioning and lifecycle for both backends.
- Web: the 云 IDE panel, the launch route, the start-branch picker that
  listed IDE branches, and the workspace count on usage.
- apps/ide, infra/oct, dev:ide and the CI job; IDE parts of local k3s,
  network policies, RBAC, docs and the architecture diagram.

A wish can still start from a pushed branch through the API (sourceBranch).
Plan files and stored entitlements may still carry maxWorkspaces; it is
accepted and ignored.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-04 12:43:02 +08:00

105 lines
5.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<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' } });
});
});