From 77d1be8dbd4092c5c23a99f0ff8f91ed2015ec74 Mon Sep 17 00:00:00 2001 From: ChaeYeon Lee Date: Fri, 9 Oct 2026 20:44:28 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20boolean=20=ED=95=84=EB=93=9C=EC=97=90=20?= =?UTF-8?q?=EB=AC=B8=EC=9E=90=EC=97=B4=EC=9D=B4=20true=EB=A1=9C=20?= =?UTF-8?q?=EB=B3=80=ED=99=98=EB=90=98=EC=96=B4=20=ED=86=B5=EA=B3=BC?= =?UTF-8?q?=ED=95=98=EB=8D=98=20=EB=AC=B8=EC=A0=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 전역 ValidationPipe의 enableImplicitConversion 때문에 @IsBoolean 필드에 "false"·"YES"·1 같은 값이 Boolean(값)으로 바뀌어 통과했다. 자기선언 동의에 "false" 문자열을 보내면 동의한 것으로 저장될 수 있었다. - 변환 전 원래 값으로 검사하는 @StrictBoolean() 데코레이터 추가 (src/core) - 자기선언 동의 3종, 질문 템플릿 required·evaluationEnabled에 적용 - 전역 설정(main.ts)은 변경하지 않음 Co-Authored-By: Claude Opus 5.5 --- .../strict-boolean.decorator.spec.ts | 85 +++++++++++++++++++ .../decorators/strict-boolean.decorator.ts | 18 ++++ src/declaration/dto/submit-declaration.dto.ts | 9 +- src/question-template/dto/question.dto.ts | 6 +- 4 files changed, 111 insertions(+), 7 deletions(-) create mode 100644 src/core/decorators/strict-boolean.decorator.spec.ts create mode 100644 src/core/decorators/strict-boolean.decorator.ts diff --git a/src/core/decorators/strict-boolean.decorator.spec.ts b/src/core/decorators/strict-boolean.decorator.spec.ts new file mode 100644 index 0000000..28cbcb7 --- /dev/null +++ b/src/core/decorators/strict-boolean.decorator.spec.ts @@ -0,0 +1,85 @@ +import { BadRequestException, ValidationPipe } from '@nestjs/common'; +import { Type } from 'class-transformer'; +import { ValidateNested } from 'class-validator'; +import { SubmitDeclarationDto } from '../../declaration/dto/submit-declaration.dto'; +import { CreateQuestionTemplateDto } from '../../question-template/dto/create-question-template.dto'; +import { StrictBoolean } from './strict-boolean.decorator'; + +// src/main.ts의 전역 ValidationPipe와 같은 설정 (implicit conversion이 켜져 있는 상태에서 검증해야 의미가 있다) +const pipe = new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + transformOptions: { enableImplicitConversion: true }, +}); + +async function transform(metatype: new () => T, body: unknown): Promise { + return pipe.transform(body, { type: 'body', metatype }); +} + +class FlagDto { + @StrictBoolean() + flag!: boolean; +} + +class NestedDto { + @ValidateNested() + @Type(() => FlagDto) + inner!: FlagDto; +} + +describe('StrictBoolean', () => { + it.each([true, false])('진짜 boolean(%s)은 그대로 통과한다', async (value) => { + await expect(transform(FlagDto, { flag: value })).resolves.toMatchObject({ flag: value }); + }); + + it.each(['false', 'true', 'YES', 'HOLD', 'NO', 1, 0, '', null])( + '%p는 true/false로 바뀌지 않고 400으로 거부된다', + async (value) => { + await expect(transform(FlagDto, { flag: value })).rejects.toBeInstanceOf(BadRequestException); + }, + ); + + it('중첩 DTO 안에서도 원래 값으로 검사한다', async () => { + await expect(transform(NestedDto, { inner: { flag: 'false' } })).rejects.toBeInstanceOf(BadRequestException); + await expect(transform(NestedDto, { inner: { flag: false } })).resolves.toMatchObject({ inner: { flag: false } }); + }); + + it('비교: 그냥 @IsBoolean이었다면 "false"가 true로 바뀌어 통과했다 (implicit conversion)', async () => { + const { IsBoolean } = await import('class-validator'); + class LooseDto { + @IsBoolean() + flag!: boolean; + } + await expect(transform(LooseDto, { flag: 'false' })).resolves.toMatchObject({ flag: true }); + }); +}); + +describe('적용된 DTO', () => { + const consents = { evaluationAgreed: true, dataAccessAgreed: true, evidenceRetentionAgreed: true, consentVersion: '2026-10-01' }; + + it.each(['evaluationAgreed', 'dataAccessAgreed', 'evidenceRetentionAgreed'])( + '자기선언 동의 %s에 "false" 문자열을 보내면 400 (동의로 저장되지 않음)', + async (field) => { + await expect( + transform(SubmitDeclarationDto, { answers: [], consents: { ...consents, [field]: 'false' } }), + ).rejects.toBeInstanceOf(BadRequestException); + }, + ); + + it('자기선언 동의가 진짜 boolean이면 그대로 전달된다 (false도 false로)', async () => { + const dto = await transform(SubmitDeclarationDto, { answers: [], consents: { ...consents, dataAccessAgreed: false } }); + expect(dto.consents.dataAccessAgreed).toBe(false); + expect(dto.consents.evaluationAgreed).toBe(true); + }); + + it.each(['required', 'evaluationEnabled'])('질문 템플릿 %s에 "false" 문자열을 보내면 400', async (field) => { + const question = { + order: 1, type: 'SCORE', text: '질문', required: true, scoreMin: 1, scoreMax: 10, evaluationEnabled: true, + [field]: 'false', + }; + await expect( + transform(CreateQuestionTemplateDto, { name: '템플릿', questions: [question] }), + ).rejects.toBeInstanceOf(BadRequestException); + }); +}); diff --git a/src/core/decorators/strict-boolean.decorator.ts b/src/core/decorators/strict-boolean.decorator.ts new file mode 100644 index 0000000..80efe56 --- /dev/null +++ b/src/core/decorators/strict-boolean.decorator.ts @@ -0,0 +1,18 @@ +import { applyDecorators } from '@nestjs/common'; +import { Transform } from 'class-transformer'; +import { IsBoolean, ValidationOptions } from 'class-validator'; + +/** + * 진짜 boolean(true/false)만 통과시킨다. + * + * 전역 ValidationPipe의 enableImplicitConversion이 boolean 필드를 검증 전에 Boolean(값)으로 바꾸기 때문에 + * 그냥 @IsBoolean()만 쓰면 "false"·"YES"·1 같은 값이 true로 바뀌어 통과한다. + * 동의 여부·재고용 의사처럼 법적 의미가 있는 값이 뒤바뀌지 않도록, 변환 전 원래 값으로 검사한다. + */ +export function StrictBoolean(validationOptions?: ValidationOptions) { + return applyDecorators( + // obj는 변환 전 원본 요청 값. 암묵 변환된 값 대신 원본을 그대로 검증에 넘긴다 + Transform(({ obj, key }) => obj[key]), + IsBoolean(validationOptions), + ); +} diff --git a/src/declaration/dto/submit-declaration.dto.ts b/src/declaration/dto/submit-declaration.dto.ts index d8ffc45..6871ea6 100644 --- a/src/declaration/dto/submit-declaration.dto.ts +++ b/src/declaration/dto/submit-declaration.dto.ts @@ -2,13 +2,13 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { Type } from 'class-transformer'; import { IsArray, - IsBoolean, IsNotEmpty, IsNumber, IsOptional, IsString, ValidateNested, } from 'class-validator'; +import { StrictBoolean } from '../../core/decorators/strict-boolean.decorator'; /** * 질문 유형에 맞는 필드 하나만 보낸다. SCORE → answerScore, SINGLE_CHOICE → answerOptionId, TEXT → answerText @@ -36,17 +36,18 @@ export class AnswerDto { answerText?: string; } +// 동의 여부는 진짜 boolean만 허용 ("false" 문자열이 동의로 바뀌지 않도록) export class DeclarationConsentsDto { @ApiProperty({ example: true, description: '평가 활용 동의' }) - @IsBoolean() + @StrictBoolean() evaluationAgreed!: boolean; @ApiProperty({ example: true, description: '정보 열람 동의' }) - @IsBoolean() + @StrictBoolean() dataAccessAgreed!: boolean; @ApiProperty({ example: true, description: '증빙 보관 동의' }) - @IsBoolean() + @StrictBoolean() evidenceRetentionAgreed!: boolean; @ApiProperty({ example: '2026-10-01', description: '질문지 조회 응답의 consentVersion' }) diff --git a/src/question-template/dto/question.dto.ts b/src/question-template/dto/question.dto.ts index a9804ab..5b9cdf1 100644 --- a/src/question-template/dto/question.dto.ts +++ b/src/question-template/dto/question.dto.ts @@ -2,13 +2,13 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { QuestionType } from '@prisma/client'; import { IsArray, - IsBoolean, IsEnum, IsInt, IsString, Min, ValidateIf, } from 'class-validator'; +import { StrictBoolean } from '../../core/decorators/strict-boolean.decorator'; /** * 템플릿 질문 1개. 여기서는 형식(타입)만 검사하고(400), @@ -30,7 +30,7 @@ export class QuestionDto { text!: string; @ApiProperty({ example: true }) - @IsBoolean() + @StrictBoolean() required!: boolean; @ApiPropertyOptional({ example: 1, description: 'SCORE 필수. 1 이상' }) @@ -59,6 +59,6 @@ export class QuestionDto { maxLength?: number; @ApiProperty({ example: true, description: '퇴사 평가 항목으로 사용할지 여부' }) - @IsBoolean() + @StrictBoolean() evaluationEnabled!: boolean; }