-
Notifications
You must be signed in to change notification settings - Fork 12
Pruebas Unitarias #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # Crear tests unitarios | ||
|
|
||
| ## Objetivo | ||
|
|
||
| Crear una suite de tests unitarios para el backend | ||
|
|
||
| ## Contexto | ||
|
|
||
| - README.md | ||
|
|
||
| ## Instrucciones | ||
|
|
||
| - Escribe tests jest en /src/tests/tests-iniciales.test.ts para: | ||
| - backend\src\application\services\candidateService.ts | ||
| - backend\src\application\services\fileUploadService.ts | ||
|
|
||
| - Ejecútalos con npm test y corrige cualquier fallo. | ||
| - Hay 2 familias principales de tests: | ||
| 1. Recepción de los datos del formulario | ||
| 2. Guardado en la base de datos | ||
| Se deben cubrir ambas. | ||
|
|
||
| ## Preguntas posteriores | ||
|
|
||
| - ¿Qué otros casos límite se te ocurren que puedan fallar para candidateService.addCandidate y para fileUploadService.uploadFile ? | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,360 @@ | ||
| // Mocks del cliente Prisma: todas las instancias de PrismaClient (una por modelo) | ||
| // deben resolver al mismo objeto simulado para poder aserir sobre las llamadas. | ||
| const mockPrisma = { | ||
| candidate: { | ||
| create: jest.fn(), | ||
| update: jest.fn(), | ||
| }, | ||
| education: { | ||
| create: jest.fn(), | ||
| update: jest.fn(), | ||
| }, | ||
| workExperience: { | ||
| create: jest.fn(), | ||
| update: jest.fn(), | ||
| }, | ||
| resume: { | ||
| create: jest.fn(), | ||
| }, | ||
| }; | ||
|
|
||
| class PrismaClientInitializationError extends Error {} | ||
|
|
||
| jest.mock('@prisma/client', () => { | ||
| return { | ||
| PrismaClient: jest.fn(() => mockPrisma), | ||
| Prisma: { | ||
| PrismaClientInitializationError, | ||
| }, | ||
| }; | ||
| }); | ||
|
|
||
| // Mock de multer: controlamos manualmente el middleware devuelto por upload.single() | ||
| // para simular éxito, rechazo de tipo de archivo y errores de Multer. | ||
| const singleMock = jest.fn(); | ||
|
|
||
| jest.mock('multer', () => { | ||
| class MulterError extends Error { | ||
| code: string; | ||
| constructor(code: string) { | ||
| super(code); | ||
| this.code = code; | ||
| } | ||
| } | ||
|
|
||
| const multerMock: any = jest.fn(() => ({ | ||
| single: singleMock, | ||
| })); | ||
| multerMock.diskStorage = jest.fn(() => ({})); | ||
| multerMock.MulterError = MulterError; | ||
|
|
||
| return multerMock; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- candidate test file ---'
sed -n '1,80p' backend/src/tests/tests-iniciales.test.ts
printf '%s\n' '--- Jest configuration and package versions ---'
find . -maxdepth 3 -type f \( -name 'package.json' -o -iname '*jest*' -o -name 'tsconfig*.json' \) -print
rg -n --hidden --glob '!node_modules/**' \
'jest|ts-jest|babel-jest|swc|transform|automock|PrismaClientInitializationError|singleMock|mockPrisma' \
package.json backend/package.json backend 2>/dev/null | head -250Repository: LIDR-academy/AI4Devs-tdd-202607-seniors Length of output: 8617 🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- backend package configuration ---'
cat backend/package.json
printf '%s\n' '--- backend TypeScript configuration ---'
cat backend/tsconfig.json
printf '%s\n' '--- repository Jest configuration files ---'
find . -maxdepth 4 -type f \( -iname 'jest.config.*' -o -iname 'jest.setup.*' -o -name '.babelrc' -o -name 'babel.config.*' \) -printRepository: LIDR-academy/AI4Devs-tdd-202607-seniors Length of output: 1862 🌐 Web query:
💡 Result: In Jest, calls to jest.mock are automatically hoisted to the top of the file [1][2][3]. Because of this hoisting, the code inside the module factory function is executed before the rest of the file's code, including variable initializations [1][3]. Consequently, accessing variables defined outside the factory is generally prohibited to prevent runtime errors caused by accessing uninitialized values [1][4][5]. To allow referencing variables within the mock factory, Jest provides an escape hatch: if a variable name begins with the word "mock" (case-insensitive), the babel-plugin-jest-hoist will permit its use inside the factory [1][4][5]. However, using this prefix does not automatically resolve the underlying issue of hoisting [1][3]. Even if the variable is permitted by the plugin, it remains your responsibility to ensure the variable is properly initialized by the time the factory function is executed [1][3]. If the variable is not yet initialized when the factory runs, you will encounter a ReferenceError [1][3]. Common approaches to handle this include: * Using a higher-order function: If you need to access a mock function, wrapping the reference in a function within the factory can delay the access until the mock is actually used, which may occur after initialization [1][6][3]. * Lazy initialization: Ensuring the mock is required or accessed lazily [4][5]. * Re-importing inside the factory: You can require or import dependencies directly inside the factory function to ensure they are available in that scope [6][7][8]. Regarding ts-jest, it performs its own hoisting logic to ensure compatibility with Jest's requirements [9][10]. While ts-jest aims to replicate this behavior, issues can arise depending on your configuration (e.g., if you disable built-in transformations or use certain module systems) [9][11]. If hoisting is not behaving as expected, ensure you are using the appropriate configuration (e.g., using babel-jest or the built-in ts-jest transformers) and follow the requirement to place jest.mock calls at the top level of the file [9][11]. Citations:
🌐 Web query:
💡 Result: In ts-jest, specifically surrounding version 29.2.5, the hoisting mechanism—implemented in hoist-jest.ts—is designed to move jest.mock and related calls to the top of the file [1]. Because these calls are moved to the top of the scope, any variables referenced within the jest.mock factory function that were defined later in the file would become out-of-scope or result in a reference error [2]. To address this, ts-jest performs a static analysis check during the transformation process. It identifies variables used within the factory function and verifies if they are available at the hoisted location [2]. Key points regarding this behavior include: 1. Static Analysis: The transformer inspects the factory function of jest.mock to detect dependencies [1][2]. If it determines that the factory function relies on variables that are defined after the mock call, it may avoid hoisting that specific call to prevent runtime errors [2]. 2. Variable Naming Conventions: By convention and implementation, variables starting with mock (case-insensitive) are often ignored by this out-of-scope check [2]. This allows developers to define mock implementations or helpers without triggering hoisting restrictions [2]. 3. Factory API Refactor: Around the v29.x series, the codebase transitioned to using the TypeScript factory API for AST transformations [3][4]. This change improved the robustness and maintainability of the transformer, including the logic that handles hoisting and scope validation [3][4]. If you encounter an error related to out-of-scope variables, ensure that any dependencies used inside your jest.mock factory function are defined before the mock call or are globally available [2]. Alternatively, you can move the logic inside the factory function or define the necessary variables earlier in the test file [2]. Citations:
🏁 Script executed: #!/bin/bash
set -eu
url='https://raw.githubusercontent.com/kulshekhar/ts-jest/v29.2.5/src/transformers/hoist-jest.ts'
curl -fsSL "$url" | sed -n '1,240p'
printf '%s\n' '--- related ts-jest hoist tests ---'
test_url='https://raw.githubusercontent.com/kulshekhar/ts-jest/v29.2.5/src/transformers/hoist-jest.spec.ts'
curl -fsSL "$test_url" | rg -n -C 4 'mock|out.of.scope|prefix|hoist' | head -240Repository: LIDR-academy/AI4Devs-tdd-202607-seniors Length of output: 12672 🏁 Script executed: #!/bin/bash
set -eu
python3 - <<'PY'
import json
from pathlib import Path
package = json.loads(Path("backend/package.json").read_text())
root = Path("backend")
config_files = [
p for p in root.rglob("*")
if p.is_file() and (
p.name.startswith("jest.config.") or
p.name.startswith("jest.setup.") or
p.name in {".babelrc", "babel.config.js", "babel.config.cjs", "babel.config.json"}
)
]
source = Path("backend/src/tests/tests-iniciales.test.ts").read_text()
print("test_command:", package["scripts"].get("test"))
print("ts-jest_dependency:", package["devDependencies"].get("ts-jest"))
print("jest_config_files:", [str(p) for p in config_files])
for identifier in ("PrismaClientInitializationError", "singleMock", "mockPrisma"):
print(f"{identifier}_used_in_mock_factory:",
identifier in source and (
f"mockPrisma" == identifier or
identifier in source[source.index("jest.mock('`@prisma/client`'"):source.index("// Mock de multer")] or
identifier in source[source.index("jest.mock('multer'"):source.index("import { addCandidate")]
))
PYRepository: LIDR-academy/AI4Devs-tdd-202607-seniors Length of output: 381 Configura el transformador TypeScript y corrige las capturas de
🤖 Prompt for AI Agents |
||
| }); | ||
|
|
||
| import { addCandidate } from '../application/services/candidateService'; | ||
| import { uploadFile } from '../application/services/fileUploadService'; | ||
| // eslint-disable-next-line @typescript-eslint/no-var-requires | ||
| const multer = require('multer'); | ||
|
|
||
| // Capturamos la config real que fileUploadService.ts pasa a multer() y multer.diskStorage() | ||
| // al cargar el módulo, ANTES de que ningún beforeEach limpie los mocks. | ||
| const diskStorageConfig = multer.diskStorage.mock.calls[0][0]; | ||
| const multerConfig = multer.mock.calls[0][0]; | ||
|
|
||
| describe('candidateService.addCandidate', () => { | ||
| const validCandidateData = { | ||
| firstName: 'Juan', | ||
| lastName: 'Perez', | ||
| email: 'juan.perez@example.com', | ||
| phone: '612345678', | ||
| address: 'Calle Falsa 123', | ||
| }; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('Recepción de los datos del formulario', () => { | ||
| it('rechaza el candidato si falta el nombre', async () => { | ||
| const invalidData = { ...validCandidateData, firstName: '' }; | ||
|
|
||
| await expect(addCandidate(invalidData)).rejects.toThrow('Invalid name'); | ||
| expect(mockPrisma.candidate.create).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('rechaza el candidato si el email tiene un formato inválido', async () => { | ||
| const invalidData = { ...validCandidateData, email: 'not-an-email' }; | ||
|
|
||
| await expect(addCandidate(invalidData)).rejects.toThrow('Invalid email'); | ||
| expect(mockPrisma.candidate.create).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('rechaza el candidato si el teléfono no es válido', async () => { | ||
| const invalidData = { ...validCandidateData, phone: '123' }; | ||
|
|
||
| await expect(addCandidate(invalidData)).rejects.toThrow('Invalid phone'); | ||
| expect(mockPrisma.candidate.create).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('acepta datos sin id como alta de un candidato nuevo', async () => { | ||
| mockPrisma.candidate.create.mockResolvedValue({ id: 1, ...validCandidateData }); | ||
|
|
||
| await addCandidate(validCandidateData); | ||
|
|
||
| expect(mockPrisma.candidate.create).toHaveBeenCalledWith({ | ||
| data: expect.objectContaining({ | ||
| firstName: 'Juan', | ||
| lastName: 'Perez', | ||
| email: 'juan.perez@example.com', | ||
| }), | ||
| }); | ||
| }); | ||
|
|
||
| it('omite las validaciones obligatorias cuando se envía un id (edición)', async () => { | ||
| mockPrisma.candidate.update.mockResolvedValue({ id: 5 }); | ||
|
|
||
| await addCandidate({ id: 5, firstName: '' }); | ||
|
|
||
| expect(mockPrisma.candidate.update).toHaveBeenCalledWith({ | ||
| where: { id: 5 }, | ||
| data: expect.any(Object), | ||
| }); | ||
| }); | ||
|
Comment on lines
+113
to
+122
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win Corrija el caso de edición.
🤖 Prompt for AI Agents |
||
| }); | ||
|
|
||
| describe('Guardado en la base de datos', () => { | ||
| it('guarda el candidato y devuelve el registro creado', async () => { | ||
| const savedCandidate = { id: 10, ...validCandidateData }; | ||
| mockPrisma.candidate.create.mockResolvedValue(savedCandidate); | ||
|
|
||
| const result = await addCandidate(validCandidateData); | ||
|
|
||
| expect(result).toEqual(savedCandidate); | ||
| }); | ||
|
|
||
| it('guarda las educaciones asociadas al candidato', async () => { | ||
| mockPrisma.candidate.create.mockResolvedValue({ id: 2 }); | ||
| mockPrisma.education.create.mockResolvedValue({ id: 20 }); | ||
|
|
||
| const dataWithEducation = { | ||
| ...validCandidateData, | ||
| educations: [ | ||
| { institution: 'UNI', title: 'Ingeniería', startDate: '2020-01-01' }, | ||
| ], | ||
| }; | ||
|
|
||
| await addCandidate(dataWithEducation); | ||
|
|
||
| expect(mockPrisma.education.create).toHaveBeenCalledWith({ | ||
| data: expect.objectContaining({ | ||
| institution: 'UNI', | ||
| title: 'Ingeniería', | ||
| candidateId: 2, | ||
| }), | ||
| }); | ||
| }); | ||
|
|
||
| it('guarda las experiencias laborales asociadas al candidato', async () => { | ||
| mockPrisma.candidate.create.mockResolvedValue({ id: 3 }); | ||
| mockPrisma.workExperience.create.mockResolvedValue({ id: 30 }); | ||
|
|
||
| const dataWithExperience = { | ||
| ...validCandidateData, | ||
| workExperiences: [ | ||
| { company: 'ACME', position: 'Dev', startDate: '2021-01-01' }, | ||
| ], | ||
| }; | ||
|
|
||
| await addCandidate(dataWithExperience); | ||
|
|
||
| expect(mockPrisma.workExperience.create).toHaveBeenCalledWith({ | ||
| data: expect.objectContaining({ | ||
| company: 'ACME', | ||
| position: 'Dev', | ||
| candidateId: 3, | ||
| }), | ||
| }); | ||
| }); | ||
|
|
||
| it('guarda el CV asociado al candidato', async () => { | ||
| mockPrisma.candidate.create.mockResolvedValue({ id: 4 }); | ||
| mockPrisma.resume.create.mockResolvedValue({ id: 40 }); | ||
|
|
||
| const dataWithCv = { | ||
| ...validCandidateData, | ||
| cv: { filePath: '/uploads/cv.pdf', fileType: 'application/pdf' }, | ||
| }; | ||
|
|
||
| await addCandidate(dataWithCv); | ||
|
|
||
| expect(mockPrisma.resume.create).toHaveBeenCalledWith({ | ||
| data: expect.objectContaining({ | ||
| candidateId: 4, | ||
| filePath: '/uploads/cv.pdf', | ||
| fileType: 'application/pdf', | ||
| }), | ||
| }); | ||
| }); | ||
|
|
||
| it('lanza un error legible cuando el email ya existe (constraint P2002)', async () => { | ||
| mockPrisma.candidate.create.mockRejectedValue({ code: 'P2002' }); | ||
|
|
||
| await expect(addCandidate(validCandidateData)).rejects.toThrow( | ||
| 'The email already exists in the database' | ||
| ); | ||
| }); | ||
|
|
||
| it('propaga otros errores de base de datos sin modificarlos', async () => { | ||
| const dbError = new Error('Connection lost'); | ||
| mockPrisma.candidate.create.mockRejectedValue(dbError); | ||
|
|
||
| await expect(addCandidate(validCandidateData)).rejects.toThrow('Connection lost'); | ||
| }); | ||
|
|
||
| it('[BUG] no revierte al candidato ni a las educaciones ya guardadas si falla un guardado posterior (no hay transacción)', async () => { | ||
| mockPrisma.candidate.create.mockResolvedValue({ id: 7 }); | ||
| mockPrisma.education.create | ||
| .mockResolvedValueOnce({ id: 100 }) // primera educación: se guarda con éxito | ||
| .mockRejectedValueOnce(new Error('DB connection lost')); // segunda educación: falla | ||
|
|
||
| const dataWithTwoEducations = { | ||
| ...validCandidateData, | ||
| educations: [ | ||
| { institution: 'UNI A', title: 'Grado', startDate: '2018-01-01' }, | ||
| { institution: 'UNI B', title: 'Master', startDate: '2020-01-01' }, | ||
| ], | ||
| }; | ||
|
|
||
| await expect(addCandidate(dataWithTwoEducations)).rejects.toThrow('DB connection lost'); | ||
|
|
||
| // El candidato ya quedó insertado en la base de datos... | ||
| expect(mockPrisma.candidate.create).toHaveBeenCalledTimes(1); | ||
| // ...y la primera educación también, a pesar de que addCandidate() "falló" globalmente. | ||
| // Al no usar una transacción, quedan datos parciales/huérfanos en la base de datos. | ||
| expect(mockPrisma.education.create).toHaveBeenCalledTimes(2); | ||
| expect(mockPrisma.education.create).toHaveBeenNthCalledWith( | ||
| 1, | ||
| expect.objectContaining({ | ||
| data: expect.objectContaining({ institution: 'UNI A', candidateId: 7 }), | ||
| }) | ||
| ); | ||
| }); | ||
|
Comment on lines
+214
to
+241
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift Convierta este caso en una prueba de atomicidad. La prueba pasa cuando 🤖 Prompt for AI Agents |
||
| }); | ||
| }); | ||
|
|
||
| describe('fileUploadService.uploadFile', () => { | ||
| const buildRes = () => { | ||
| const res: any = {}; | ||
| res.status = jest.fn().mockReturnValue(res); | ||
| res.json = jest.fn().mockReturnValue(res); | ||
| return res; | ||
| }; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('Recepción de los datos del formulario', () => { | ||
| it('rechaza el archivo cuando el filtro de multer lo descarta por tipo inválido', () => { | ||
| singleMock.mockReturnValue((req: any, res: any, cb: any) => { | ||
| req.file = undefined; | ||
| cb(null); | ||
| }); | ||
|
|
||
| const req: any = {}; | ||
| const res = buildRes(); | ||
|
|
||
| uploadFile(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(400); | ||
| expect(res.json).toHaveBeenCalledWith({ | ||
| error: 'Invalid file type, only PDF and DOCX are allowed!', | ||
| }); | ||
| }); | ||
|
|
||
| it('responde 500 cuando ocurre un MulterError (por ejemplo, tamaño excedido)', () => { | ||
| const multerError = new (multer as any).MulterError('LIMIT_FILE_SIZE'); | ||
| singleMock.mockReturnValue((req: any, res: any, cb: any) => { | ||
| cb(multerError); | ||
| }); | ||
|
|
||
| const req: any = {}; | ||
| const res = buildRes(); | ||
|
|
||
| uploadFile(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(500); | ||
| expect(res.json).toHaveBeenCalledWith({ error: multerError.message }); | ||
| }); | ||
|
|
||
| it('responde 500 cuando ocurre un error inesperado durante la subida', () => { | ||
| const unexpectedError = new Error('disk full'); | ||
| singleMock.mockReturnValue((req: any, res: any, cb: any) => { | ||
| cb(unexpectedError); | ||
| }); | ||
|
|
||
| const req: any = {}; | ||
| const res = buildRes(); | ||
|
|
||
| uploadFile(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(500); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'disk full' }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('Guardado en la base de datos', () => { | ||
| it('devuelve la ruta y el tipo del archivo cuando la subida es correcta', () => { | ||
| singleMock.mockReturnValue((req: any, res: any, cb: any) => { | ||
| req.file = { | ||
| path: '../uploads/123-cv.pdf', | ||
| mimetype: 'application/pdf', | ||
| }; | ||
| cb(null); | ||
| }); | ||
|
|
||
| const req: any = {}; | ||
| const res = buildRes(); | ||
|
|
||
| uploadFile(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(200); | ||
| expect(res.json).toHaveBeenCalledWith({ | ||
| filePath: '../uploads/123-cv.pdf', | ||
| fileType: 'application/pdf', | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('Seguridad (vulnerabilidades conocidas)', () => { | ||
| it('[VULNERABILIDAD] no sanea el nombre original del archivo: permite path traversal', () => { | ||
| const cb = jest.fn(); | ||
|
|
||
| diskStorageConfig.filename( | ||
| {} as any, | ||
| { originalname: '../../../../etc/passwd' } as any, | ||
| cb | ||
| ); | ||
|
|
||
| const [error, generatedFilename] = cb.mock.calls[0]; | ||
| expect(error).toBeNull(); | ||
| // Documenta el comportamiento actual: el "../" del nombre original no se elimina, | ||
| // por lo que un cliente malicioso podría intentar escribir fuera de uploads/. | ||
| expect(generatedFilename).toEqual(expect.stringContaining('../../../../etc/passwd')); | ||
| }); | ||
|
Comment on lines
+330
to
+344
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- candidate references ---'
rg -n -C 8 'diskStorageConfig|filename\s*:|destination\s*:|originalname|path\.join|path\.basename|sanitize|safe' backend/src backend/package.json package.json 2>/dev/null || true
printf '%s\n' '--- test context ---'
sed -n '280,375p' backend/src/tests/tests-iniciales.test.ts
printf '%s\n' '--- candidate file map ---'
fd -t f . backend/src | rg 'candidate|upload|multer|storage|config|test'Repository: LIDR-academy/AI4Devs-tdd-202607-seniors Length of output: 9628 🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- upload service ---'
sed -n '1,140p' backend/src/application/services/fileUploadService.ts
printf '%s\n' '--- package versions and lock entries ---'
rg -n -C 3 '"multer"|"`@types/multer`"|multer@' backend/package.json package.json package-lock.json backend/package-lock.json yarn.lock pnpm-lock.yaml 2>/dev/null || true
printf '%s\n' '--- path construction probe ---'
node - <<'JS'
const path = require('node:path');
const destination = '../uploads/';
const originalname = '../../../../etc/passwd';
const generatedFilename = `1700000000000-${originalname}`;
const joined = path.join(destination, generatedFilename);
const resolved = path.resolve(destination, generatedFilename);
console.log(JSON.stringify({
destination,
originalname,
generatedFilename,
joined,
resolved,
escapesDestination: !resolved.startsWith(path.resolve(destination) + path.sep),
}, null, 2));
JSRepository: LIDR-academy/AI4Devs-tdd-202607-seniors Length of output: 3033 🌐 Web query:
💡 Result: In Multer 1.4.5-lts.1, the diskStorage engine uses the Citations:
Rechace nombres de archivo con path traversal.
🤖 Prompt for AI Agents |
||
|
|
||
| it('[VULNERABILIDAD] el filtro de archivos confía ciegamente en el mimetype declarado por el cliente', () => { | ||
| const cb = jest.fn(); | ||
|
|
||
| // Un ejecutable disfrazado de PDF con solo cambiar el mimetype declarado en la petición | ||
| multerConfig.fileFilter( | ||
| {} as any, | ||
| { mimetype: 'application/pdf', originalname: 'malware.exe' } as any, | ||
| cb | ||
| ); | ||
|
|
||
| // El filtro lo acepta: no inspecciona el contenido real del archivo, solo el header. | ||
| expect(cb).toHaveBeenCalledWith(null, true); | ||
| }); | ||
|
Comment on lines
+346
to
+358
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift 🧩 Analysis chain🏁 Script executed: sed -n '320,370p' backend/src/tests/tests-iniciales.test.ts
printf '\n--- multer references ---\n'
rg -n "multerConfig|fileFilter|mimetype|originalname" backend/src backend -g '!node_modules' | head -200Repository: LIDR-academy/AI4Devs-tdd-202607-seniors Length of output: 4858 🏁 Script executed: cat -n backend/src/application/services/fileUploadService.ts
printf '\n--- test setup ---\n'
sed -n '1,80p' backend/src/tests/tests-iniciales.test.ts
printf '\n--- upload call sites and routes ---\n'
rg -n "upload|fileUploadService|single\\(|array\\(|fields\\(|req\\.file|fileType" backend/src -g '*.ts'Repository: LIDR-academy/AI4Devs-tdd-202607-seniors Length of output: 8064 No trate el MIME declarado por el cliente como validación de tipo.
🤖 Prompt for AI Agents |
||
| }); | ||
| }); | ||
Uh oh!
There was an error while loading. Please reload this page.