test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
1 parent
1e73715169
commit
ddbf1ca026
439 files changed
+32911
-6107
No files matched your search
@@ -3,64 +3,64 @@ import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
} from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class CsrfGuard implements CanActivate {
|
||||
private readonly stateChangingMethods = new Set([
|
||||
'POST',
|
||||
'PUT',
|
||||
'PATCH',
|
||||
'DELETE',
|
||||
"POST",
|
||||
"PUT",
|
||||
"PATCH",
|
||||
"DELETE",
|
||||
]);
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const method = (req.method || '').toUpperCase();
|
||||
const method = (req.method || "").toUpperCase();
|
||||
|
||||
// Safe / Read-only HTTP methods are not subject to CSRF
|
||||
if (!this.stateChangingMethods.has(method)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const path = req.originalUrl || req.url || '';
|
||||
const path = req.originalUrl || req.url || "";
|
||||
|
||||
// Webhooks & Payment Callbacks (e.g. Zibal gateway callback, MeliPayamak incoming webhooks)
|
||||
if (
|
||||
path.includes('/payment/callback') ||
|
||||
path.includes('/payment/verify') ||
|
||||
path.includes('/webhooks')
|
||||
path.includes("/payment/callback") ||
|
||||
path.includes("/payment/verify") ||
|
||||
path.includes("/webhooks")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 1. Authorization Bearer Token requests are immune to standard cross-site browser CSRF
|
||||
const authHeader = req.headers['authorization'];
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const authHeader = req.headers["authorization"];
|
||||
if (authHeader && authHeader.startsWith("Bearer ")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Custom header verification (X-Requested-With or X-CSRF-Token)
|
||||
const customHeader =
|
||||
req.headers['x-requested-with'] ||
|
||||
req.headers['x-csrf-token'] ||
|
||||
req.headers['x-api-key'];
|
||||
req.headers["x-requested-with"] ||
|
||||
req.headers["x-csrf-token"] ||
|
||||
req.headers["x-api-key"];
|
||||
|
||||
if (customHeader) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3. Same-origin Sec-Fetch-Site check (Modern Browsers Protection)
|
||||
const secFetchSite = req.headers['sec-fetch-site'];
|
||||
if (secFetchSite === 'same-origin' || secFetchSite === 'same-site') {
|
||||
const secFetchSite = req.headers["sec-fetch-site"];
|
||||
if (secFetchSite === "same-origin" || secFetchSite === "same-site") {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If request has cookie credentials but lacks any anti-CSRF signature, block it
|
||||
if (req.headers.cookie) {
|
||||
throw new ForbiddenException(
|
||||
'درخواست مشکوک به حمله CSRF است. هدر اعتبارسنجی یافت نشد.',
|
||||
"درخواست مشکوک به حمله CSRF است. هدر اعتبارسنجی یافت نشد.",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { RolesGuard } from './roles.guard';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ExecutionContext, ForbiddenException } from '@nestjs/common';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { RolesGuard } from "./roles.guard";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { ROLES_KEY } from "../decorators/roles.decorator";
|
||||
|
||||
describe('RolesGuard', () => {
|
||||
describe("RolesGuard", () => {
|
||||
let guard: RolesGuard;
|
||||
let reflector: Reflector;
|
||||
|
||||
@@ -35,37 +35,37 @@ describe('RolesGuard', () => {
|
||||
} as any;
|
||||
};
|
||||
|
||||
it('should be defined', () => {
|
||||
it("should be defined", () => {
|
||||
expect(guard).toBeDefined();
|
||||
});
|
||||
|
||||
it('should allow access if no roles are required', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(undefined);
|
||||
const context = createMockContext({ role: 'User_PetOwner' });
|
||||
it("should allow access if no roles are required", () => {
|
||||
jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(undefined);
|
||||
const context = createMockContext({ role: "User_PetOwner" });
|
||||
expect(guard.canActivate(context)).toBe(true);
|
||||
});
|
||||
|
||||
it('should throw ForbiddenException if user is missing', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
|
||||
it("should throw ForbiddenException if user is missing", () => {
|
||||
jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(["Admin"]);
|
||||
const context = createMockContext(undefined);
|
||||
expect(() => guard.canActivate(context)).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('should throw ForbiddenException if user has non-matching role', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
|
||||
const context = createMockContext({ role: 'User_PetOwner' });
|
||||
it("should throw ForbiddenException if user has non-matching role", () => {
|
||||
jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(["Admin"]);
|
||||
const context = createMockContext({ role: "User_PetOwner" });
|
||||
expect(() => guard.canActivate(context)).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('should allow access if user has matching role', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
|
||||
const context = createMockContext({ role: 'Admin' });
|
||||
it("should allow access if user has matching role", () => {
|
||||
jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(["Admin"]);
|
||||
const context = createMockContext({ role: "Admin" });
|
||||
expect(guard.canActivate(context)).toBe(true);
|
||||
});
|
||||
|
||||
it('should allow access if user has case-insensitive matching admin role', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
|
||||
const context = createMockContext({ role: 'SUPER_ADMIN' });
|
||||
it("should allow access if user has case-insensitive matching admin role", () => {
|
||||
jest.spyOn(reflector, "getAllAndOverride").mockReturnValue(["Admin"]);
|
||||
const context = createMockContext({ role: "SUPER_ADMIN" });
|
||||
expect(guard.canActivate(context)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -3,9 +3,9 @@ import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
} from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { ROLES_KEY } from "../decorators/roles.decorator";
|
||||
|
||||
interface RequestWithUser {
|
||||
user?: {
|
||||
@@ -32,21 +32,21 @@ export class RolesGuard implements CanActivate {
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const user = request.user;
|
||||
if (!user || !user.role) {
|
||||
throw new ForbiddenException('شما دسترسی لازم برای این بخش را ندارید');
|
||||
throw new ForbiddenException("شما دسترسی لازم برای این بخش را ندارید");
|
||||
}
|
||||
|
||||
// If request originates from an API key, verify it has admin scope for admin-guarded routes
|
||||
if (user.isApiKey) {
|
||||
const scopes = Array.isArray(user.scopes) ? user.scopes : [];
|
||||
const hasAdminScope = scopes.includes('admin');
|
||||
const hasAdminScope = scopes.includes("admin");
|
||||
if (!hasAdminScope) {
|
||||
throw new ForbiddenException(
|
||||
'کلید API ارائهشده فاقد اسکوپ مدیریتی لازم برای این عملیات است',
|
||||
"کلید API ارائهشده فاقد اسکوپ مدیریتی لازم برای این عملیات است",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeRole = (r: string) => r.toLowerCase().replace(/[_-]/g, '');
|
||||
const normalizeRole = (r: string) => r.toLowerCase().replace(/[_-]/g, "");
|
||||
|
||||
const userRoleNorm = normalizeRole(user.role);
|
||||
const hasRole = requiredRoles.some((r) => {
|
||||
@@ -55,8 +55,8 @@ export class RolesGuard implements CanActivate {
|
||||
if (requiredNorm === userRoleNorm) return true;
|
||||
// Superadmin satisfies admin
|
||||
if (
|
||||
(userRoleNorm === 'superadmin' || userRoleNorm === 'adminsuper') &&
|
||||
requiredNorm === 'admin'
|
||||
(userRoleNorm === "superadmin" || userRoleNorm === "adminsuper") &&
|
||||
requiredNorm === "admin"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
@@ -64,7 +64,7 @@ export class RolesGuard implements CanActivate {
|
||||
});
|
||||
|
||||
if (!hasRole) {
|
||||
throw new ForbiddenException('سطح دسترسی شما کافی نیست');
|
||||
throw new ForbiddenException("سطح دسترسی شما کافی نیست");
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
Reference in new issue
Block a user