Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59d79a6f32 |
No files matched your search
@@ -0,0 +1,15 @@
|
||||
-- A server-issued attestation is persisted atomically with a DONE transition.
|
||||
CREATE TABLE "task_completion_attestations" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"artifact_type" VARCHAR(20) NOT NULL,
|
||||
"artifact_id" UUID NOT NULL,
|
||||
"artifact_url" VARCHAR(255) NOT NULL,
|
||||
"verifier" VARCHAR(50) NOT NULL,
|
||||
"verified_at" TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT "task_completion_attestations_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "task_completion_attestations_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "department_tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "task_completion_attestations_artifact_type_check" CHECK ("artifact_type" = 'BLOG'),
|
||||
CONSTRAINT "task_completion_attestations_verifier_check" CHECK ("verifier" = 'SERVER_ARTIFACT_VERIFIER')
|
||||
);
|
||||
CREATE INDEX "task_completion_attestations_task_id_idx" ON "task_completion_attestations"("task_id");
|
||||
@@ -1067,7 +1067,22 @@ model AuditLog {
|
||||
// ------------------------------------------------------------------------------
|
||||
// 7. DepartmentTask (Autonomous Corporate Task & Kanban Manager)
|
||||
// ------------------------------------------------------------------------------
|
||||
model TaskCompletionAttestation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
artifactType String @map("artifact_type") @db.VarChar(20)
|
||||
artifactId String @map("artifact_id") @db.Uuid
|
||||
artifactUrl String @map("artifact_url") @db.VarChar(255)
|
||||
verifier String @db.VarChar(50)
|
||||
verifiedAt DateTime @map("verified_at") @db.Timestamptz()
|
||||
task DepartmentTask @relation(fields: [taskId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([taskId])
|
||||
@@map("task_completion_attestations")
|
||||
}
|
||||
|
||||
model DepartmentTask {
|
||||
completionAttestations TaskCompletionAttestation[]
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique @db.VarChar(50)
|
||||
department String @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
|
||||
|
||||
@@ -32,14 +32,25 @@ describe("department task completion policy", () => {
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("allows completion with URL, criteria and QA evidence", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).not.toThrow();
|
||||
it("does not trust caller-spoofable QA evidence even with URL and criteria", () => {
|
||||
expect(() => assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
})).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("requires matching server-issued artifact identity", () => {
|
||||
expect(() => assertTaskCanComplete({
|
||||
id: "task-1", deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
attestation: { taskId: "task-1", artifactType: "BLOG", artifactId: "blog-1", artifactUrl: "https://canina.ir/blog/verified", verifier: "SERVER_ARTIFACT_VERIFIER" },
|
||||
})).not.toThrow();
|
||||
expect(() => assertTaskCanComplete({
|
||||
id: "task-2", deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
attestation: { taskId: "task-1", artifactType: "BLOG", artifactId: "blog-1", artifactUrl: "https://canina.ir/blog/verified", verifier: "SERVER_ARTIFACT_VERIFIER" },
|
||||
})).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects pseudo-protocol canina:// deliverable URLs", () => {
|
||||
|
||||
@@ -6,6 +6,8 @@ export interface CompletableTask {
|
||||
deliverableUrl?: string | null;
|
||||
acceptanceCriteria?: unknown;
|
||||
executionLogs?: unknown;
|
||||
id?: string;
|
||||
attestation?: { taskId: string; artifactType: string; artifactId: string; artifactUrl: string; verifier: string };
|
||||
}
|
||||
|
||||
function hasAcceptanceCriteria(criteria: unknown): boolean {
|
||||
@@ -20,35 +22,6 @@ function hasAcceptanceCriteria(criteria: unknown): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasValidQaEvidence(logs: unknown): boolean {
|
||||
if (!Array.isArray(logs)) return false;
|
||||
const validPassStatuses = ["QA_PASSED", "VERIFIED", "PRODUCTION_VERIFIED"];
|
||||
|
||||
let foundValidPass = false;
|
||||
for (const log of logs) {
|
||||
if (!log || typeof log !== "object") continue;
|
||||
const entry = log as Record<string, unknown>;
|
||||
const status = String(entry.status || "").toUpperCase();
|
||||
const note = String(entry.note || "").toLowerCase();
|
||||
|
||||
// Rejection of invalid QA claims: 404, missing article, not found, post-tsk
|
||||
if (
|
||||
note.includes("404") ||
|
||||
note.includes("مقاله یافت نشد") ||
|
||||
note.includes("not found") ||
|
||||
note.includes("missing article") ||
|
||||
note.includes("post-tsk")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (validPassStatuses.includes(status)) {
|
||||
foundValidPass = true;
|
||||
}
|
||||
}
|
||||
return foundValidPass;
|
||||
}
|
||||
|
||||
export function assertTaskCanComplete(task: CompletableTask): void {
|
||||
const rawUrl = task.deliverableUrl?.trim();
|
||||
if (!rawUrl) {
|
||||
@@ -87,7 +60,11 @@ export function assertTaskCanComplete(task: CompletableTask): void {
|
||||
throw new BadRequestException("DONE requires explicit acceptance criteria");
|
||||
}
|
||||
|
||||
if (!hasValidQaEvidence(task.executionLogs)) {
|
||||
throw new BadRequestException("DONE requires QA/production verification evidence");
|
||||
const evidence = task.attestation;
|
||||
if (!task.id || !evidence || evidence.taskId !== task.id ||
|
||||
evidence.verifier !== "SERVER_ARTIFACT_VERIFIER" ||
|
||||
evidence.artifactType !== "BLOG" || !evidence.artifactId ||
|
||||
evidence.artifactUrl !== rawUrl) {
|
||||
throw new BadRequestException("DONE requires a matching server-verified artifact attestation");
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,10 @@ import { PrismaService } from "../prisma/prisma.service";
|
||||
describe("DepartmentTasksController", () => {
|
||||
let controller: DepartmentTasksController;
|
||||
let prisma: {
|
||||
taskCompletionAttestation: { create: jest.Mock };
|
||||
blog: { findUnique: jest.Mock };
|
||||
product: { findUnique: jest.Mock };
|
||||
$transaction: jest.Mock;
|
||||
departmentTask: {
|
||||
findUnique: jest.Mock;
|
||||
findMany: jest.Mock;
|
||||
@@ -21,6 +25,10 @@ describe("DepartmentTasksController", () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
prisma = {
|
||||
taskCompletionAttestation: { create: jest.fn() },
|
||||
blog: { findUnique: jest.fn() },
|
||||
product: { findUnique: jest.fn() },
|
||||
$transaction: jest.fn(async (callback) => callback(prisma)),
|
||||
departmentTask: {
|
||||
findUnique: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
@@ -47,6 +55,70 @@ describe("DepartmentTasksController", () => {
|
||||
controller = module.get<DepartmentTasksController>(DepartmentTasksController);
|
||||
});
|
||||
|
||||
describe("trusted completion authorization", () => {
|
||||
const validTask = {
|
||||
id: "task-105", code: "TSK-100105", title: "Published blog", status: "TEST",
|
||||
acceptanceCriteria: { criteria: ["Published blog"] }, executionLogs: [{ status: "QA_PASSED" }],
|
||||
deliverableUrl: "https://canina.ir/blog/cat-food-nutrition",
|
||||
};
|
||||
|
||||
it("cannot create a DONE task even with caller-supplied QA logs", async () => {
|
||||
await expect(controller.create({ department: "content", title: "fake", status: "DONE", executionLogs: [{ status: "QA_PASSED" }] }))
|
||||
.rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects unknown statuses at creation and transition", async () => {
|
||||
await expect(controller.create({ department: "content", title: "fake", status: "DONE " })).rejects.toThrow(BadRequestException);
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
await expect(controller.updateStatus(validTask.id, { status: "COMPLETE" })).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects spoofed historical QA and requires independent verification", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue(null);
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE" })).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
expect(prisma.taskCompletionAttestation.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects arbitrary hosts and changed deliverables before lookup", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE", deliverableUrl: "https://evil.example/blog/cat-food-nutrition" }))
|
||||
.rejects.toThrow(BadRequestException);
|
||||
expect(prisma.blog.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unpublished artifact", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "cat-food-nutrition", status: "DRAFT", isPublished: false });
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE" })).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not write DONE if attestation persistence fails", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "cat-food-nutrition", status: "PUBLISHED", isPublished: true });
|
||||
prisma.taskCompletionAttestation.create.mockRejectedValue(new Error("attestation store unavailable"));
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE" })).rejects.toThrow("attestation store unavailable");
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("persists a server-verifier attestation bound to the task and artifact before DONE", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "cat-food-nutrition", status: "PUBLISHED", isPublished: true });
|
||||
prisma.departmentTask.update.mockResolvedValue({ ...validTask, status: "DONE" });
|
||||
await controller.updateStatus(validTask.id, { status: "DONE", logNote: "QA_PASSED" });
|
||||
expect(prisma.taskCompletionAttestation.create).toHaveBeenCalledWith({ data: expect.objectContaining({
|
||||
taskId: validTask.id, artifactType: "BLOG", artifactId: "blog-1", artifactUrl: validTask.deliverableUrl,
|
||||
verifier: "SERVER_ARTIFACT_VERIFIER", verifiedAt: expect.any(Date),
|
||||
}) });
|
||||
expect(prisma.$transaction).toHaveBeenCalled();
|
||||
expect(prisma.departmentTask.update).toHaveBeenCalledWith({ where: { id: validTask.id }, data: expect.objectContaining({ status: "DONE" }) });
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateStatus - verifiable completion guards", () => {
|
||||
it("rejects completion with pseudo-protocol canina://", async () => {
|
||||
const taskId = "task-101";
|
||||
@@ -140,6 +212,7 @@ describe("DepartmentTasksController", () => {
|
||||
deliverableUrl: "https://canina.ir/blog/cat-food-nutrition",
|
||||
};
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(existingTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-2", slug: "cat-food-nutrition", status: "PUBLISHED", isPublished: true });
|
||||
prisma.departmentTask.update.mockResolvedValue({
|
||||
...existingTask,
|
||||
status: "DONE",
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
import { assertTaskCanComplete } from "./department-task-completion.policy";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
@@ -23,6 +24,16 @@ import { PrismaService } from "../prisma/prisma.service";
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/department-tasks")
|
||||
export class DepartmentTasksController {
|
||||
private readonly allowedStatuses = new Set([
|
||||
"BACKLOG", "TODO", "IN_PROGRESS", "TEST", "IN_REVIEW", "APPROVED", "DEPLOYING", "DONE",
|
||||
]);
|
||||
|
||||
private assertStatus(status: unknown): void {
|
||||
if (typeof status !== "string" || !this.allowedStatuses.has(status)) {
|
||||
throw new BadRequestException("Unknown task status");
|
||||
}
|
||||
}
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@@ -113,6 +124,9 @@ export class DepartmentTasksController {
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
|
||||
async create(@Body() body: any) {
|
||||
this.assertStatus(body.status || "TODO");
|
||||
// Creation cannot attest its own work; require an existing task for verification.
|
||||
if (body.status === "DONE") throw new BadRequestException("Create task before completing it");
|
||||
const code = body.code || "TSK-" + Date.now().toString().slice(-6);
|
||||
const task = await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
@@ -155,6 +169,7 @@ export class DepartmentTasksController {
|
||||
where: { id },
|
||||
});
|
||||
if (!existing) throw new NotFoundException(`Task ${id} not found`);
|
||||
this.assertStatus(body.status);
|
||||
|
||||
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
|
||||
if (body.logNote) {
|
||||
@@ -166,13 +181,33 @@ export class DepartmentTasksController {
|
||||
}
|
||||
|
||||
const candidateDeliverableUrl = body.deliverableUrl || existing.deliverableUrl;
|
||||
let attestation: { taskId: string; artifactType: string; artifactId: string; artifactUrl: string; verifier: string; verifiedAt: Date } | undefined;
|
||||
if (body.status === "DONE") {
|
||||
// Only a canonical first-party blog URL is an eligible identity. Never fetch
|
||||
// arbitrary caller URLs (SSRF), or accept claims in executionLogs as proof.
|
||||
let url: URL;
|
||||
try { url = new URL(candidateDeliverableUrl); }
|
||||
catch { throw new BadRequestException("DONE requires a canonical published blog URL"); }
|
||||
const match = /^\/blog\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.exec(url.pathname);
|
||||
if (url.protocol !== "https:" || url.hostname !== "canina.ir" ||
|
||||
url.port || url.username || url.password || url.search || url.hash || !match ||
|
||||
/^post-tsk(?:-|$)/.test(match[1])) {
|
||||
throw new BadRequestException("DONE requires a canonical published blog URL");
|
||||
}
|
||||
const blog = await (this.prisma as any).blog.findUnique({ where: { slug: match[1] } });
|
||||
if (!blog || blog.status !== "PUBLISHED" || blog.isPublished !== true) {
|
||||
throw new BadRequestException("DONE requires an independently verified published artifact");
|
||||
}
|
||||
attestation = {
|
||||
taskId: id, artifactType: "BLOG", artifactId: blog.id,
|
||||
artifactUrl: candidateDeliverableUrl, verifier: "SERVER_ARTIFACT_VERIFIER",
|
||||
verifiedAt: new Date(),
|
||||
};
|
||||
assertTaskCanComplete({
|
||||
code: existing.code,
|
||||
title: existing.title,
|
||||
id, code: existing.code, title: existing.title,
|
||||
deliverableUrl: candidateDeliverableUrl,
|
||||
acceptanceCriteria: existing.acceptanceCriteria,
|
||||
executionLogs: logs,
|
||||
attestation,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -187,10 +222,13 @@ export class DepartmentTasksController {
|
||||
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
|
||||
}
|
||||
|
||||
const updated = await (this.prisma as any).departmentTask.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
const updated = attestation
|
||||
? await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
// Persist attestation and transition together: no DONE without its record.
|
||||
await tx.taskCompletionAttestation.create({ data: attestation });
|
||||
return tx.departmentTask.update({ where: { id }, data: updateData });
|
||||
})
|
||||
: await (this.prisma as any).departmentTask.update({ where: { id }, data: updateData });
|
||||
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
|
||||
Reference in new issue
Block a user