Files
canina/backend/src/orchestration/prepare-workflow.http.spec.ts
T
2026-10-24 10:58:18 +00:00

186 lines
6.7 KiB
TypeScript

import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { OrchestrationController } from './orchestration.controller';
import { OrchestrationService } from './orchestration.service';
import { PrepareWorkflowService } from './prepare-workflow.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
describe('bounded workflow HTTP contracts', () => {
let app: INestApplication;
const t = {
id: 't',
key: 'k',
state: 'DRAFT',
version: 1,
metadata: {
scope: 'STAGE_PREPARE',
environment: 'staging',
commitSha: 'a'.repeat(40),
token: 'secret',
},
};
const workflow = {
editorialRecovery: jest.fn(async () => undefined as undefined | {runId:string}),
create: jest.fn(async () => t),
transition: jest.fn(async () => t),
decide: jest.fn(async () => t),
project: jest.fn((row: any) => ({
...row,
metadata: {
scope: 'STAGE_PREPARE',
environment: 'staging',
commitSha: 'a'.repeat(40),
},
availableActions: ['SUBMIT_GATE1'],
})),
};
const core = {
findAll: async () => [t],
findOne: async () => t,
command: jest.fn(),
};
beforeAll(async () => {
const m = await Test.createTestingModule({
controllers: [OrchestrationController],
providers: [
{ provide: OrchestrationService, useValue: core },
{ provide: PrepareWorkflowService, useValue: workflow },
RolesGuard,
],
})
.overrideGuard(JwtAuthGuard)
.useValue({
canActivate(c: any) {
const req = c.switchToHttp().getRequest();
if (!req.headers.authorization) return false;
req.user = {
sub: 'verified-subject',
role: req.headers.authorization,
};
return true;
},
})
.compile();
app = m.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
it.each([
['ADMIN', 'Admin'],
['admin', 'Admin'],
['Admin', 'Admin'],
['SUPER_ADMIN', 'SUPER_ADMIN'],
['super-admin', 'SUPER_ADMIN'],
['SuperAdmin', 'SUPER_ADMIN'],
['ADMIN_SUPER', 'SUPER_ADMIN'],
])('canonicalizes guard-supported %s on task reads to %s', async (role, canonical) => {
for (const path of ['tasks', 'tasks/t']) {
workflow.project.mockClear();
const response = await request(app.getHttpServer())
.get('/admin/orchestration/' + path)
.set('Authorization', role)
.expect(200);
expect(workflow.project).toHaveBeenCalledWith(t, {
id: 'verified-subject', role: canonical,
});
const task = Array.isArray(response.body) ? response.body[0] : response.body;
expect(task.availableActions).toEqual(['SUBMIT_GATE1']);
}
});
it('adds only the safe recovery hint to detail, never the list', async () => {
workflow.editorialRecovery.mockResolvedValueOnce({runId:'registered-run'});
const detail=await request(app.getHttpServer()).get('/admin/orchestration/tasks/t').set('Authorization','SUPER_ADMIN').expect(200);
expect(detail.body.editorialRecovery).toEqual({runId:'registered-run'});
expect(workflow.editorialRecovery).toHaveBeenCalledWith(t,{id:'verified-subject',role:'SUPER_ADMIN'});
const list=await request(app.getHttpServer()).get('/admin/orchestration/tasks').set('Authorization','SUPER_ADMIN').expect(200);
expect(list.body[0].editorialRecovery).toBeUndefined();
expect(JSON.stringify(detail.body)).not.toContain('secret');
});
it('denies ordinary users before workflow projection', async () => {
workflow.project.mockClear();
for (const path of ['tasks', 'tasks/t', 'overview']) {
await request(app.getHttpServer())
.get('/admin/orchestration/' + path)
.set('Authorization', 'User_PetOwner')
.expect(403);
}
expect(workflow.project).not.toHaveBeenCalled();
});
it('accepts existing proposal DTO, derives actor from JWT sub and returns projected task', async () => {
const dto = {
key: 'k',
title: 'T',
department: 'ENGINEERING',
operationMode: 'PREPARE',
budgetLimitCents: 20,
metadata: {
commitSha: 'a'.repeat(40),
scope: 'Staging audit only',
acceptanceCriteria: ['QA passes'],
},
};
const r = await request(app.getHttpServer())
.post('/admin/orchestration/tasks')
.set('Authorization', 'Admin')
.send(dto)
.expect(201);
expect(workflow.create).toHaveBeenCalledWith(dto, {
id: 'verified-subject',
role: 'Admin',
});
expect(r.body.availableActions).toEqual(['SUBMIT_GATE1']);
expect(JSON.stringify(r.body)).not.toMatch(/token|secret/);
await request(app.getHttpServer())
.post('/admin/orchestration/tasks')
.set('Authorization', 'Admin')
.send({ ...dto, actorId: 'browser' })
.expect(400);
});
it('routes fixed transition/gate contracts and rejects invalid gates plus release without invoking core', async () => {
await request(app.getHttpServer())
.put('/admin/orchestration/tasks/t/transition')
.set('Authorization', 'Admin')
.send({
toState: 'GATE1_PENDING',
expectedVersion: 1,
idempotencyKey: 'submit',
})
.expect(200);
await request(app.getHttpServer())
.put('/admin/orchestration/tasks/t/transition')
.set('Authorization', 'SUPER_ADMIN')
.send({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'Review sources'})
.expect(200);
expect(workflow.transition).toHaveBeenCalledWith('t', expect.objectContaining({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'Review sources'}), {id:'verified-subject',role:'SUPER_ADMIN'});
await request(app.getHttpServer())
.post('/admin/orchestration/tasks/t/gates/1/decide')
.set('Authorization', 'SUPER_ADMIN')
.send({
decision: 'APPROVED',
expectedVersion: 2,
idempotencyKey: 'approval',
expiresAt: new Date(Date.now() + 60000).toISOString(),
})
.expect(201);
expect(workflow.decide).toHaveBeenCalledWith('t', 1, expect.any(Object), {
id: 'verified-subject',
role: 'SUPER_ADMIN',
});
await request(app.getHttpServer())
.post('/admin/orchestration/tasks/t/gates/2/decide')
.set('Authorization', 'SUPER_ADMIN')
.send({})
.expect(403);
await request(app.getHttpServer())
.post('/admin/orchestration/tasks/t/commands/RELEASE_AUTHORIZE')
.set('Authorization', 'SUPER_ADMIN')
.send({})
.expect(403);
expect(core.command).not.toHaveBeenCalled();
});
});