690417:1538 Refactor Work flow ADR-021
This commit is contained in:
@@ -0,0 +1,328 @@
|
||||
// File: src/modules/workflow-engine/guards/workflow-transition.guard.spec.ts
|
||||
// Unit tests for WorkflowTransitionGuard - T030
|
||||
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import {
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||
import { WorkflowTransitionGuard } from './workflow-transition.guard';
|
||||
import { WorkflowInstance } from '../entities/workflow-instance.entity';
|
||||
import { UserService } from '../../../modules/user/user.service';
|
||||
import type { RequestWithUser } from '../../../common/interfaces/request-with-user.interface';
|
||||
|
||||
type MockUserPayload = {
|
||||
user_id: number;
|
||||
email: string;
|
||||
primaryOrganizationId: number | null;
|
||||
} | null;
|
||||
|
||||
describe('WorkflowTransitionGuard', () => {
|
||||
let guard: WorkflowTransitionGuard;
|
||||
let instanceRepo: { findOne: jest.Mock };
|
||||
let userService: { getUserPermissions: jest.Mock };
|
||||
let dataSource: { query: jest.Mock };
|
||||
|
||||
const mockUser = {
|
||||
user_id: 123,
|
||||
email: 'test@example.com',
|
||||
primaryOrganizationId: 1,
|
||||
};
|
||||
|
||||
const mockRequest = (
|
||||
params: Record<string, string> = {},
|
||||
user: MockUserPayload = mockUser
|
||||
): Partial<RequestWithUser> => ({
|
||||
params,
|
||||
user: user as RequestWithUser['user'],
|
||||
});
|
||||
|
||||
const mockContext = (req: Partial<RequestWithUser>): ExecutionContext =>
|
||||
({
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => req,
|
||||
}),
|
||||
}) as ExecutionContext;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
WorkflowTransitionGuard,
|
||||
{
|
||||
provide: getRepositoryToken(WorkflowInstance),
|
||||
useValue: {
|
||||
findOne: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: UserService,
|
||||
useValue: {
|
||||
getUserPermissions: jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: DataSource,
|
||||
useValue: {
|
||||
query: jest.fn(),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
guard = module.get<WorkflowTransitionGuard>(WorkflowTransitionGuard);
|
||||
instanceRepo = module.get(getRepositoryToken(WorkflowInstance));
|
||||
userService = module.get(UserService);
|
||||
dataSource = module.get(DataSource);
|
||||
|
||||
instanceRepo.findOne = jest.fn();
|
||||
userService.getUserPermissions = jest.fn();
|
||||
dataSource.query = jest.fn();
|
||||
});
|
||||
|
||||
describe('Level 1: Superadmin', () => {
|
||||
it('should allow access for user with system.manage_all permission', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue(['system.manage_all']);
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }));
|
||||
|
||||
// Act
|
||||
const result = await guard.canActivate(context);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
expect(userService.getUserPermissions).toHaveBeenCalledWith(123);
|
||||
expect(instanceRepo.findOne).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Level 2: Org Admin', () => {
|
||||
it('should allow access for org admin with same organization as document', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue([
|
||||
'organization.manage_users',
|
||||
]);
|
||||
const mockInstance = {
|
||||
id: 'instance-123',
|
||||
context: { organizationId: 1 },
|
||||
contractId: null,
|
||||
};
|
||||
instanceRepo.findOne.mockResolvedValue(mockInstance);
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }));
|
||||
|
||||
// Act
|
||||
const result = await guard.canActivate(context);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
expect(userService.getUserPermissions).toHaveBeenCalledWith(123);
|
||||
expect(instanceRepo.findOne).toHaveBeenCalledWith({
|
||||
where: { id: 'instance-123' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should deny access for org admin from different organization', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue([
|
||||
'organization.manage_users',
|
||||
]);
|
||||
const mockInstance = {
|
||||
id: 'instance-123',
|
||||
context: { organizationId: 2 }, // Different org
|
||||
contractId: null,
|
||||
};
|
||||
instanceRepo.findOne.mockResolvedValue(mockInstance);
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }));
|
||||
|
||||
// Act & Assert
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
ForbiddenException
|
||||
);
|
||||
});
|
||||
|
||||
it('should deny access for org admin when document has no organization', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue([
|
||||
'organization.manage_users',
|
||||
]);
|
||||
const mockInstance = {
|
||||
id: 'instance-123',
|
||||
context: { organizationId: undefined },
|
||||
contractId: null,
|
||||
};
|
||||
instanceRepo.findOne.mockResolvedValue(mockInstance);
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }));
|
||||
|
||||
// Act & Assert
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
ForbiddenException
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Level 2.5: Contract Membership', () => {
|
||||
it('should allow access for user in same contract as document AND assigned as handler', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue(['document.view']); // No special permissions
|
||||
const mockInstance = {
|
||||
id: 'instance-123',
|
||||
context: {
|
||||
organizationId: 2, // Different org from user
|
||||
assignedUserId: 123, // This user is assigned
|
||||
},
|
||||
contractId: 42, // Has contract
|
||||
};
|
||||
instanceRepo.findOne.mockResolvedValue(mockInstance);
|
||||
dataSource.query.mockResolvedValue([{ cnt: '1' }]); // User org in contract
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }));
|
||||
|
||||
// Act
|
||||
const result = await guard.canActivate(context);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
expect(dataSource.query).toHaveBeenCalledWith(
|
||||
'SELECT COUNT(*) AS cnt FROM contract_organizations WHERE contract_id = ? AND organization_id = ?',
|
||||
[42, 1]
|
||||
);
|
||||
});
|
||||
|
||||
it('should deny access for user not in contract (cross-contract block)', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue(['document.view']);
|
||||
const mockInstance = {
|
||||
id: 'instance-123',
|
||||
context: { organizationId: 1 },
|
||||
contractId: 42,
|
||||
};
|
||||
instanceRepo.findOne.mockResolvedValue(mockInstance);
|
||||
dataSource.query.mockResolvedValue([{ cnt: '0' }]); // User org NOT in contract
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }));
|
||||
|
||||
// Act & Assert
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
ForbiddenException
|
||||
);
|
||||
expect(dataSource.query).toHaveBeenCalledWith(
|
||||
'SELECT COUNT(*) AS cnt FROM contract_organizations WHERE contract_id = ? AND organization_id = ?',
|
||||
[42, 1]
|
||||
);
|
||||
});
|
||||
|
||||
it('should deny access for user without primary organization when contract is present', async () => {
|
||||
// Arrange
|
||||
const userWithoutOrg = { ...mockUser, primaryOrganizationId: null };
|
||||
userService.getUserPermissions.mockResolvedValue(['document.view']);
|
||||
const mockInstance = {
|
||||
id: 'instance-123',
|
||||
context: { organizationId: 1 },
|
||||
contractId: 42,
|
||||
};
|
||||
instanceRepo.findOne.mockResolvedValue(mockInstance);
|
||||
const context = mockContext(
|
||||
mockRequest({ id: 'instance-123' }, userWithoutOrg)
|
||||
);
|
||||
|
||||
// Act & Assert
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
ForbiddenException
|
||||
);
|
||||
expect(dataSource.query).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Level 3: Assigned Handler', () => {
|
||||
it('should allow access for user assigned as handler', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue(['document.view']);
|
||||
const mockInstance = {
|
||||
id: 'instance-123',
|
||||
context: {
|
||||
organizationId: 2, // Different org
|
||||
assignedUserId: 123, // This user is assigned
|
||||
},
|
||||
contractId: null,
|
||||
};
|
||||
instanceRepo.findOne.mockResolvedValue(mockInstance);
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }));
|
||||
|
||||
// Act
|
||||
const result = await guard.canActivate(context);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should deny access for different assigned user', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue(['document.view']);
|
||||
const mockInstance = {
|
||||
id: 'instance-123',
|
||||
context: {
|
||||
organizationId: 2,
|
||||
assignedUserId: 456, // Different user assigned
|
||||
},
|
||||
contractId: null,
|
||||
};
|
||||
instanceRepo.findOne.mockResolvedValue(mockInstance);
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }));
|
||||
|
||||
// Act & Assert
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
ForbiddenException
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Level 4: Unauthorized Users', () => {
|
||||
it('should deny access for regular users without any special permissions', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue(['document.view']); // Basic permission only
|
||||
const mockInstance = {
|
||||
id: 'instance-123',
|
||||
context: { organizationId: 2 }, // Different org
|
||||
contractId: null,
|
||||
};
|
||||
instanceRepo.findOne.mockResolvedValue(mockInstance);
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }));
|
||||
|
||||
// Act & Assert
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
ForbiddenException
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
it('should throw NotFoundException when workflow instance does not exist', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue(['document.view']);
|
||||
instanceRepo.findOne.mockResolvedValue(null);
|
||||
const context = mockContext(mockRequest({ id: 'non-existent' }));
|
||||
|
||||
// Act & Assert
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
NotFoundException
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle missing user in request', async () => {
|
||||
// Arrange
|
||||
const context = mockContext(mockRequest({ id: 'instance-123' }, null));
|
||||
|
||||
// Act & Assert
|
||||
await expect(guard.canActivate(context)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('should handle missing instanceId in params', async () => {
|
||||
// Arrange
|
||||
userService.getUserPermissions.mockResolvedValue(['document.view']);
|
||||
const context = mockContext(mockRequest({})); // No id param
|
||||
|
||||
// Act & Assert
|
||||
await expect(guard.canActivate(context)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { WorkflowInstance } from '../entities/workflow-instance.entity';
|
||||
import { UserService } from '../../../modules/user/user.service';
|
||||
import type { RequestWithUser } from '../../../common/interfaces/request-with-user.interface';
|
||||
@@ -18,10 +18,12 @@ import type { RequestWithUser } from '../../../common/interfaces/request-with-us
|
||||
/**
|
||||
* WorkflowTransitionGuard — ตรวจสอบสิทธิ์ 4 ระดับก่อนอนุญาตให้เปลี่ยนสถานะ Workflow
|
||||
*
|
||||
* Level 1: system.manage_all (Superadmin) → ผ่านทันที
|
||||
* Level 2: organization.manage_users + สังกัดองค์กรเดียวกับเอกสาร → ผ่าน
|
||||
* Level 3: Assigned Handler (context.assignedUserId === req.user.user_id) → ผ่าน
|
||||
* Level 4: ผู้ใช้ทั่วไป → ForbiddenException
|
||||
* Level 1: system.manage_all (Superadmin) → ผ่านทันที
|
||||
* Level 2: organization.manage_users + สังกัดองค์กรเดียวกับเอกสาร → ผ่าน
|
||||
* Level 2.5: [C3] contract_organizations membership — ถ้า instance.contractId ถูกตั้ง
|
||||
* และ User ไม่อยู่ใน contract นั้น → ForbiddenException (cross-contract block)
|
||||
* Level 3: Assigned Handler (context.assignedUserId === req.user.user_id) → ผ่าน
|
||||
* Level 4: ผู้ใช้ทั่วไป → ForbiddenException
|
||||
*/
|
||||
@Injectable()
|
||||
export class WorkflowTransitionGuard implements CanActivate {
|
||||
@@ -30,7 +32,8 @@ export class WorkflowTransitionGuard implements CanActivate {
|
||||
constructor(
|
||||
@InjectRepository(WorkflowInstance)
|
||||
private readonly instanceRepo: Repository<WorkflowInstance>,
|
||||
private readonly userService: UserService
|
||||
private readonly userService: UserService,
|
||||
private readonly dataSource: DataSource
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
@@ -67,6 +70,35 @@ export class WorkflowTransitionGuard implements CanActivate {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Level 2.5: [C3] Contract Membership check — ถ้า instance ผูกกับ contract ใด
|
||||
// User ต้องสังกัดองค์กรที่อยู่ใน contract นั้น ป้องกัน cross-contract access
|
||||
if (instance.contractId !== null && instance.contractId !== undefined) {
|
||||
const userOrgId = user.primaryOrganizationId;
|
||||
if (!userOrgId) {
|
||||
this.logger.warn(
|
||||
`No org for User ${user.user_id} attempting contract-scoped workflow ${instanceId}`
|
||||
);
|
||||
throw new ForbiddenException({
|
||||
userMessage:
|
||||
'คุณไม่ได้สังกัดองค์กรใด ไม่สามารถดำเนินการในสัญญานี้ได้',
|
||||
recoveryAction: 'ติดต่อ Admin เพื่อกำหนดองค์กร',
|
||||
});
|
||||
}
|
||||
const rows = await this.dataSource.query<[{ cnt: string }]>(
|
||||
'SELECT COUNT(*) AS cnt FROM contract_organizations WHERE contract_id = ? AND organization_id = ?',
|
||||
[instance.contractId, userOrgId]
|
||||
);
|
||||
if (Number(rows[0]?.cnt ?? 0) === 0) {
|
||||
this.logger.warn(
|
||||
`Cross-contract access attempt: User ${user.user_id} (Org ${userOrgId}) on Contract ${instance.contractId} Instance ${instanceId}`
|
||||
);
|
||||
throw new ForbiddenException({
|
||||
userMessage: 'คุณไม่มีสิทธิ์เข้าถึง Workflow ของสัญญานี้',
|
||||
recoveryAction: 'ตรวจสอบสิทธิ์กับ Project Admin',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Level 3: Assigned Handler — User นี้ถูก Assign มาให้ทำ Step นี้โดยตรง
|
||||
const assignedUserId = instance.context?.assignedUserId as
|
||||
| number
|
||||
|
||||
Reference in New Issue
Block a user