-
Notifications
You must be signed in to change notification settings - Fork 0
[feat] 메일 인증 보안 강화 #89
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
src/main/java/com/daramg/server/auth/repository/RateLimitRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,48 @@ | ||||||||||||||||||||||||||||||||||||||||||
| package com.daramg.server.auth.repository; | ||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||
| import lombok.RequiredArgsConstructor; | ||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.data.redis.core.RedisTemplate; | ||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.stereotype.Repository; | ||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||
| import java.time.Duration; | ||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||
| @Repository | ||||||||||||||||||||||||||||||||||||||||||
| @RequiredArgsConstructor | ||||||||||||||||||||||||||||||||||||||||||
| public class RateLimitRepository { | ||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||
| private final RedisTemplate<String, String> redisTemplate; | ||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||
| private static final String RATE_LIMIT_PREFIX = "ratelimit:"; | ||||||||||||||||||||||||||||||||||||||||||
| private static final String ATTEMPT_PREFIX = "attempts:"; | ||||||||||||||||||||||||||||||||||||||||||
| private static final Duration RATE_LIMIT_DURATION = Duration.ofMinutes(1); | ||||||||||||||||||||||||||||||||||||||||||
| private static final Duration ATTEMPT_DURATION = Duration.ofMinutes(3); | ||||||||||||||||||||||||||||||||||||||||||
| private static final int MAX_ATTEMPTS = 5; | ||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||
| /** 1분에 1번 제한. 제한 초과 시 true 반환 */ | ||||||||||||||||||||||||||||||||||||||||||
| public boolean isRateLimited(String email) { | ||||||||||||||||||||||||||||||||||||||||||
| String key = RATE_LIMIT_PREFIX + email; | ||||||||||||||||||||||||||||||||||||||||||
| Boolean isNew = redisTemplate.opsForValue().setIfAbsent(key, "1", RATE_LIMIT_DURATION); | ||||||||||||||||||||||||||||||||||||||||||
| return !Boolean.TRUE.equals(isNew); | ||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||
| /** 검증 시도 횟수 초과 여부. MAX_ATTEMPTS 이상이면 true 반환 */ | ||||||||||||||||||||||||||||||||||||||||||
| public boolean isAttemptExceeded(String email) { | ||||||||||||||||||||||||||||||||||||||||||
| String key = ATTEMPT_PREFIX + email; | ||||||||||||||||||||||||||||||||||||||||||
| String count = redisTemplate.opsForValue().get(key); | ||||||||||||||||||||||||||||||||||||||||||
| return count != null && Integer.parseInt(count) >= MAX_ATTEMPTS; | ||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+29
to
+33
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.
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||
| /** 검증 실패 시 시도 횟수 증가 */ | ||||||||||||||||||||||||||||||||||||||||||
| public void incrementAttempt(String email) { | ||||||||||||||||||||||||||||||||||||||||||
| String key = ATTEMPT_PREFIX + email; | ||||||||||||||||||||||||||||||||||||||||||
| Long count = redisTemplate.opsForValue().increment(key); | ||||||||||||||||||||||||||||||||||||||||||
| if (count != null && count == 1) { | ||||||||||||||||||||||||||||||||||||||||||
| redisTemplate.expire(key, ATTEMPT_DURATION); | ||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||
| /** 검증 성공 또는 새 코드 발급 시 시도 횟수 초기화 */ | ||||||||||||||||||||||||||||||||||||||||||
| public void resetAttempts(String email) { | ||||||||||||||||||||||||||||||||||||||||||
| redisTemplate.delete(ATTEMPT_PREFIX + email); | ||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,7 +20,7 @@ spring: | |
| mail: | ||
| smtp: | ||
| auth: true | ||
| timeout: 5000 | ||
| timeout: 10000 | ||
| starttls: | ||
| enable: true | ||
| servlet: | ||
|
|
||
150 changes: 150 additions & 0 deletions
150
src/test/java/com/daramg/server/auth/application/MailVerificationServiceImplTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| package com.daramg.server.auth.application; | ||
|
|
||
| import com.daramg.server.auth.domain.EmailPurpose; | ||
| import com.daramg.server.auth.dto.EmailVerificationRequestDto; | ||
| import com.daramg.server.auth.exception.AuthErrorStatus; | ||
| import com.daramg.server.auth.repository.RateLimitRepository; | ||
| import com.daramg.server.auth.repository.VerificationCodeRepository; | ||
| import com.daramg.server.auth.util.MailContentBuilder; | ||
| import com.daramg.server.auth.util.MimeMessageGenerator; | ||
| import com.daramg.server.common.exception.BusinessException; | ||
| import com.daramg.server.user.repository.UserRepository; | ||
| import jakarta.mail.internet.MimeMessage; | ||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Nested; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.api.extension.ExtendWith; | ||
| import org.mockito.InjectMocks; | ||
| import org.mockito.Mock; | ||
| import org.mockito.junit.jupiter.MockitoExtension; | ||
| import org.springframework.mail.javamail.JavaMailSender; | ||
|
|
||
| import java.util.Optional; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThatThrownBy; | ||
| import static org.mockito.ArgumentMatchers.any; | ||
| import static org.mockito.ArgumentMatchers.anyString; | ||
| import static org.mockito.BDDMockito.given; | ||
| import static org.mockito.Mockito.*; | ||
|
|
||
| @ExtendWith(MockitoExtension.class) | ||
| class MailVerificationServiceImplTest { | ||
|
|
||
| @Mock private MimeMessageGenerator mimeMessageGenerator; | ||
| @Mock private MailContentBuilder mailContentBuilder; | ||
| @Mock private JavaMailSender javaMailSender; | ||
| @Mock private VerificationCodeRepository verificationCodeRepository; | ||
| @Mock private RateLimitRepository rateLimitRepository; | ||
| @Mock private UserRepository userRepository; | ||
|
|
||
| @InjectMocks | ||
| private MailVerificationServiceImpl mailVerificationService; | ||
|
|
||
| private static final String TEST_EMAIL = "test@daramg.com"; | ||
|
|
||
| @Nested | ||
| @DisplayName("인증코드 발송 시") | ||
| class SendVerificationEmail { | ||
|
|
||
| @Test | ||
| @DisplayName("새 코드 발급 시 시도 횟수를 초기화하지 않는다") | ||
| void 새_코드_발급_시_시도_횟수_초기화_안됨() throws Exception { | ||
| given(userRepository.existsByEmail(TEST_EMAIL)).willReturn(false); | ||
| given(rateLimitRepository.isRateLimited(TEST_EMAIL)).willReturn(false); | ||
| given(mailContentBuilder.buildVerificationEmail(anyString())).willReturn("<html>code</html>"); | ||
| given(mimeMessageGenerator.generate(anyString(), anyString(), anyString())) | ||
| .willReturn(mock(MimeMessage.class)); | ||
|
|
||
| EmailVerificationRequestDto request = new EmailVerificationRequestDto(null, TEST_EMAIL, EmailPurpose.SIGNUP); | ||
| mailVerificationService.sendVerificationEmail(request); | ||
|
|
||
| verify(rateLimitRepository, never()).resetAttempts(TEST_EMAIL); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("레이트 리밋 초과 시 예외가 발생한다") | ||
| void 레이트_리밋_초과_시_예외_발생() { | ||
| given(userRepository.existsByEmail(TEST_EMAIL)).willReturn(false); | ||
| given(rateLimitRepository.isRateLimited(TEST_EMAIL)).willReturn(true); | ||
|
|
||
| EmailVerificationRequestDto request = new EmailVerificationRequestDto(null, TEST_EMAIL, EmailPurpose.SIGNUP); | ||
|
|
||
| assertThatThrownBy(() -> mailVerificationService.sendVerificationEmail(request)) | ||
| .isInstanceOf(BusinessException.class) | ||
| .hasFieldOrPropertyWithValue("errorCode", AuthErrorStatus.EMAIL_RATE_LIMIT_EXCEEDED); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("이미 가입된 이메일로 SIGNUP 요청 시 예외가 발생한다") | ||
| void 중복_이메일_SIGNUP_예외_발생() { | ||
| given(userRepository.existsByEmail(TEST_EMAIL)).willReturn(true); | ||
|
|
||
| EmailVerificationRequestDto request = new EmailVerificationRequestDto(null, TEST_EMAIL, EmailPurpose.SIGNUP); | ||
|
|
||
| assertThatThrownBy(() -> mailVerificationService.sendVerificationEmail(request)) | ||
| .isInstanceOf(BusinessException.class) | ||
| .hasFieldOrPropertyWithValue("errorCode", AuthErrorStatus.DUPLICATE_EMAIL); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("미가입 이메일로 PASSWORD_RESET 요청 시 예외가 발생한다") | ||
| void 미가입_이메일_PASSWORD_RESET_예외_발생() { | ||
| given(userRepository.existsByEmail(TEST_EMAIL)).willReturn(false); | ||
|
|
||
| EmailVerificationRequestDto request = new EmailVerificationRequestDto(null, TEST_EMAIL, EmailPurpose.PASSWORD_RESET); | ||
|
|
||
| assertThatThrownBy(() -> mailVerificationService.sendVerificationEmail(request)) | ||
| .isInstanceOf(BusinessException.class) | ||
| .hasFieldOrPropertyWithValue("errorCode", AuthErrorStatus.EMAIL_NOT_REGISTERED); | ||
| } | ||
| } | ||
|
|
||
| @Nested | ||
| @DisplayName("인증코드 검증 시") | ||
| class VerifyEmailWithCode { | ||
|
|
||
| @Test | ||
| @DisplayName("인증 성공 시 시도 횟수를 초기화한다") | ||
| void 인증_성공_시_시도_횟수_초기화() { | ||
| given(rateLimitRepository.isAttemptExceeded(TEST_EMAIL)).willReturn(false); | ||
| given(verificationCodeRepository.findByEmail(TEST_EMAIL)).willReturn(Optional.of("123456")); | ||
| doNothing().when(verificationCodeRepository).deleteByEmail(TEST_EMAIL); | ||
| doNothing().when(rateLimitRepository).resetAttempts(TEST_EMAIL); | ||
|
|
||
| com.daramg.server.auth.dto.CodeVerificationRequestDto request = | ||
| new com.daramg.server.auth.dto.CodeVerificationRequestDto(TEST_EMAIL, "123456"); | ||
| mailVerificationService.verifyEmailWithCode(request); | ||
|
|
||
| verify(rateLimitRepository).resetAttempts(TEST_EMAIL); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("검증 시도 횟수 초과 시 예외가 발생한다") | ||
| void 시도_횟수_초과_시_예외_발생() { | ||
| given(rateLimitRepository.isAttemptExceeded(TEST_EMAIL)).willReturn(true); | ||
|
|
||
| com.daramg.server.auth.dto.CodeVerificationRequestDto request = | ||
| new com.daramg.server.auth.dto.CodeVerificationRequestDto(TEST_EMAIL, "123456"); | ||
|
|
||
| assertThatThrownBy(() -> mailVerificationService.verifyEmailWithCode(request)) | ||
| .isInstanceOf(BusinessException.class) | ||
| .hasFieldOrPropertyWithValue("errorCode", AuthErrorStatus.VERIFICATION_ATTEMPT_EXCEEDED); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("잘못된 인증코드 입력 시 시도 횟수가 증가한다") | ||
| void 틀린_코드_시도_횟수_증가() { | ||
| given(rateLimitRepository.isAttemptExceeded(TEST_EMAIL)).willReturn(false); | ||
| given(verificationCodeRepository.findByEmail(TEST_EMAIL)).willReturn(Optional.of("123456")); | ||
|
|
||
| com.daramg.server.auth.dto.CodeVerificationRequestDto request = | ||
| new com.daramg.server.auth.dto.CodeVerificationRequestDto(TEST_EMAIL, "999999"); | ||
|
|
||
| assertThatThrownBy(() -> mailVerificationService.verifyEmailWithCode(request)) | ||
| .isInstanceOf(BusinessException.class) | ||
| .hasFieldOrPropertyWithValue("errorCode", AuthErrorStatus.CODE_VERIFICATION_FAILED); | ||
|
|
||
| verify(rateLimitRepository).incrementAttempt(TEST_EMAIL); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
verifyEmailWithCode메서드에서 여러 번의executeRedisOperationVoid및executeRedisOperation호출이 있습니다. 이는 각 호출마다 Redis 연결 및 예외 처리 오버헤드를 발생시켜 비효율적입니다. 관련된 모든 Redis 작업을 단일executeRedisOperationVoid블록으로 묶으면 코드가 더 간결해지고 성능도 향상됩니다.