Skip to content

[feat] 메일 인증 보안 강화#89

Merged
k3vin7 merged 3 commits intomainfrom
feat/mailVerification
Feb 26, 2026
Merged

[feat] 메일 인증 보안 강화#89
k3vin7 merged 3 commits intomainfrom
feat/mailVerification

Conversation

@k3vin7
Copy link
Contributor

@k3vin7 k3vin7 commented Feb 26, 2026

Summary

  • 재발송 레이트 리밋 추가 (이메일 기준 1분에 1회)
  • 인증번호 검증 시도 횟수 제한 추가 (5회 초과 시 차단)
  • 회원가입 시 중복 이메일 인증 차단
  • 발송 실패 로그 추가
  • SMTP timeout 5초 → 10초 변경

Test plan

  • 1분 내 재발송 요청 시 429 응답 확인
  • 인증번호 5회 초과 시도 시 429 응답 확인
  • 이미 가입된 이메일로 회원가입 인증 요청 시 409 응답 확인
  • 정상 인증 플로우 동작 확인

@gemini-code-assist
Copy link

Summary of Changes

Hello @k3vin7, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

이 Pull Request는 메일 인증 시스템의 보안을 강화하기 위한 여러 개선 사항을 포함합니다. 이메일 재발송 및 인증번호 검증에 대한 레이트 리밋을 도입하여 악의적인 시도를 방지하고, 회원가입 시 중복 이메일 인증 요청을 차단하여 데이터 무결성을 높였습니다. 또한, 이메일 발송 실패 시 로깅을 추가하고 SMTP 타임아웃을 조정하여 시스템 안정성을 향상시켰습니다.

Highlights

  • 이메일 재발송 레이트 리밋 추가: 이메일 재발송에 대한 분당 1회 레이트 리밋이 추가되었습니다.
  • 인증번호 검증 시도 횟수 제한: 인증번호 검증 시도 횟수가 5회로 제한되었으며, 초과 시 차단됩니다.
  • 회원가입 시 중복 이메일 인증 차단: 회원가입 시 이미 존재하는 이메일로 인증을 요청하는 경우 차단됩니다.
  • 이메일 발송 실패 로그 추가: 이메일 발송 실패 시 로그가 기록되도록 추가되었습니다.
  • SMTP 타임아웃 변경: SMTP 타임아웃 설정이 5초에서 10초로 연장되었습니다.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/main/java/com/daramg/server/auth/application/MailVerificationServiceImpl.java
    • RateLimitRepository를 주입하여 이메일 발송 및 인증 시도에 대한 레이트 리밋 로직을 추가했습니다.
    • 회원가입 시 중복 이메일 인증 요청을 확인하고 DUPLICATE_EMAIL 예외를 발생시키는 로직을 추가했습니다.
    • 이메일 발송 전 레이트 리밋을 확인하고 초과 시 EMAIL_RATE_LIMIT_EXCEEDED 예외를 발생시킵니다.
    • 이메일 발송 성공 시 rateLimitRepository.resetAttempts를 호출하여 시도 횟수를 초기화합니다.
    • 이메일 발송 실패 시 에러 로그를 기록하도록 변경했습니다.
    • 인증번호 검증 전 시도 횟수를 확인하고 초과 시 VERIFICATION_ATTEMPT_EXCEEDED 예외를 발생시킵니다.
    • 인증 실패 시 rateLimitRepository.incrementAttempt를 호출하여 시도 횟수를 증가시킵니다.
    • 인증 성공 시 rateLimitRepository.resetAttempts를 호출하여 시도 횟수를 초기화합니다.
  • src/main/java/com/daramg/server/auth/exception/AuthErrorStatus.java
    • EMAIL_RATE_LIMIT_EXCEEDEDVERIFICATION_ATTEMPT_EXCEEDED 두 가지 새로운 에러 상태 코드를 추가했습니다.
  • src/main/java/com/daramg/server/auth/repository/RateLimitRepository.java
    • 이메일 기반의 레이트 리밋 및 인증 시도 횟수를 관리하는 RateLimitRepository 클래스를 새로 추가했습니다.
    • Redis를 사용하여 이메일당 1분 재발송 제한 및 5회 인증 시도 제한 로직을 구현했습니다.
  • src/main/resources/application.yml
    • SMTP 메일 발송 타임아웃을 5000ms에서 10000ms로 변경했습니다.
  • src/test/java/com/daramg/server/auth/presentation/AuthControllerTest.java
    • AuthErrorStatusBusinessException 임포트를 추가했습니다.
    • doThrow Mockito 메서드 임포트를 추가했습니다.
    • 이미 가입된 이메일로 회원가입 인증 요청 시 409 Conflict 응답을 확인하는 테스트 케이스를 추가했습니다.
    • 레이트 리밋 초과 시 인증 코드 메일 발송 실패에 대한 429 Too Many Requests 응답을 확인하는 테스트 케이스를 추가했습니다.
    • 검증 시도 횟수 초과 시 이메일 인증 실패에 대한 429 Too Many Requests 응답을 확인하는 테스트 케이스를 추가했습니다.
