Skip to content

[feat] 메일 발송 비동기 처리 전환#91

Merged
k3vin7 merged 1 commit intomainfrom
feat/auth
Feb 28, 2026
Merged

[feat] 메일 발송 비동기 처리 전환#91
k3vin7 merged 1 commit intomainfrom
feat/auth

Conversation

@k3vin7
Copy link
Contributor

@k3vin7 k3vin7 commented Feb 28, 2026

Summary

  • AsyncMailSender 컴포넌트 추가 — @Async("mailTaskExecutor")로 SMTP 발송 백그라운드 처리
  • AsyncConfig 추가 — @EnableAsyncmailTaskExecutor 스레드 풀 설정 (core 2, max 5, queue 100)
  • MailVerificationServiceImpl 수정 — 레이트 리밋·코드 저장은 동기 유지, SMTP 발송만 비동기 위임
  • 발송 실패 시 사용자에게 에러 전파 없이 log.error만 기록 → FE 재발송 버튼으로 재시도
  • MailVerificationServiceImplTest 수정 — AsyncMailSender mock으로 교체

Test plan

  • MailVerificationServiceImplTest 전체 통과 확인
  • 인증 코드 발송 요청 후 즉시 200 응답 확인
  • SMTP 실패 시 서버 로그에 에러 기록 확인
  • 1분 레이트 리밋 동작 확인

@gemini-code-assist
Copy link

Summary of Changes

Hello, 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는 이메일 발송 기능을 비동기 처리로 전환하여 사용자 경험을 개선하고 서버의 응답성을 향상시키는 것을 목표로 합니다. 기존에는 이메일 발송이 동기적으로 처리되어 응답 지연을 유발할 수 있었으나, 이제는 별도의 스레드 풀에서 메일 발송 작업을 처리함으로써 메인 스레드의 부하를 줄이고 즉각적인 응답을 제공할 수 있게 됩니다. 또한, 메일 발송 실패 시에도 서비스의 안정성을 유지하도록 에러 처리 방식이 개선되었습니다.

Highlights

  • 비동기 메일 발송 컴포넌트 추가: AsyncMailSender 컴포넌트가 추가되어 @Async("mailTaskExecutor")를 통해 SMTP 발송을 백그라운드에서 처리합니다.
  • 비동기 설정 추가: AsyncConfig가 추가되어 @EnableAsync를 활성화하고 mailTaskExecutor 스레드 풀을 설정합니다 (core 2, max 5, queue 100).
  • 메일 검증 서비스 로직 개선: MailVerificationServiceImpl은 레이트 리밋 및 인증 코드 저장은 동기적으로 유지하되, SMTP 발송만 비동기 AsyncMailSender로 위임하도록 수정되었습니다.
  • 메일 발송 실패 처리: 메일 발송 실패 시 사용자에게 에러를 전파하지 않고 log.error만 기록하며, 프론트엔드에서 재발송 버튼으로 재시도할 수 있도록 합니다.
  • 테스트 코드 업데이트: MailVerificationServiceImplTestAsyncMailSender를 Mock으로 교체하여 테스트를 수행하도록 수정되었습니다.

🧠 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/AsyncMailSender.java
    • 비동기 이메일 발송을 담당하는 새로운 컴포넌트가 추가되었습니다.
    • @Async("mailTaskExecutor") 어노테이션을 사용하여 sendVerificationCode 메서드가 비동기적으로 실행되도록 설정되었습니다.
    • 메일 발송 실패 시 예외를 catch하여 로그만 기록하고 사용자에게 에러를 전파하지 않도록 처리되었습니다.
  • src/main/java/com/daramg/server/auth/application/MailVerificationServiceImpl.java
    • 기존의 MimeMessageGenerator, MailContentBuilder, JavaMailSender 의존성이 제거되고 AsyncMailSenderRateLimitRepository가 주입되었습니다.
    • sendVerificationEmail 메서드 내에서 이메일 발송 목적에 따른 예외 처리가 AuthErrorStatusUserErrorStatus를 사용하도록 변경되었습니다.
    • sendForSignup 메서드에 이미 가입된 이메일인지 확인하는 로직이 추가되었습니다.
    • sendVerificationCode 메서드에서 레이트 리밋 검사 로직이 추가되었고, 실제 메일 발송은 asyncMailSender로 위임되었습니다.
    • verifyEmailWithCode 메서드에 인증 시도 횟수 초과 여부를 확인하는 로직과 잘못된 코드 입력 시 시도 횟수를 증가시키는 로직이 추가되었습니다.
    • 인증 성공 시 시도 횟수를 초기화하는 로직이 추가되었습니다.
  • src/main/java/com/daramg/server/common/config/AsyncConfig.java
    • 비동기 처리를 위한 설정 클래스가 추가되었습니다.
    • @EnableAsync 어노테이션을 통해 비동기 기능을 활성화했습니다.
    • mailTaskExecutor라는 이름의 ThreadPoolTaskExecutor 빈을 정의하여 메일 발송 전용 스레드 풀을 구성했습니다 (core 2, max 5, queue 100).
  • src/test/java/com/daramg/server/auth/application/MailVerificationServiceImplTest.java
    • MailVerificationServiceImpl에 대한 테스트 파일이 추가되었습니다.
    • AsyncMailSender를 Mock으로 처리하여 비동기 메일 발송 로직을 테스트에서 분리했습니다.
    • 인증 코드 발송 시 레이트 리밋 초과, 중복 이메일, 미가입 이메일 등의 시나리오에 대한 테스트 케이스가 추가되었습니다.
    • 인증 코드 검증 시 시도 횟수 초기화, 시도 횟수 초과, 잘못된 코드 입력 시 시도 횟수 증가 등의 시나리오에 대한 테스트 케이스가 추가되었습니다.
Activity
  • MailVerificationServiceImplTest 전체 통과 확인.
  • 인증 코드 발송 요청 후 즉시 200 응답 확인.
  • SMTP 실패 시 서버 로그에 에러 기록 확인.
  • 1분 레이트 리밋 동작 확인.
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은 메일 발송 로직을 비동기로 전환하여 사용자 경험을 개선하는 좋은 변경입니다. 하지만, 인증 서비스의 보안 및 규정 준수를 위해 해결해야 할 몇 가지 중요한 보안 취약점이 발견되었습니다. 특히, 인증 시도 제한의 레이스 컨디션으로 인해 무차별 대입 공격이 가능하며, 이메일 발송 속도 제한의 누락된 증가 로직으로 인해 무제한 이메일 요청이 발생할 수 있습니다. 또한, 개인 식별 정보(PII)인 이메일 주소가 실패 시 평문으로 로깅되고 있습니다. 전반적으로 코드 구조는 잘 개선되었으나, 예외 로깅을 좀 더 상세하게 하고 에러 코드 사용의 일관성을 높이는 방향으로 수정하면 더 좋을 것 같습니다.

Comment on lines 76 to 86
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()));

Choose a reason for hiding this comment

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

security-high high

The verifyEmailWithCode method implements rate limiting for verification attempts using a "check-then-act" pattern that is not atomic. The check for exceeded attempts happens on line 76, while the increment of the attempt counter happens on line 86 after the code verification fails. An attacker can send multiple concurrent requests that all pass the isAttemptExceeded check before any of them increment the attempt counter, effectively bypassing the brute-force protection. This could allow an attacker to attempt more verification codes than intended within a short window.

Remediation: The check and increment operations should be performed atomically. Consider using a Redis-based atomic increment and check (e.g., using a Lua script or the INCR command followed by a check) to ensure the rate limit is enforced correctly across concurrent requests.


executeRedisOperationVoid(() -> {
verificationCodeRepository.save(request.getEmail(), verificationCode);
if (rateLimitRepository.isRateLimited(request.getEmail())) {

Choose a reason for hiding this comment

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

security-high high

The sendVerificationCode method checks if the email sending is rate-limited on line 60, but it never seems to increment the rate limit counter. In contrast, the verifyEmailWithCode method explicitly calls incrementAttempt on line 86. Without an increment operation, the isRateLimited check will always return false (assuming it's a simple check), allowing an attacker to send an unlimited number of verification emails. This can lead to resource exhaustion, increased costs, and potential blacklisting of the mail server's IP address.

Remediation: Ensure that the rate limit counter is incremented every time a verification email is successfully requested. This should be done atomically with the check to avoid race conditions.

);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
log.error("이메일 발송 실패 - email: {}, error: {}", email, e.getMessage());

Choose a reason for hiding this comment

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

security-medium medium

이메일 발송 실패 시 사용자 이메일 주소가 평문으로 로깅되고 있습니다. 이메일 주소는 개인 식별 정보(PII)로 간주되며, PII를 평문으로 로깅하는 것은 보안 및 규정 준수 문제를 야기할 수 있습니다. 또한, 비동기 작업에서 예외 발생 시 원인 파악을 용이하게 하기 위해 전체 스택 트레이스를 로깅하는 것이 좋습니다. e.getMessage()만 기록할 경우 상세 정보를 놓칠 수 있습니다. SLF4J의 로거는 마지막 인자로 Throwable을 받으면 스택 트레이스를 자동으로 출력해줍니다. 이메일 주소는 마스킹 처리하고, 예외 발생 시 스택 트레이스를 함께 로깅하도록 수정해주세요.

Suggested change
log.error("이메일 발송 실패 - email: {}, error: {}", email, e.getMessage());
log.error("이메일 발송 실패 - email: {}, error: {}", email.replaceAll("(?<=.{3}).(?=.*@)", "*"), e.getMessage(), e);


private void sendForSignup(EmailVerificationRequestDto request) {
if (userRepository.existsByEmail(request.getEmail())) {
throw new BusinessException(AuthErrorStatus.DUPLICATE_EMAIL);

Choose a reason for hiding this comment

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

medium

sendForEmailChange 메서드(53라인)에서는 중복 이메일에 대해 UserErrorStatus.DUPLICATE_EMAIL을 사용하고 있습니다. 코드의 일관성을 높이고 에러 코드의 역할을 명확히 하기 위해, 회원가입 시 중복 이메일 검사에서도 동일한 UserErrorStatus.DUPLICATE_EMAIL을 사용하도록 변경하는 것을 제안합니다. 중복 이메일은 인증(Auth)보다는 사용자(User) 도메인의 책임에 더 가깝다고 볼 수 있습니다.

이 변경사항을 적용하려면 MailVerificationServiceImplTest중복_이메일_SIGNUP_예외_발생 테스트 케이스도 함께 수정해야 합니다.

Suggested change
throw new BusinessException(AuthErrorStatus.DUPLICATE_EMAIL);
throw new BusinessException(UserErrorStatus.DUPLICATE_EMAIL);

@k3vin7 k3vin7 merged commit 7065792 into main Feb 28, 2026
1 check passed
@k3vin7 k3vin7 deleted the feat/auth branch February 28, 2026 14:06
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