fix(users): preserve superadmin roles and enforce actor privilege boundary
This commit is contained in:
1 parent
3321bac22d
commit
6b1eee114b
7 files changed
+183
-29
No files matched your search
@@ -0,0 +1,73 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
|
||||
// All identities and credentials here are disposable test fixtures.
|
||||
describe("admin user privilege boundary", () => {
|
||||
let service: any;
|
||||
let prisma: any;
|
||||
const owner = { id: "owner-fixture", role: "SUPER_ADMIN" };
|
||||
const admin = { id: "admin-fixture", role: "ADMIN" };
|
||||
beforeEach(() => {
|
||||
prisma = {
|
||||
user: {
|
||||
findUnique: jest.fn().mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" }),
|
||||
update: jest.fn().mockImplementation(async ({ data }) => ({ role: "SUPER_ADMIN", ...data })),
|
||||
create: jest.fn(),
|
||||
},
|
||||
walletTransaction: { create: jest.fn() },
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
service = new AdminService(prisma, {} as never, {} as never);
|
||||
});
|
||||
it("allows an authenticated superadmin password-only edit without changing the exact role", async () => {
|
||||
const result = await service.updateUser("target-fixture", { password: "Fixture-only-123" }, owner);
|
||||
expect(result.role).toBe("SUPER_ADMIN");
|
||||
expect(prisma.user.update.mock.calls[0][0].data).not.toHaveProperty("role");
|
||||
});
|
||||
it.each(["ADMIN", "Admin", "User_PetOwner"])("denies %s assigning superadmin on create", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
await expect(service.createUser({ firstName: "Test", lastName: "Fixture", mobile: "09120000001", role: "SUPER_ADMIN" }, { id: "actor", role })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["SUPER_ADMIN", "super-admin", "AdminSuper"])("denies ordinary admin escalation to %s", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: admin.id, role: "Admin" });
|
||||
await expect(service.updateUser(admin.id, { role }, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([{ password: "Fixture-only-123" }, { email: "fixture@example.test" }, { mobile: "09120000001" }, { role: "Admin" }, { walletBalance: 1 }, { firstName: "Changed" }])("denies ordinary admin editing superadmin", async dto => {
|
||||
await expect(service.updateUser("target-fixture", dto, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies alternate role endpoint revocation", async () => {
|
||||
await expect(service.updateUserRole("target-fixture", "Admin", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies deleting superadmin", async () => {
|
||||
await expect(service.deleteUser("target-fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies changing superadmin wallet", async () => {
|
||||
await expect(service.adjustUserWallet("target-fixture", 1, "deposit", "fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.walletTransaction.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("accepts ADMIN alias for ordinary CRUD and authorized promotion/revocation", async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "User_PetOwner" });
|
||||
await service.updateUser("target-fixture", { role: "ADMIN" }, admin);
|
||||
await service.updateUser("target-fixture", { role: "SUPER_ADMIN" }, owner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" });
|
||||
await service.updateUserRole("target-fixture", "Admin", owner);
|
||||
expect(prisma.user.update).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it("fails closed without authenticated actor or with API key superadmin", async () => {
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" }, { ...owner, isApiKey: true })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
it("controller forwards authenticated request identity, not DTO identity", async () => {
|
||||
const svc = { updateUser: jest.fn().mockResolvedValue({}) };
|
||||
const controller: any = new AdminController(svc as never, {} as never);
|
||||
const dto = { firstName: "Test" };
|
||||
await controller.updateUser("target-fixture", dto, { user: admin });
|
||||
expect(svc.updateUser).toHaveBeenCalledWith("target-fixture", dto, admin);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
} from "@nestjs/swagger";
|
||||
|
||||
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
@@ -62,8 +64,8 @@ export class AdminController {
|
||||
|
||||
@Post("users")
|
||||
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
|
||||
async createUser(@Body() dto: CreateUserDto) {
|
||||
const user = await this.adminService.createUser(dto);
|
||||
async createUser(@Body() dto: CreateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.createUser(dto, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر جدید با موفقیت ایجاد شد",
|
||||
@@ -80,8 +82,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id")
|
||||
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto) {
|
||||
const user = await this.adminService.updateUser(id, dto);
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUser(id, dto, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "اطلاعات کاربر با موفقیت ویرایش شد",
|
||||
@@ -91,8 +93,8 @@ export class AdminController {
|
||||
|
||||
@Delete("users/:id")
|
||||
@ApiOperation({ summary: "حذف کاربر و دادههای مرتبط" })
|
||||
async deleteUser(@Param("id") id: string) {
|
||||
await this.adminService.deleteUser(id);
|
||||
async deleteUser(@Param("id") id: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
await this.adminService.deleteUser(id, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر با موفقیت از سیستم حذف شد",
|
||||
@@ -101,8 +103,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id/role")
|
||||
@ApiOperation({ summary: "تغییر نقش کاربر" })
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string) {
|
||||
const user = await this.adminService.updateUserRole(id, role);
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUserRole(id, role, req?.user);
|
||||
return { success: true, data: user };
|
||||
}
|
||||
|
||||
@@ -113,6 +115,7 @@ export class AdminController {
|
||||
@Body("amount") amount: number,
|
||||
@Body("type") type: "deposit" | "withdrawal" | "refund",
|
||||
@Body("description") description?: string,
|
||||
@Req() req?: { user?: UserAdminActor },
|
||||
) {
|
||||
const numAmount = Number(amount);
|
||||
if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
|
||||
@@ -130,6 +133,7 @@ export class AdminController {
|
||||
numAmount,
|
||||
type,
|
||||
description,
|
||||
req?.user,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@@ -61,15 +61,8 @@ export class CouponInput {
|
||||
targets?: CouponTargetInput[];
|
||||
}
|
||||
|
||||
const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner",
|
||||
"User_Vet",
|
||||
"User_Clinic",
|
||||
"User_PetShop",
|
||||
"Customer",
|
||||
"Admin",
|
||||
"SUPER_ADMIN",
|
||||
];
|
||||
import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
@@ -242,7 +235,8 @@ export class AdminService {
|
||||
return user;
|
||||
}
|
||||
|
||||
async createUser(dto: CreateUserDto) {
|
||||
async createUser(dto: CreateUserDto, actor?: UserAdminActor) {
|
||||
assertUserMutationAllowed(actor, undefined, dto.role);
|
||||
const mobile = normalizeMobile(dto.mobile);
|
||||
const existingMobile = await this.prisma.user.findUnique({
|
||||
where: { mobile },
|
||||
@@ -289,7 +283,7 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto) {
|
||||
async updateUser(id: string, dto: UpdateUserDto, actor?: UserAdminActor) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException(
|
||||
"امکان ویرایش حساب ادمین پیشفرض وجود ندارد",
|
||||
@@ -301,6 +295,8 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role, dto.role);
|
||||
|
||||
const normalizedMobile = dto.mobile
|
||||
? normalizeMobile(dto.mobile)
|
||||
: undefined;
|
||||
@@ -355,17 +351,11 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUserRole(id: string, role: string) {
|
||||
if (!ALLOWED_USER_ROLES.includes(role)) {
|
||||
throw new BadRequestException("نقش کاربری مشخص شده نامعتبر است");
|
||||
}
|
||||
return this.prisma.user.update({
|
||||
where: { id },
|
||||
data: { role },
|
||||
});
|
||||
async updateUserRole(id: string, role: string, actor?: UserAdminActor) {
|
||||
return this.updateUser(id, { role }, actor);
|
||||
}
|
||||
|
||||
async deleteUser(id: string) {
|
||||
async deleteUser(id: string, actor?: UserAdminActor) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException("امکان حذف حساب ادمین پیشفرض وجود ندارد");
|
||||
}
|
||||
@@ -375,6 +365,8 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await tx.userAddress.deleteMany({ where: { userId: id } });
|
||||
await tx.walletTransaction.deleteMany({ where: { userId: id } });
|
||||
@@ -1412,12 +1404,15 @@ export class AdminService {
|
||||
amount: number,
|
||||
type: "deposit" | "withdrawal" | "refund",
|
||||
description?: string,
|
||||
actor?: UserAdminActor,
|
||||
) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
const transaction = await this.prisma.walletTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
|
||||
@@ -5,9 +5,12 @@ import {
|
||||
IsEmail,
|
||||
MinLength,
|
||||
IsNumber,
|
||||
IsIn,
|
||||
} from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
|
||||
import { ALLOWED_USER_ROLES } from "../user-role-policy";
|
||||
|
||||
export class CreateUserDto {
|
||||
@ApiProperty({ description: "نام کاربر", example: "علی" })
|
||||
@IsNotEmpty({ message: "نام الزامی است" })
|
||||
@@ -41,6 +44,7 @@ export class CreateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
|
||||
@@ -85,6 +89,7 @@ export class UpdateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
|
||||
export const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner", "User_Vet", "User_Clinic", "User_PetShop",
|
||||
"User_Wholesale", "User_B2B", "Customer", "Admin", "ADMIN", "SUPER_ADMIN",
|
||||
];
|
||||
|
||||
export interface UserAdminActor {
|
||||
id?: string;
|
||||
role?: string;
|
||||
isApiKey?: boolean;
|
||||
}
|
||||
|
||||
// Match RolesGuard semantics; keep stored values unchanged.
|
||||
export function isSuperAdminRole(role?: string): boolean {
|
||||
const normalized = typeof role === "string" ? role.toLowerCase().replace(/[_-]/g, "") : "";
|
||||
return normalized === "superadmin" || normalized === "adminsuper";
|
||||
}
|
||||
|
||||
export function assertUserMutationAllowed(actor?: UserAdminActor, currentRole?: string, nextRole?: string): void {
|
||||
const role = actor?.role?.toLowerCase().replace(/[_-]/g, "");
|
||||
const isSuperAdmin = !!actor?.id && !actor.isApiKey && isSuperAdminRole(actor.role);
|
||||
if ((!actor?.id && !actor?.isApiKey) || (role !== "admin" && !isSuperAdmin) ||
|
||||
((isSuperAdminRole(currentRole) || isSuperAdminRole(nextRole)) && !isSuperAdmin)) {
|
||||
throw new ForbiddenException("فقط مدیر ارشد مجاز به مدیریت حساب و نقش مدیر ارشد است");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,46 @@ import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Users from './Users';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
vi.mock('../store/adminAuthStore', () => ({ useAdminAuthStore: vi.fn() }));
|
||||
|
||||
describe('Users superadmin editor', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(useAdminAuthStore).mockReturnValue('SUPER_ADMIN');
|
||||
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'owner-fixture', firstName: 'Owner', role: 'SUPER_ADMIN' }], meta: { total: 1 } } });
|
||||
vi.mocked(api.put).mockResolvedValue({ data: { success: true } });
|
||||
});
|
||||
it.each(['SUPER_ADMIN', 'ADMIN', 'Admin', 'User_Vet'])('preserves exact %s role on password-only save', async (role) => {
|
||||
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'owner-fixture', firstName: 'Owner', role }], meta: { total: 1 } } });
|
||||
render(<MemoryRouter><Users /></MemoryRouter>);
|
||||
fireEvent.click((await screen.findAllByTitle('ویرایش مشخصات'))[0]);
|
||||
const select = screen.getAllByRole('combobox')[1];
|
||||
expect(select).toHaveValue(role);
|
||||
expect(screen.getAllByRole('option', { name: /مدیر ارشد/ }).length).toBeGreaterThan(0);
|
||||
fireEvent.change(document.querySelector('input[type="password"]')!, { target: { value: 'Fixture-only-123' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات' }));
|
||||
await waitFor(() => expect(api.put).toHaveBeenCalled());
|
||||
const payload = vi.mocked(api.put).mock.calls[0][1] as Record<string, unknown>;
|
||||
expect(payload).not.toHaveProperty('role');
|
||||
});
|
||||
it('submits explicit superadmin promotion for authorized actor', async () => {
|
||||
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'ordinary-fixture', role: 'Admin' }], meta: { total: 1 } } });
|
||||
render(<MemoryRouter><Users /></MemoryRouter>);
|
||||
fireEvent.click((await screen.findAllByTitle('ویرایش مشخصات'))[0]);
|
||||
fireEvent.change(screen.getAllByRole('combobox')[1], { target: { value: 'SUPER_ADMIN' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات' }));
|
||||
await waitFor(() => expect(api.put).toHaveBeenCalledWith('/admin/users/ordinary-fixture', expect.objectContaining({ role: 'SUPER_ADMIN' })));
|
||||
});
|
||||
it('does not offer superadmin promotion to ordinary admin', async () => {
|
||||
vi.mocked(useAdminAuthStore).mockReturnValue('Admin');
|
||||
render(<MemoryRouter><Users /></MemoryRouter>);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'افزودن کاربر جدید' }));
|
||||
const select = screen.getAllByRole('combobox')[1];
|
||||
expect(select.querySelector('option[value="SUPER_ADMIN"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
|
||||
@@ -17,6 +17,7 @@ import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
|
||||
|
||||
@@ -44,6 +45,8 @@ export interface UserRecord {
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
export default function Users() {
|
||||
const actorRole = useAdminAuthStore(state => state.adminUser?.role);
|
||||
const canManageSuperAdmin = ['superadmin', 'adminsuper'].includes((actorRole || '').toLowerCase().replace(/[_-]/g, ''));
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [users, setUsers] = useState<UserRecord[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
@@ -266,7 +269,7 @@ export default function Users() {
|
||||
firstName: editFormData.firstName.trim(),
|
||||
lastName: editFormData.lastName.trim(),
|
||||
mobile: editFormData.mobile.trim(),
|
||||
role: editFormData.role,
|
||||
...(editFormData.role !== editUser.role && { role: editFormData.role }),
|
||||
walletBalance: Number(editFormData.walletBalance) || 0,
|
||||
};
|
||||
if (editFormData.email.trim()) payload.email = editFormData.email.trim();
|
||||
@@ -358,6 +361,7 @@ export default function Users() {
|
||||
<option value="User_Wholesale">خریدار عمده</option>
|
||||
<option value="User_B2B">همکار (B2B)</option>
|
||||
<option value="ADMIN">مدیر سیستم (Admin)</option>
|
||||
<option value="SUPER_ADMIN">مدیر ارشد (Super Admin)</option>
|
||||
</select>
|
||||
|
||||
<div className="relative w-full sm:w-64">
|
||||
@@ -633,6 +637,7 @@ export default function Users() {
|
||||
<option value="User_Wholesale">خریدار عمده (داروخانه/پتشاپ)</option>
|
||||
<option value="User_B2B">همکار (B2B)</option>
|
||||
<option value="ADMIN">مدیر سیستم (Admin)</option>
|
||||
{canManageSuperAdmin && <option value="SUPER_ADMIN">مدیر ارشد (Super Admin)</option>}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -742,6 +747,7 @@ export default function Users() {
|
||||
<label className="block text-gray-700 font-bold mb-1">نقش دسترسی</label>
|
||||
<select
|
||||
value={editFormData.role}
|
||||
disabled={!canManageSuperAdmin && ['superadmin', 'adminsuper'].includes((editUser?.role || '').toLowerCase().replace(/[_-]/g, ''))}
|
||||
onChange={(e) => setEditFormData({ ...editFormData, role: e.target.value })}
|
||||
className="w-full px-3 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none font-bold bg-white"
|
||||
>
|
||||
@@ -749,6 +755,10 @@ export default function Users() {
|
||||
<option value="User_Wholesale">خریدار عمده (داروخانه/پتشاپ)</option>
|
||||
<option value="User_B2B">همکار (B2B)</option>
|
||||
<option value="ADMIN">مدیر سیستم (Admin)</option>
|
||||
{canManageSuperAdmin && <option value="SUPER_ADMIN">مدیر ارشد (Super Admin)</option>}
|
||||
{editUser?.role && !['User_PetOwner', 'User_Wholesale', 'User_B2B', 'ADMIN', ...(canManageSuperAdmin ? ['SUPER_ADMIN'] : [])].includes(editUser.role) && (
|
||||
<option value={editUser.role}>{['superadmin', 'adminsuper'].includes(editUser.role.toLowerCase().replace(/[_-]/g, '')) ? 'مدیر ارشد (Super Admin)' : editUser.role}</option>
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in new issue
Block a user