Activity
  • 현재까지 이 Pull Request에 대한 사람의 활동(댓글, 리뷰 등)은 없습니다.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

이번 PR은 메일 인증 플로우에 재발송 속도 제한, 인증 시도 횟수 제한 등 중요한 보안 강화를 추가하여 서비스의 안정성을 크게 향상시켰습니다. 전반적으로 좋은 변경이라고 생각합니다. 몇 가지 코드 개선 제안을 포함하였으니 검토 부탁드립니다. RateLimitRepository에서 발생할 수 있는 NumberFormatException을 처리하여 안정성을 더욱 높이고, MailVerificationServiceImpl의 여러 Redis 호출을 하나로 통합하여 코드 효율성과 가독성을 개선하는 것을 제안합니다.

Comment on lines +29 to +33
public boolean isAttemptExceeded(String email) {
String key = ATTEMPT_PREFIX + email;
String count = redisTemplate.opsForValue().get(key);
return count != null && Integer.parseInt(count) >= MAX_ATTEMPTS;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

isAttemptExceeded 메서드에서 Redis로부터 가져온 count 값을 Integer.parseInt()로 변환하고 있습니다. 만약 Redis에 저장된 값이 숫자가 아닌 경우 NumberFormatException이 발생하여 서버 오류(500)로 이어질 수 있습니다. 안정성을 높이기 위해 try-catch 블록을 사용하여 예외를 처리하는 것이 좋습니다. 예외 발생 시 에러를 기록하고, 손상된 키를 삭제하여 문제를 해결할 수 있습니다.

Suggested change
public boolean isAttemptExceeded(String email) {
String key = ATTEMPT_PREFIX + email;
String count = redisTemplate.opsForValue().get(key);
return count != null && Integer.parseInt(count) >= MAX_ATTEMPTS;
}
public boolean isAttemptExceeded(String email) {
String key = ATTEMPT_PREFIX + email;
String count = redisTemplate.opsForValue().get(key);
if (count == null) {
return false;
}
try {
return Integer.parseInt(count) >= MAX_ATTEMPTS;
} catch (NumberFormatException e) {
// Consider adding a logger to record this unexpected event.
redisTemplate.delete(key);
return false;
}
}

Comment on lines +97 to 115
executeRedisOperationVoid(() -> {
if (rateLimitRepository.isAttemptExceeded(request.getEmail())) {
throw new BusinessException(AuthErrorStatus.VERIFICATION_ATTEMPT_EXCEEDED);
}
});

String storedCode = executeRedisOperation(() ->
verificationCodeRepository.findByEmail(request.getEmail()).orElse(null)
);

if (storedCode == null || !storedCode.equals(request.getVerificationCode())) {
executeRedisOperationVoid(() -> rateLimitRepository.incrementAttempt(request.getEmail()));
throw new BusinessException(AuthErrorStatus.CODE_VERIFICATION_FAILED);
}

executeRedisOperationVoid(() -> {
verificationCodeRepository.deleteByEmail(request.getEmail());
rateLimitRepository.resetAttempts(request.getEmail());
});

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

verifyEmailWithCode 메서드에서 여러 번의 executeRedisOperationVoidexecuteRedisOperation 호출이 있습니다. 이는 각 호출마다 Redis 연결 및 예외 처리 오버헤드를 발생시켜 비효율적입니다. 관련된 모든 Redis 작업을 단일 executeRedisOperationVoid 블록으로 묶으면 코드가 더 간결해지고 성능도 향상됩니다.

        executeRedisOperationVoid(() -> {
            if (rateLimitRepository.isAttemptExceeded(request.getEmail())) {
                throw new BusinessException(AuthErrorStatus.VERIFICATION_ATTEMPT_EXCEEDED);
            }

            String storedCode = verificationCodeRepository.findByEmail(request.getEmail()).orElse(null);

            if (storedCode == null || !storedCode.equals(request.getVerificationCode())) {
                rateLimitRepository.incrementAttempt(request.getEmail());
                throw new BusinessException(AuthErrorStatus.CODE_VERIFICATION_FAILED);
            }

            verificationCodeRepository.deleteByEmail(request.getEmail());
            rateLimitRepository.resetAttempts(request.getEmail());
        });

@k3vin7 k3vin7 merged commit 08fffa0 into main Feb 26, 2026
1 check passed
@k3vin7 k3vin7 deleted the feat/mailVerification branch February 26, 2026 08:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant