Harden integration read-only boundaries and admin contracts

This commit is contained in:
devops committed 2026-10-23 06:38:39 +00:00
1 parent ac065fa911
commit 841eab0556
21 files changed
+179 -687

No files matched your search

+23 -269
View File
@@ -1,271 +1,25 @@
import { Test, TestingModule } from "@nestjs/testing";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { ApprovalsController } from "./approvals.controller";
import { PrismaService } from "../prisma/prisma.service";
import { GoneException } from '@nestjs/common';
import { ApprovalsController } from './approvals.controller';
import { PrismaService } from '../prisma/prisma.service';
describe("ApprovalsController", () => {
let controller: ApprovalsController;
let prisma: {
approvalRequest: {
findUnique: jest.Mock;
findMany: jest.Mock;
count: jest.Mock;
create: jest.Mock;
update: jest.Mock;
delete: jest.Mock;
};
departmentTask: {
findFirst: jest.Mock;
findMany: jest.Mock;
create: jest.Mock;
update: jest.Mock;
deleteMany: jest.Mock;
updateMany: jest.Mock;
};
};
beforeEach(async () => {
prisma = {
approvalRequest: {
findUnique: jest.fn(),
findMany: jest.fn(),
count: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
departmentTask: {
findFirst: jest.fn(),
findMany: jest.fn(),
create: jest.fn(),
update: jest.fn(),
deleteMany: jest.fn(),
updateMany: jest.fn(),
},
};
const module: TestingModule = await Test.createTestingModule({
controllers: [ApprovalsController],
providers: [
{
provide: PrismaService,
useValue: prisma,
},
],
}).compile();
controller = module.get<ApprovalsController>(ApprovalsController);
});
describe("decide - B2B_SUPPLIER_STRATEGY approval separation", () => {
it("B2B_SUPPLIER_STRATEGY approval must not create digital task nor set executedAt as physical action", async () => {
const approvalId = "b2b-strategy-uuid-1";
const approvalItem = {
id: approvalId,
department: "B2B",
category: "B2B_SUPPLIER_STRATEGY",
title: "[طرح استراتژیک تامین‌کننده] توسعه شبکه کلینیکی آلمان",
payload: { target: "German Suppliers", tier: "Direct" },
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
ceoNotes: "موافقت با مذاکره اولیه",
});
prisma.departmentTask.findFirst.mockResolvedValue(null);
const result = await controller.decide(approvalId, {
decision: "APPROVED",
ceoNotes: "موافقت با مذاکره اولیه",
});
expect(result.success).toBe(true);
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
where: { id: approvalId },
data: expect.objectContaining({
status: "APPROVED",
ceoNotes: "موافقت با مذاکره اولیه",
}),
});
// Verify executedAt is NOT set as physical action
const updateCall = prisma.approvalRequest.update.mock.calls[0][0];
expect(updateCall.data.executedAt).toBeUndefined();
// Verify NO digital task is created in departmentTask queue
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
});
it("B2B_SUPPLIER_STRATEGY approval must not requeue existing digital task", async () => {
const approvalId = "b2b-strategy-uuid-2";
const approvalItem = {
id: approvalId,
department: "B2B",
category: "B2B_SUPPLIER_STRATEGY",
title: "[طرح استراتژیک تامین‌کننده] پکیج نمونه دارویی",
payload: {},
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
});
prisma.departmentTask.findFirst.mockResolvedValue({
id: "task-existing-1",
status: "BACKLOG",
title: "Legacy task",
});
const result = await controller.decide(approvalId, {
decision: "APPROVED",
});
expect(result.success).toBe(true);
// Ensure existing task was NOT updated or requeued to TODO
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
});
});
describe("decide - SEO approval actionable digital task", () => {
it("SEO approval creates actionable digital task in TODO", async () => {
const approvalId = "seo-approval-uuid-1";
const approvalItem = {
id: approvalId,
department: "SEO",
category: "SEO",
title: "بهینه‌سازی متاتگ‌های صفحات دسته‌بندی گربه",
payload: { targetUrl: "/category/cat-food" },
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
ceoNotes: "در اولویت سئو قرار گیرد",
});
prisma.departmentTask.findFirst.mockResolvedValue(null);
prisma.departmentTask.create.mockResolvedValue({
id: "new-task-uuid",
code: "TSK-892110",
department: "SEO",
title: approvalItem.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: approvalId,
});
const result = await controller.decide(approvalId, {
decision: "APPROVED",
ceoNotes: "در اولویت سئو قرار گیرد",
});
expect(result.success).toBe(true);
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
where: { id: approvalId },
data: expect.objectContaining({
status: "APPROVED",
ceoNotes: "در اولویت سئو قرار گیرد",
}),
});
// Digital task MUST be created with status TODO
expect(prisma.departmentTask.create).toHaveBeenCalledWith({
data: expect.objectContaining({
department: "SEO",
title: approvalItem.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: approvalId,
}),
});
});
it("SEO approval requeues existing task to TODO when existing task found", async () => {
const approvalId = "seo-approval-uuid-2";
const approvalItem = {
id: approvalId,
department: "SEO",
category: "SEO",
title: "بررسی کنیبان سئو مقاله تغذیه سگ",
payload: {},
status: "PENDING",
};
const existingTask = {
id: "existing-task-99",
code: "TSK-112233",
status: "IN_REVIEW",
description: "Initial draft",
approvalId: approvalId,
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
ceoNotes: "تایید نهایی جهت اقدام",
});
prisma.departmentTask.findFirst.mockResolvedValue(existingTask);
prisma.departmentTask.update.mockResolvedValue({
...existingTask,
status: "TODO",
});
const result = await controller.decide(approvalId, {
decision: "APPROVED",
ceoNotes: "تایید نهایی جهت اقدام",
});
expect(result.success).toBe(true);
expect(prisma.departmentTask.update).toHaveBeenCalledWith({
where: { id: existingTask.id },
data: expect.objectContaining({
status: "TODO",
}),
});
});
});
describe("decide - rejection handling", () => {
it("handles REJECTED decision cleanly without deleting approval audit history", async () => {
const approvalId = "approval-reject-uuid";
const approvalItem = {
id: approvalId,
department: "SEO",
category: "SEO",
title: "تغییر ساختار URL",
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "REJECTED",
ceoNotes: "ریسک بالای افت رتبه سئو",
});
const result = await controller.decide(approvalId, {
decision: "REJECTED",
ceoNotes: "ریسک بالای افت رتبه سئو",
});
expect(result.success).toBe(true);
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
where: { id: approvalId },
data: expect.objectContaining({
status: "REJECTED",
ceoNotes: "ریسک بالای افت رتبه سئو",
}),
});
});
});
describe('ApprovalsController retired mutation boundary',()=>{
const access=jest.fn();
const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}});
const controller=new ApprovalsController(prisma as PrismaService);
beforeEach(()=>access.mockClear());
it('create {department:SEO,category:SEO,title:Legacy,payload:{}} returns 410 without reading or writing persistence',async()=>{
await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toBeInstanceOf(GoneException);
await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toMatchObject({status:410});
expect(access).not.toHaveBeenCalled();
});
it('decide missing, {decision:APPROVED} returns 410 without reading or writing persistence',async()=>{
await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toBeInstanceOf(GoneException);
await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toMatchObject({status:410});
expect(access).not.toHaveBeenCalled();
});
it('decide missing, {decision:REJECTED} returns 410 without reading or writing persistence',async()=>{
await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toBeInstanceOf(GoneException);
await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toMatchObject({status:410});
expect(access).not.toHaveBeenCalled();
});
});
+3 -126
View File
@@ -8,7 +8,7 @@ import {
Query,
UseGuards,
NotFoundException,
BadRequestException,
GoneException,
} from "@nestjs/common";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
@@ -82,17 +82,7 @@ export class ApprovalsController {
@Post()
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمان‌ها)" })
async create(@Body() dto: CreateApprovalRequestDto) {
const item = await (this.prisma as any).approvalRequest.create({
data: {
department: dto.department,
category: dto.category,
title: dto.title,
payload: dto.payload,
testContext: dto.testContext || {},
status: "PENDING",
},
});
return { success: true, data: item };
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
}
@Post(":id/test")
@@ -138,120 +128,7 @@ export class ApprovalsController {
@Put(":id/decide")
@ApiOperation({ summary: "تصمیم‌گیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
if (!["APPROVED", "REJECTED"].includes(dto.decision)) {
throw new BadRequestException("Decision must be either APPROVED or REJECTED");
}
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
if (dto.decision === "REJECTED") {
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: {
status: "REJECTED",
ceoNotes: dto.ceoNotes || null,
},
});
if ((this.prisma as any).departmentTask?.updateMany) {
await (this.prisma as any).departmentTask.updateMany({
where: { approvalId: id },
data: { status: "REJECTED" },
});
}
return {
success: true,
message: "درخواست رد شد و در سوابق ممیزی ثبت گردید.",
data: updated,
};
}
// تفکیک اقدامات استراتژیک تامین‌کننده/مدیریتی از کارهای دیجیتال سایت
const isStrategicSupplierAction =
item.category === "B2B_SUPPLIER_STRATEGY" ||
item.category === "PARTNERSHIP" ||
(item.department === "B2B" && String(item.category || "").includes("STRATEGY"));
if (isStrategicSupplierAction) {
// طرح‌های B2B_SUPPLIER_STRATEGY منحصراً در سوابق مدیریتی تایید می‌شوند.
// هیچ تسک دیجیتالی ایجاد یا بازگشایی نمی‌شود و executedAt فیزیکی ثبت نمی‌گردد.
const updateData: any = {
status: "APPROVED",
ceoNotes: dto.ceoNotes || null,
};
if (dto.outcome || dto.evidence) {
const payload = typeof item.payload === "object" && item.payload !== null
? { ...(item.payload as Record<string, any>) }
: {};
if (dto.outcome) payload.outcome = dto.outcome;
if (dto.evidence) payload.evidence = dto.evidence;
updateData.payload = payload;
}
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: updateData,
});
return {
success: true,
message: "طرح استراتژیک تامین‌کننده تایید گردید و در سوابق مدیریتی ثبت شد.",
data: updated,
};
}
// کارهای دیجیتال (مانند SEO، محتوا، قیمت‌گذاری و فنی)
// تایید مجوز اجرای کار دیجیتال است و تسک متناظر را در صف TODO قرار می‌دهد
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: {
status: "APPROVED",
ceoNotes: dto.ceoNotes || null,
},
});
// جستجو یا ایجاد تسک متناظر با استاتوس TODO
const existingTask = await (this.prisma as any).departmentTask.findFirst({
where: { approvalId: id },
});
if (existingTask) {
await (this.prisma as any).departmentTask.update({
where: { id: existingTask.id },
data: {
status: "TODO",
description: dto.ceoNotes
? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes
: existingTask.description,
},
});
} else {
await (this.prisma as any).departmentTask.create({
data: {
code: "TSK-" + Date.now().toString().slice(-6),
department: item.department || "SEO",
title: item.title,
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: item.id,
},
});
}
return {
success: true,
message: "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید.",
data: updated,
};
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
}
}
@@ -1,163 +1,25 @@
import { Test, TestingModule } from "@nestjs/testing";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { DepartmentTasksController } from "./department-tasks.controller";
import { PrismaService } from "../prisma/prisma.service";
import { GoneException } from '@nestjs/common';
import { DepartmentTasksController } from './department-tasks.controller';
import { PrismaService } from '../prisma/prisma.service';
describe("DepartmentTasksController", () => {
let controller: DepartmentTasksController;
let prisma: {
departmentTask: {
findUnique: jest.Mock;
findMany: jest.Mock;
count: jest.Mock;
create: jest.Mock;
update: jest.Mock;
delete: jest.Mock;
};
auditLog: {
create: jest.Mock;
};
};
beforeEach(async () => {
prisma = {
departmentTask: {
findUnique: jest.fn(),
findMany: jest.fn(),
count: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
auditLog: {
create: jest.fn().mockResolvedValue({ id: "audit-1" }),
},
};
const module: TestingModule = await Test.createTestingModule({
controllers: [DepartmentTasksController],
providers: [
{
provide: PrismaService,
useValue: prisma,
},
],
}).compile();
controller = module.get<DepartmentTasksController>(DepartmentTasksController);
});
describe("updateStatus - verifiable completion guards", () => {
it("rejects completion with pseudo-protocol canina://", async () => {
const taskId = "task-101";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100101",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [{ status: "QA_PASSED" }],
deliverableUrl: null,
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
deliverableUrl: "canina://blog/fake-article",
}),
).rejects.toThrow(BadRequestException);
});
it("rejects completion with git://stage repository reference", async () => {
const taskId = "task-102";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100102",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [{ status: "QA_PASSED" }],
deliverableUrl: null,
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
deliverableUrl: "git://stage/canina-repo#commit-xyz",
}),
).rejects.toThrow(BadRequestException);
});
it("rejects completion with post-tsk placeholder article", async () => {
const taskId = "task-103";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100103",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [{ status: "QA_PASSED" }],
deliverableUrl: null,
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
deliverableUrl: "https://canina.ir/blog/post-tsk-998877",
}),
).rejects.toThrow(BadRequestException);
});
it("rejects completion when QA log reports missing article / 404", async () => {
const taskId = "task-104";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100104",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [],
deliverableUrl: "https://canina.ir/blog/real-article",
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
logNote: "QA_PASSED but received 404 - مقاله یافت نشد",
}),
).rejects.toThrow(BadRequestException);
});
it("allows completion with valid HTTPS deliverable URL and verified QA evidence", async () => {
const taskId = "task-105";
const existingTask = {
id: taskId,
code: "TSK-100105",
title: "Optimized Cat Food Landing",
status: "TEST",
acceptanceCriteria: { criteria: ["HTTP 200", "Lighthouse > 90"] },
executionLogs: [{ status: "PRODUCTION_VERIFIED", note: "Live 200 verified on production" }],
deliverableUrl: "https://canina.ir/blog/cat-food-nutrition",
};
prisma.departmentTask.findUnique.mockResolvedValue(existingTask);
prisma.departmentTask.update.mockResolvedValue({
...existingTask,
status: "DONE",
completedAt: new Date(),
});
const res = await controller.updateStatus(taskId, {
status: "DONE",
});
expect(res.success).toBe(true);
expect(prisma.departmentTask.update).toHaveBeenCalledWith({
where: { id: taskId },
data: expect.objectContaining({
status: "DONE",
completedAt: expect.any(Date),
}),
});
});
});
describe('DepartmentTasksController retired mutation boundary',()=>{
const access=jest.fn();
const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}});
const controller=new DepartmentTasksController(prisma as PrismaService);
beforeEach(()=>access.mockClear());
it('create {department:SEO,title:Legacy} returns 410 without reading or writing persistence',async()=>{
await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toBeInstanceOf(GoneException);
await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toMatchObject({status:410});
expect(access).not.toHaveBeenCalled();
});
it('updateStatus missing, {status:DONE} returns 410 without reading or writing persistence',async()=>{
await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toBeInstanceOf(GoneException);
await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toMatchObject({status:410});
expect(access).not.toHaveBeenCalled();
});
it('updateStatus missing, {status:TODO} returns 410 without reading or writing persistence',async()=>{
await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toBeInstanceOf(GoneException);
await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toMatchObject({status:410});
expect(access).not.toHaveBeenCalled();
});
});
@@ -8,8 +8,8 @@ import {
Query,
UseGuards,
NotFoundException,
GoneException,
} from "@nestjs/common";
import { assertTaskCanComplete } from "./department-task-completion.policy";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
@@ -112,36 +112,7 @@ export class DepartmentTasksController {
@Post()
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
async create(@Body() body: any) {
const code = body.code || "TSK-" + Date.now().toString().slice(-6);
const task = await (this.prisma as any).departmentTask.create({
data: {
code,
department: body.department,
title: body.title,
description: body.description || null,
status: body.status || "TODO",
priority: body.priority || "MEDIUM",
assignee: body.assignee || "AI_AGENT",
acceptanceCriteria: body.acceptanceCriteria || null,
executionLogs: body.executionLogs || [],
deliverableUrl: body.deliverableUrl || null,
startedAt: body.status === "IN_PROGRESS" ? new Date() : null,
},
});
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
entityId: task.id,
action: "CREATE",
department: task.department,
actor: task.assignee || "SYSTEM",
summary: "تسک جدید " + task.code + " (" + task.title + ") ایجاد شد.",
newValues: task,
},
});
return { success: true, data: task };
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
}
@Put(":id/status")
@@ -150,61 +121,7 @@ export class DepartmentTasksController {
@Param("id") id: string,
@Body() body: { status: string; logNote?: string; deliverableUrl?: string }
) {
const existing = await (this.prisma as any).departmentTask.findUnique({
where: { id },
});
if (!existing) throw new NotFoundException(`Task ${id} not found`);
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
if (body.logNote) {
logs.push({
timestamp: new Date().toISOString(),
status: body.status,
note: body.logNote,
});
}
const candidateDeliverableUrl = body.deliverableUrl || existing.deliverableUrl;
if (body.status === "DONE") {
assertTaskCanComplete({
code: existing.code,
title: existing.title,
deliverableUrl: candidateDeliverableUrl,
acceptanceCriteria: existing.acceptanceCriteria,
executionLogs: logs,
});
}
const updateData: any = {
status: body.status,
executionLogs: logs,
};
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
if (body.status === "DONE") updateData.completedAt = new Date();
if (body.status === "TODO" && body.logNote) {
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
}
const updated = await (this.prisma as any).departmentTask.update({
where: { id },
data: updateData,
});
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
entityId: updated.id,
action: "UPDATE",
department: updated.department,
actor: "SYSTEM",
summary: "وضعیت تسک " + updated.code + " به " + body.status + " تغییر یافت.",
oldValues: { status: existing.status },
newValues: { status: updated.status, note: body.logNote },
},
});
return { success: true, data: updated };
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
}
}
@@ -0,0 +1,52 @@
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { ApprovalsController } from './approvals.controller';
import { DepartmentTasksController } from './department-tasks.controller';
import { PrismaService } from '../prisma/prisma.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
describe('retired legacy orchestration HTTP boundary', () => {
let app: INestApplication;
const dbAccess = jest.fn();
const prisma = new Proxy({}, {get: (_target, key) => {
// Nest inspects provider thenables and lifecycle hooks during setup.
if (["then", "onModuleInit", "onApplicationBootstrap", "onModuleDestroy", "beforeApplicationShutdown", "onApplicationShutdown"].includes(String(key))) return undefined;
dbAccess(key);
throw new Error('Persistence must not be accessed');
}});
const routes = [
['post', '/admin/approvals'],
['put', '/admin/approvals/missing/decide'],
['post', '/admin/department-tasks'],
['put', '/admin/department-tasks/missing/status'],
] as const;
beforeAll(async () => {
const module = await Test.createTestingModule({
controllers: [ApprovalsController, DepartmentTasksController],
providers: [{provide: PrismaService, useValue: prisma}, RolesGuard],
}).overrideGuard(JwtAuthGuard).useValue({canActivate(context: any) {
const req = context.switchToHttp().getRequest();
if (!req.headers.authorization) return false;
req.user = {id: 'test-admin', role: req.headers.authorization};
return true;
}}).compile();
app = module.createNestApplication();
await app.init();
dbAccess.mockClear();
});
beforeEach(() => dbAccess.mockClear());
afterAll(async () => app?.close());
it.each(routes)('%s %s returns explicit 410 for authorized callers before database access', async (method, path) => {
const response = await request(app.getHttpServer())[method](path)
.set('Authorization', 'Admin').send({decision:'APPROVED',status:'DONE'}).expect(410);
expect(response.body.message).toContain('retired');
expect(dbAccess).not.toHaveBeenCalled();
});
it.each(routes)('%s %s retains anonymous and customer authorization guards', async (method, path) => {
await request(app.getHttpServer())[method](path).send({}).expect(403);
await request(app.getHttpServer())[method](path).set('Authorization','CUSTOMER').send({}).expect(403);
expect(dbAccess).not.toHaveBeenCalled();
});
});