import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Actor, Project } from '@wishforge/contracts'; import { ControlPlane } from '../apps/api/src/domain/control-plane.js'; import { Services } from '../apps/api/src/http.js'; import { GitStorage } from '../apps/api/src/domain/git-storage.js'; import { MemoryStore } from './helpers/memory-store.js'; import { internalFetch } from './helpers/internal-fetch.js'; // FR-H2: an IDE workspace clones the project and pushes back with a short-lived credential // the gateway asks for on behalf of the person whose session is open. const devUser = '11111111-1111-4111-8111-111111111111'; const env = { NODE_ENV: 'test', WF_DISPATCH_TENANTS: 'demo', WF_INTERNAL_TOKEN_KEY: 'internal-token-signing-key-for-tests-only', WF_WORKER_TOKEN: 'coordinator-static-token-for-tests-only', 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', WF_GIT_SERVICE_URL: 'http://127.0.0.1:4504', WF_GIT_ADMIN_TOKEN: 'git-admin-token-for-tests-only-0001', }; const owner: Actor = { tenantId: 'demo', userId: 'owner', role: 'owner', kind: 'human' }; let store: MemoryStore; let project: Project; let gitCalls: { path: string; body: Record; authorization: string }[]; let call: (route: string, body: unknown, token?: string) => Promise; async function workspaceFor(projectId: string, id: string) { await store.transaction('demo', tx => tx.put('workspace', { id, tenantId: 'demo', version: 1, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), projectId, status: 'ready', upstreamUrl: 'http://127.0.0.1:4300/', }), ); } beforeEach(async () => { gitCalls = []; vi.stubGlobal('fetch', async (input: string | URL, init: RequestInit) => { const url = new URL(String(input)); const body = JSON.parse(String(init.body)); gitCalls.push({ path: url.pathname, body, authorization: (init.headers as Record).Authorization }); if (url.pathname === '/repos') return Response.json({ repositoryUrl: `https://git.test/git/${body.tenantId}/${body.projectId}.git`, initialCommit: 'a'.repeat(40), defaultBranch: 'main', }); return Response.json({ token: 'payload.signature', expiresAt: new Date(Date.now() + 900_000).toISOString() }); }); store = new MemoryStore(); store.seed('demo'); await store.transaction('demo', tx => tx.putMembership({ userId: devUser, role: 'developer', active: true })); const services = new Services(new ControlPlane(store, env)); project = await services.control.createProject(owner, { name: 'Todo App' }); await store.transaction('demo', async tx => { const current = (await tx.get('project', project.id))!; await tx.put('project', { ...current, memberIds: [...current.memberIds, devUser] }); }); await workspaceFor(project.id, 'workspace-1'); const fetcher = internalFetch(services); call = (route, body, token = env.WF_WORKSPACE_GATEWAY_TOKEN) => fetcher(`http://127.0.0.1:4000/internal${route}`, { method: 'POST', headers: { authorization: `Bearer ${token}`, 'x-wishforge-tenant': 'demo', 'content-type': 'application/json' }, body: JSON.stringify(body), }); }); afterEach(() => vi.unstubAllGlobals()); describe('IDE workspace repository access', () => { it('names the session’s author from the sign-in, and only from it', async () => { const first = await call('/workspaces/workspace-1/authorize', { userToken: env.WF_DEV_AUTH_TOKEN, operation: 'edit', }); expect((await first.json()).data.author).toEqual({ name: 'Local Developer', email: 'developer@wishforge.invalid' }); const later = await call('/workspaces/workspace-1/authorize', { userId: devUser, operation: 'edit' }); expect((await later.json()).data.author).toBeUndefined(); }); it('mints a credential that may push ide/ branches of the project’s platform repository', async () => { gitCalls = []; const response = await call('/workspaces/workspace-1/git-credential', { userId: devUser }); expect(response.status).toBe(200); expect((await response.json()).data).toEqual({ projectId: project.id, projectName: 'Todo App', repositoryUrl: `https://git.test/git/demo/${project.id}.git`, branch: 'main', token: 'payload.signature', expiresAt: expect.any(String), }); expect(gitCalls).toEqual([ { path: '/tokens', body: { tenantId: 'demo', projectId: project.id, permission: 'write', ttlSeconds: 900, refPrefix: 'refs/heads/ide/', }, authorization: `Bearer ${env.WF_GIT_ADMIN_TOKEN}`, }, ]); }); it('refuses viewers, revoked members, other identities and malformed requests', async () => { await store.transaction('demo', tx => tx.putMembership({ userId: devUser, role: 'viewer', active: true })); expect((await call('/workspaces/workspace-1/git-credential', { userId: devUser })).status).toBe(403); await store.transaction('demo', tx => tx.putMembership({ userId: devUser, role: 'developer', active: false })); expect((await call('/workspaces/workspace-1/git-credential', { userId: devUser })).status).toBe(403); await store.transaction('demo', tx => tx.putMembership({ userId: devUser, role: 'developer', active: true })); expect( (await call('/workspaces/workspace-1/git-credential', { userId: devUser }, env.WF_WORKER_TOKEN)).status, ).toBe(403); expect((await call('/workspaces/workspace-1/git-credential', { userId: devUser, repositoryUrl: 'x' })).status).toBe( 400, ); expect((await call('/workspaces/missing/git-credential', { userId: devUser })).status).toBe(404); expect(gitCalls.filter(entry => entry.path === '/tokens')).toEqual([]); }); it('does not clone an external repository into the workspace', async () => { const external = await new Services(new ControlPlane(store, env)).control.createProject(owner, { name: 'Imported', repositoryUrl: 'https://github.com/example/imported.git', }); await workspaceFor(external.id, 'workspace-2'); const response = await call('/workspaces/workspace-2/git-credential', { userId: 'owner' }); expect(response.status).toBe(409); expect(await response.json()).toMatchObject({ error: { code: 'WORKSPACE_REPOSITORY_UNSUPPORTED' } }); }); }); describe('wishes that start from an IDE branch', () => { it('lists the ide/ branches people pushed, for platform repositories only', async () => { vi.stubGlobal('fetch', async (input: string | URL, init: RequestInit) => { gitCalls.push({ path: new URL(String(input)).pathname, body: JSON.parse(String(init.body)), authorization: (init.headers as Record).Authorization, }); return Response.json({ branches: [{ name: 'ide/work', commit: 'b'.repeat(40), updatedAt: '2026-10-19T12:00:00+08:00' }], }); }); gitCalls = []; const git = new GitStorage(env); expect(await git.ideBranches(project)).toEqual([ { name: 'ide/work', commit: 'b'.repeat(40), updatedAt: '2026-10-19T12:00:00+08:00' }, ]); expect(gitCalls).toEqual([ { path: '/refs', body: { tenantId: 'demo', projectId: project.id, prefix: 'refs/heads/ide/' }, authorization: `Bearer ${env.WF_GIT_ADMIN_TOKEN}`, }, ]); expect(await git.ideBranches({ ...project, repositoryStorage: 'external' })).toEqual([]); }); it('records the branch on the run and refuses the target branch or the platform’s own branches', async () => { const control = new Services(new ControlPlane(store, env)).control; const submit = (sourceBranch: string, key: string) => control.submit( owner, project.id, { goal: 'Merge the IDE work', acceptanceCriteria: ['Checks pass'], sourceBranch }, key, ); await expect(submit('main', 'source-branch-0001')).rejects.toMatchObject({ code: 'INVALID_SOURCE_BRANCH' }); await expect(submit('wishforge/run/abc', 'source-branch-0002')).rejects.toMatchObject({ code: 'INVALID_SOURCE_BRANCH', }); await expect(submit('../main', 'source-branch-0003')).rejects.toThrow('A safe Git branch name is required'); const { run_id } = await submit('ide/work', 'source-branch-0004'); expect(await control.run(owner, run_id)).toMatchObject({ sourceBranch: 'ide/work' }); }); });