272 lines
9.4 KiB
TypeScript
272 lines
9.4 KiB
TypeScript
import { Test } from '@nestjs/testing';
|
|
import { INestApplication } from '@nestjs/common';
|
|
import { PrismaClient } from '@prisma/client';
|
|
import { createHash, randomUUID } from 'crypto';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import { PrepareWorkflowService } from '../orchestration/prepare-workflow.service';
|
|
import { WorkerTransportModule } from './worker-transport.module';
|
|
|
|
(process.env.EDITORIAL_BRIDGE_DB === '1' ? describe : describe.skip)(
|
|
'editorial proposal real TCP boundary',
|
|
() => {
|
|
const db = new PrismaClient();
|
|
const token = 'disposable-pmo-token-'.repeat(3),
|
|
other = 'disposable-other-token-'.repeat(3),
|
|
ci = 'disposable-ci-token-'.repeat(3);
|
|
const digest = (s: string) => createHash('sha256').update(s).digest('hex');
|
|
let app: INestApplication, base: string, workflow: PrepareWorkflowService;
|
|
const config = (enabled = true, withPmo = true) => ({
|
|
enabled,
|
|
grants: [
|
|
...(withPmo
|
|
? [
|
|
{
|
|
id: 'pmo',
|
|
role: 'WORKFLOW_WORKER' as const,
|
|
credentialSha256: digest(token),
|
|
},
|
|
]
|
|
: []),
|
|
{
|
|
id: 'other',
|
|
role: 'WORKFLOW_WORKER' as const,
|
|
credentialSha256: digest(other),
|
|
},
|
|
{ id: 'ci', role: 'STAGE_CI' as const, credentialSha256: digest(ci) },
|
|
],
|
|
workerIds: withPmo ? ['pmo', 'other'] : ['other'],
|
|
stageCiIds: ['ci'],
|
|
artifactDirectory: '/work/tmp/editorial-artifacts',
|
|
artifactBaseUrl:
|
|
'https://isolated.invalid/internal/prepare-worker/artifacts',
|
|
});
|
|
async function start(c = config()) {
|
|
const m = await Test.createTestingModule({
|
|
imports: [WorkerTransportModule.register(c)],
|
|
})
|
|
.overrideProvider(PrismaService)
|
|
.useValue(db)
|
|
.compile();
|
|
const a = m.createNestApplication();
|
|
await a.listen(0, '127.0.0.1');
|
|
return a;
|
|
}
|
|
beforeAll(async () => {
|
|
app = await start();
|
|
base = await app.getUrl();
|
|
workflow = app.get(PrepareWorkflowService);
|
|
});
|
|
afterAll(async () => {
|
|
await app?.close();
|
|
await db.$disconnect();
|
|
});
|
|
const dto = () => ({
|
|
requestId: randomUUID(),
|
|
pilotKind: 'editorial-research-to-brief-v1',
|
|
operationMode: 'PREPARE',
|
|
environment: 'staging',
|
|
scope: 'EDITORIAL_RESEARCH_TO_BRIEF',
|
|
researchTopic: 'Evidence-based senior dog nutrition research',
|
|
acceptanceCriteria: [
|
|
'Cite primary sources with dates',
|
|
'Return a research brief, not a published article',
|
|
],
|
|
commitSha: 'a'.repeat(40),
|
|
budgetLimitCents: 20,
|
|
});
|
|
async function post(body: any, secret = token, url = base) {
|
|
const r = await fetch(
|
|
url + '/internal/prepare-worker/editorial-proposals',
|
|
{
|
|
method: 'POST',
|
|
headers: {
|
|
authorization: 'Bearer ' + secret,
|
|
'content-type': 'application/json',
|
|
},
|
|
body: JSON.stringify(body),
|
|
},
|
|
);
|
|
return { status: r.status, body: await r.json() };
|
|
}
|
|
it('submits immutable owner-reviewable proposal, never approves or dispatches, retries idempotently', async () => {
|
|
const body = dto();
|
|
const r = await post(body);
|
|
expect(r.status).toBe(201);
|
|
expect(r.body).toMatchObject({
|
|
pilotKind: body.pilotKind,
|
|
state: 'GATE1_PENDING',
|
|
operationMode: 'PREPARE',
|
|
department: 'CONTENT',
|
|
budgetLimitCents: 20,
|
|
metadata: {
|
|
environment: 'staging',
|
|
commitSha: body.commitSha,
|
|
acceptanceCriteria: body.acceptanceCriteria,
|
|
},
|
|
});
|
|
const task = await db.orchestrationTask.findUniqueOrThrow({
|
|
where: { id: r.body.taskId },
|
|
});
|
|
expect((task.metadata as any).createdBy).toBe('pmo');
|
|
expect(task.key).toMatch(/^editorial-v1:/);
|
|
expect((await post(body)).body.taskId).toBe(task.id);
|
|
expect(
|
|
await db.orchestrationEvent.count({ where: { taskId: task.id } }),
|
|
).toBe(2);
|
|
for (const model of [
|
|
db.orchestrationApprovalDecision,
|
|
db.orchestrationRun,
|
|
db.prepareWorkflowOutbox,
|
|
db.orchestrationBudgetLedger,
|
|
] as any[])
|
|
expect(await model.count({ where: { taskId: task.id } })).toBe(0);
|
|
expect(
|
|
(await post({ ...body, researchTopic: 'Changed topic' })).status,
|
|
).toBe(409);
|
|
expect((await post({ ...body, commitSha: 'b'.repeat(40) })).status).toBe(
|
|
409,
|
|
);
|
|
await expect(
|
|
workflow.decide(task.id, 1, {}, { id: 'pmo', role: 'Admin' }),
|
|
).rejects.toThrow('Authenticated workflow identity required');
|
|
});
|
|
it('rejects untrusted workers, CI, impersonation, unbounded scope and disabled or absent PMO grants', async () => {
|
|
for (const secret of [other, ci])
|
|
expect((await post(dto(), secret)).status).toBe(403);
|
|
expect((await post(dto(), 'incorrect')).status).toBe(401);
|
|
for (const patch of [
|
|
{ actorId: 'owner' },
|
|
{ role: 'SUPER_ADMIN' },
|
|
{ department: 'ENGINEERING' },
|
|
{ scope: 'arbitrary' },
|
|
{ pilotKind: 'other' },
|
|
{ environment: 'production' },
|
|
{ operationMode: 'RELEASE' },
|
|
{ budgetLimitCents: 21 },
|
|
{ researchTopic: ' ' },
|
|
{ acceptanceCriteria: [' '] },
|
|
{ commitSha: 123 },
|
|
{ acceptanceCriteria: [] },
|
|
{ taskId: randomUUID() },
|
|
])
|
|
expect((await post({ ...dto(), ...patch })).status).toBe(400);
|
|
for (const c of [config(false), config(true, false)]) {
|
|
const isolated = await start(c);
|
|
try {
|
|
const r = await post(dto(), token, await isolated.getUrl());
|
|
expect([401, 403]).toContain(r.status);
|
|
} finally {
|
|
await isolated.close();
|
|
}
|
|
}
|
|
});
|
|
it('races identical requests with one proposal and submission event, and resumes a draft', async () => {
|
|
const body = dto();
|
|
const responses = await Promise.all(
|
|
Array.from({ length: 5 }, () => post(body)),
|
|
);
|
|
expect(responses.map((r) => r.status)).toEqual([201, 201, 201, 201, 201]);
|
|
expect(new Set(responses.map((r) => r.body.taskId)).size).toBe(1);
|
|
expect(
|
|
await db.orchestrationEvent.count({
|
|
where: { taskId: responses[0].body.taskId },
|
|
}),
|
|
).toBe(2);
|
|
const pending = await post(dto());
|
|
const task = await db.orchestrationTask.findUniqueOrThrow({
|
|
where: { id: pending.body.taskId },
|
|
});
|
|
// Interrupted transaction fixture: core create exists but no submission.
|
|
const retry = dto();
|
|
const key =
|
|
'editorial-v1:' + digest(JSON.stringify(['pmo', retry.requestId]));
|
|
const metadata = task.metadata as any;
|
|
await workflow.create(
|
|
{
|
|
key,
|
|
title: task.title,
|
|
department: 'CONTENT',
|
|
operationMode: 'PREPARE',
|
|
budgetLimitCents: 20,
|
|
metadata,
|
|
},
|
|
{ id: 'pmo', role: 'Admin' },
|
|
);
|
|
expect((await post(retry)).body.state).toBe('GATE1_PENDING');
|
|
});
|
|
it('honors kill switches without creating work', async () => {
|
|
const previous = await db.orchestrationKillSwitch.findUnique({
|
|
where: { scope: 'GLOBAL' },
|
|
});
|
|
await db.orchestrationKillSwitch.upsert({
|
|
where: { scope: 'GLOBAL' },
|
|
create: {
|
|
scope: 'GLOBAL',
|
|
level: 'FREEZE_NEW_WORK',
|
|
active: true,
|
|
reason: 'disposable test',
|
|
actorId: 'fixture',
|
|
},
|
|
update: { level: 'FREEZE_NEW_WORK', active: true },
|
|
});
|
|
try {
|
|
expect((await post(dto())).status).toBe(403);
|
|
} finally {
|
|
if (previous)
|
|
await db.orchestrationKillSwitch.update({
|
|
where: { scope: 'GLOBAL' },
|
|
data: { level: previous.level, active: previous.active },
|
|
});
|
|
else
|
|
await db.orchestrationKillSwitch.delete({
|
|
where: { scope: 'GLOBAL' },
|
|
});
|
|
}
|
|
});
|
|
it('never admits an editorial proposal into the deterministic tracer even after real independent Gate1 approval', async () => {
|
|
const created = await post(dto());
|
|
let t = await db.orchestrationTask.findUniqueOrThrow({
|
|
where: { id: created.body.taskId },
|
|
});
|
|
t = await workflow.decide(
|
|
t.id,
|
|
1,
|
|
{
|
|
decision: 'APPROVED',
|
|
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
|
expectedVersion: t.version,
|
|
idempotencyKey: randomUUID(),
|
|
},
|
|
{ id: 'independent-fixture-owner', role: 'SUPER_ADMIN' },
|
|
);
|
|
t = await workflow.transition(
|
|
t.id,
|
|
{
|
|
toState: 'READY',
|
|
expectedVersion: t.version,
|
|
idempotencyKey: randomUUID(),
|
|
},
|
|
{ id: 'pmo', role: 'Admin' },
|
|
);
|
|
const r = await fetch(base + '/internal/prepare-worker/claim', {
|
|
method: 'POST',
|
|
headers: {
|
|
authorization: 'Bearer ' + token,
|
|
'content-type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ taskId: t.id }),
|
|
});
|
|
expect(r.status).toBe(403);
|
|
expect(await db.orchestrationRun.count({ where: { taskId: t.id } })).toBe(
|
|
0,
|
|
);
|
|
expect(
|
|
await db.orchestrationBudgetLedger.count({ where: { taskId: t.id } }),
|
|
).toBe(0);
|
|
expect((await post({ ...dto(), requestId: randomUUID() })).status).toBe(
|
|
201,
|
|
);
|
|
});
|
|
},
|
|
);
|