test(security): add and refactor api security/idor coverage
Test Suite / test (24.15.0) (push) Has been cancelled

This commit is contained in:
Nils-Johan Gynther
2026-05-11 16:40:16 +02:00
parent 9b468d9a13
commit 1db30c9b6f
12 changed files with 1025 additions and 23 deletions
+149
View File
@@ -0,0 +1,149 @@
import { NotFoundException } from '@nestjs/common';
import { RecipesService } from './recipes.service';
describe('RecipesService IDOR security', () => {
const prismaMock = {
recipe: {
findUnique: jest.fn(),
findFirst: jest.fn(),
findMany: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
recipeIngredient: {
findMany: jest.fn(),
create: jest.fn(),
deleteMany: jest.fn(),
},
product: {
findMany: jest.fn(),
findFirst: jest.fn(),
},
user: {
findUnique: jest.fn(),
},
recipeShare: {
findUnique: jest.fn(),
create: jest.fn(),
delete: jest.fn(),
},
$transaction: jest.fn(),
};
const aiServiceMock = {};
const recipeMatchingServiceMock = {};
const service = new RecipesService(prismaMock as any, aiServiceMock as any, recipeMatchingServiceMock as any);
beforeEach(() => {
jest.clearAllMocks();
});
const setRecipeAsOwnedByAnotherUser = () => {
prismaMock.recipe.findUnique.mockResolvedValue({
id: 1,
ownerId: 100,
});
};
it('findAll scopar resultaten till userId (owner eller shared)', async () => {
prismaMock.recipe.findMany.mockResolvedValue([]);
await service.findAll(42);
expect(prismaMock.recipe.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
OR: expect.arrayContaining([
{ ownerId: 42 },
{ isPublic: true },
{ shares: { some: { userId: 42 } } },
]),
}),
}),
);
});
it('findOne nekar access om recipe inte är owner/shared/public', async () => {
prismaMock.recipe.findFirst.mockResolvedValue(null);
await expect(service.findOne(1, 42)).rejects.toThrow(NotFoundException);
});
it('findOne tillåter owner att läsa eget recipe', async () => {
prismaMock.recipe.findFirst.mockResolvedValue({
id: 1,
ownerId: 42,
isPublic: false,
name: 'Test Recipe',
description: '',
instructions: '',
mealPlanDayOfWeek: null,
imageUrl: null,
createdAt: new Date(),
updatedAt: new Date(),
});
const result = await service.findOne(1, 42);
expect(result).toBeDefined();
});
it('findOne tillåter shared user att läsa shared recipe', async () => {
prismaMock.recipe.findFirst.mockResolvedValue({
id: 1,
ownerId: 100,
isPublic: false,
shares: [{ userId: 42 }],
});
const result = await service.findOne(1, 42);
expect(result).toBeDefined();
});
it('findOne tillåter alla att läsa public recipe', async () => {
prismaMock.recipe.findFirst.mockResolvedValue({
id: 1,
ownerId: 100,
isPublic: true,
});
const result = await service.findOne(1, 42);
expect(result).toBeDefined();
});
it.each([
{
name: 'update',
action: () => service.update(1, {} as any, 42),
},
{
name: 'remove',
action: () => service.remove(1, 42),
},
{
name: 'shareWithUser',
action: () => service.shareWithUser(1, 42, 'someuser'),
},
{
name: 'unshareWithUser',
action: () => service.unshareWithUser(1, 42, 'someuser'),
},
{
name: 'setVisibility',
action: () => service.setVisibility(1, 42, true),
},
{
name: 'addIngredient',
action: () => service.addIngredient(1, { productId: 1, quantity: 100 } as any, 42),
},
{
name: 'updateImage',
action: () => service.updateImage(1, 'http://example.com/image.jpg', 42),
},
])('%s nekar icke-owner', async ({ action }) => {
setRecipeAsOwnedByAnotherUser();
await expect(action()).rejects.toThrow(NotFoundException);
});
});
@@ -0,0 +1,100 @@
import { UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RecipesController } from './recipes.controller';
describe('Recipes controller security', () => {
const makeUser = (overrides: Partial<{ userId: number; role: string }> = {}) => ({
userId: 42,
role: 'user',
...overrides,
});
const recipesServiceMock = {
findAll: jest.fn(),
findOne: jest.fn(),
create: jest.fn(),
update: jest.fn(),
remove: jest.fn(),
shareWithUser: jest.fn(),
unshareWithUser: jest.fn(),
setVisibility: jest.fn(),
};
const controller = new RecipesController(recipesServiceMock as any, {} as any);
beforeEach(() => {
jest.clearAllMocks();
});
it('JwtAuthGuard kräver autentisering på findAll', () => {
const guard = new JwtAuthGuard(new Reflector());
expect(() => guard.handleRequest(null, null, null)).toThrow(UnauthorizedException);
});
it('JwtAuthGuard tillåter autentiserad användare på findAll', () => {
const guard = new JwtAuthGuard(new Reflector());
const user = makeUser({ userId: 1 });
expect(guard.handleRequest(null, user, null)).toBe(user);
});
it('findOne vidarebefordrar @CurrentUser.userId till service', () => {
recipesServiceMock.findOne.mockResolvedValue({ id: 1 });
controller.findOne(1, makeUser());
expect(recipesServiceMock.findOne).toHaveBeenCalledWith(1, 42);
});
it('create vidarebefordrar @CurrentUser.userId till service', async () => {
const dto = { name: 'test' };
recipesServiceMock.create.mockResolvedValue({ id: 1 });
await controller.create(dto as any, makeUser());
expect(recipesServiceMock.create).toHaveBeenCalledWith(dto, 42);
});
it('update vidarebefordrar @CurrentUser.userId till service', async () => {
const dto = { name: 'updated' };
recipesServiceMock.update.mockResolvedValue({ id: 1 });
await controller.update(1, dto as any, makeUser());
expect(recipesServiceMock.update).toHaveBeenCalledWith(1, dto, 42);
});
it('remove vidarebefordrar @CurrentUser.userId till service', async () => {
recipesServiceMock.remove.mockResolvedValue(undefined);
await controller.remove(1, makeUser());
expect(recipesServiceMock.remove).toHaveBeenCalledWith(1, 42);
});
it('shareRecipe vidarebefordrar userId och trimmar username', async () => {
recipesServiceMock.shareWithUser.mockResolvedValue(undefined);
await controller.shareRecipe(1, { username: ' alice ' } as any, makeUser());
expect(recipesServiceMock.shareWithUser).toHaveBeenCalledWith(1, 42, 'alice');
});
it('unshareRecipe vidarebefordrar userId och trimmar username', async () => {
recipesServiceMock.unshareWithUser.mockResolvedValue(undefined);
await controller.unshareRecipe(1, ' alice ', makeUser());
expect(recipesServiceMock.unshareWithUser).toHaveBeenCalledWith(1, 42, 'alice');
});
it('setVisibility vidarebefordrar userId till service', async () => {
recipesServiceMock.setVisibility.mockResolvedValue(undefined);
await controller.setVisibility(1, { isPublic: true } as any, makeUser());
expect(recipesServiceMock.setVisibility).toHaveBeenCalledWith(1, 42, true);
});
});