Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/main/java/com/gcp/domain/gcp/aop/RequiredValidToken.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.gcp.domain.gcp.aop;


import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequiredValidToken {
}
46 changes: 46 additions & 0 deletions src/main/java/com/gcp/domain/gcp/aop/TokenAspect.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.gcp.domain.gcp.aop;


import com.gcp.domain.discord.entity.DiscordUser;
import com.gcp.domain.discord.repository.DiscordUserRepository;
import com.gcp.domain.discord.service.DiscordUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class TokenAspect {

private final DiscordUserRepository discordUserRepository;
private final DiscordUserService discordUserService;

@Around("@within(com.gcp.domain.gcp.aop.RequiredValidToken) && args(userId, guildId, ..)")
public Object validateAndRefreshToken(ProceedingJoinPoint joinPoint, String userId, String guildId) throws Throwable {

LocalDateTime tokenExp = discordUserRepository.findAccessTokenExpByUserIdAndGuildId(userId, guildId)
.orElseThrow();

if (tokenExp.isBefore(LocalDateTime.now())) {
DiscordUser discordUser = discordUserRepository.findByUserIdAndGuildId(userId, guildId)
.orElseThrow();

Map<String, Object> reissued = discordUserService.refreshAccessToken(discordUser.getGoogleRefreshToken());

Comment on lines +36 to +37
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

보안: 리프레시 토큰 로그 출력 금지 권고

해당 어드바이스는 만료 시 매번 refreshAccessToken(...)을 호출합니다. 현재 DiscordUserService.refreshAccessToken 내부에서 refreshToken을 로그(INFO)로 찍고 있어 민감정보 유출 위험이 큽니다. 즉시 제거를 권장합니다.

수정 제안 (다른 파일, 참고용):

// src/main/java/com/gcp/domain/discord/service/DiscordUserService.java
public Map<String, Object> refreshAccessToken(String refreshToken) {
    String url = "https://oauth2.googleapis.com/token";
-   log.info("{}", refreshToken); // 민감정보 로그 출력 금지
+   // 로그 미출력 또는 마스킹 처리 고려
    ...
}
🤖 Prompt for AI Agents
In src/main/java/com/gcp/domain/gcp/aop/TokenAspect.java around lines 36 to 37,
the code calls discordUserService.refreshAccessToken(...) which currently logs
the raw refresh token inside DiscordUserService; remove any logging of the full
refresh token (or replace with a non-sensitive indicator/masked value) inside
DiscordUserService.refreshAccessToken and any other methods it calls, ensure
only non-sensitive info (e.g., "refresh token present" or masked substring) is
logged if needed, and run a quick grep to delete other occurrences of logging
the refresh token across the codebase.

discordUser.updateAccessToken((String) reissued.get("access_token"));
discordUser.updateAccessTokenExpiration(
LocalDateTime.now().plusSeconds((Integer) reissued.get("expires_in"))
);
}
Comment on lines +32 to +42
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

토큰 업데이트 영속화 누락 및 expires_in 캐스팅 위험

  • 문제 1: discordUser.updateAccessToken/Expiration 호출 후 저장(save)을 하지 않아, 트랜잭션 경계/어드바이스 순서에 따라 DB 반영이 누락될 수 있습니다. 이 경우 매 호출마다 재발급이 반복되거나, 서비스 메서드에서 여전히 만료된 토큰을 읽을 수 있습니다.
  • 문제 2: (Integer) 캐스팅은 JSON 파서가 Long/Double 등으로 매핑할 때 ClassCastException을 유발할 수 있습니다. Number로 처리하세요.
  • 문제 3: 만료 시각 계산 시 LocalDateTime.now()의 시스템 기본 타임존을 사용해, OAuth2AuthenticationSuccessHandler에서 Asia/Seoul로 저장한 시각과 불일치 가능성이 있습니다(서버 TZ가 다를 경우). 동일 TZ로 맞추거나 UTC로 일원화하세요.
  • 문제 4: refreshToken null/공백 방어 로직이 없습니다.

아래와 같이 보완을 권장합니다.

@@
-        if (tokenExp.isBefore(LocalDateTime.now())) {
+        if (tokenExp.isBefore(LocalDateTime.now())) {
             DiscordUser discordUser = discordUserRepository.findByUserIdAndGuildId(userId, guildId)
                     .orElseThrow();
 
-            Map<String, Object> reissued = discordUserService.refreshAccessToken(discordUser.getGoogleRefreshToken());
+            String refreshToken = discordUser.getGoogleRefreshToken();
+            if (refreshToken == null || refreshToken.isBlank()) {
+                throw new IllegalStateException(
+                        String.format("리프레시 토큰이 없습니다: userId=%s, guildId=%s", userId, guildId)
+                );
+            }
+            Map<String, Object> reissued = discordUserService.refreshAccessToken(refreshToken);
 
-            discordUser.updateAccessToken((String) reissued.get("access_token"));
-            discordUser.updateAccessTokenExpiration(
-                    LocalDateTime.now().plusSeconds((Integer) reissued.get("expires_in"))
-            );
+            discordUser.updateAccessToken((String) reissued.get("access_token"));
+            Number expiresInNum = (Number) reissued.get("expires_in");
+            long expiresInSec = (expiresInNum != null) ? expiresInNum.longValue() : 3600L;
+            discordUser.updateAccessTokenExpiration(
+                    // OAuth2AuthenticationSuccessHandler와 동일하게 Asia/Seoul 기준으로 저장
+                    LocalDateTime.now(java.time.ZoneId.of("Asia/Seoul")).plusSeconds(expiresInSec)
+            );
+            // 트랜잭션 경계/어드바이스 순서와 무관하게 영속화 보장
+            discordUserRepository.save(discordUser);
         }

추가 메모:

  • 동시다발 호출 시 다중 재발급 경쟁이 발생할 수 있습니다. 사용자별 락(분산락/DB-Lock/Optimistic Lock) 도입이나 더블체크(재조회 후 여전히 만료인 경우에만 갱신)로 개선을 고려해보세요.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (tokenExp.isBefore(LocalDateTime.now())) {
DiscordUser discordUser = discordUserRepository.findByUserIdAndGuildId(userId, guildId)
.orElseThrow();
Map<String, Object> reissued = discordUserService.refreshAccessToken(discordUser.getGoogleRefreshToken());
discordUser.updateAccessToken((String) reissued.get("access_token"));
discordUser.updateAccessTokenExpiration(
LocalDateTime.now().plusSeconds((Integer) reissued.get("expires_in"))
);
}
if (tokenExp.isBefore(LocalDateTime.now())) {
DiscordUser discordUser = discordUserRepository.findByUserIdAndGuildId(userId, guildId)
.orElseThrow();
String refreshToken = discordUser.getGoogleRefreshToken();
if (refreshToken == null || refreshToken.isBlank()) {
throw new IllegalStateException(
String.format("리프레시 토큰이 없습니다: userId=%s, guildId=%s", userId, guildId)
);
}
Map<String, Object> reissued = discordUserService.refreshAccessToken(refreshToken);
discordUser.updateAccessToken((String) reissued.get("access_token"));
Number expiresInNum = (Number) reissued.get("expires_in");
long expiresInSec = (expiresInNum != null) ? expiresInNum.longValue() : 3600L;
discordUser.updateAccessTokenExpiration(
// OAuth2AuthenticationSuccessHandler와 동일하게 Asia/Seoul 기준으로 저장
LocalDateTime.now(java.time.ZoneId.of("Asia/Seoul")).plusSeconds(expiresInSec)
);
// 트랜잭션 경계/어드바이스 순서와 무관하게 영속화 보장
discordUserRepository.save(discordUser);
}
🤖 Prompt for AI Agents
In src/main/java/com/gcp/domain/gcp/aop/TokenAspect.java around lines 32-42, the
token refresh block needs these fixes: guard against null/blank refresh token
and bail/throw before calling refresh; when reading expires_in treat it as a
Number (Number expiresNum = (Number) reissued.get("expires_in")) and use
expiresNum.longValue() to avoid ClassCastException; compute the new expiration
using a consistent ZoneId (e.g., ZoneId.of("Asia/Seoul") or ZoneOffset.UTC)
instead of LocalDateTime.now() with system default; after updating discordUser
fields persist the change via repository.save(discordUser) (and consider
reloading the user and double-checking expiration to avoid race-condition double
refreshes or implement a user-level lock/optimistic check).


return joinPoint.proceed();
}
}
13 changes: 3 additions & 10 deletions src/main/java/com/gcp/domain/gcp/service/GcpService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
import com.gcp.domain.discord.entity.DiscordUser;
import com.gcp.domain.discord.repository.DiscordUserRepository;
import com.gcp.domain.discord.service.DiscordUserService;
import com.gcp.domain.gcp.aop.RequiredValidToken;
import com.gcp.domain.gcp.dto.ProjectZoneDto;
import com.gcp.domain.gcp.repository.GcpProjectRepository;

import com.gcp.domain.gcp.util.GcpImageUtil;
import com.gcp.domain.oauth2.util.TokenEncryptConverter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -24,13 +24,13 @@


import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
@RequiredValidToken
public class GcpService {

private final RestTemplate restTemplate = new RestTemplate();
Expand Down Expand Up @@ -216,16 +216,8 @@ public List<Map<String, String>> getVmList(String userId, String guildId) {
public List<String> getProjectIds(String userId, String guildId) {
try {
String url = "https://cloudresourcemanager.googleapis.com/v1/projects";
LocalDateTime tokenExp = discordUserRepository.findAccessTokenExpByUserIdAndGuildId(userId, guildId).orElseThrow();
if(tokenExp.isBefore(LocalDateTime.now())){
DiscordUser discordUser = discordUserRepository.findByUserIdAndGuildId(userId, guildId).orElseThrow();
Map<String, Object> reissued = discordUserService.refreshAccessToken(discordUser.getGoogleRefreshToken());
discordUser.updateAccessToken((String) reissued.get("access_token"));
discordUser.updateAccessTokenExpiration(LocalDateTime.now().plusSeconds((Integer) reissued.get("expires_in")));
}
String accessToken = discordUserRepository.findAccessTokenByUserIdAndGuildId(userId, guildId).orElseThrow();


HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
headers.setContentType(MediaType.APPLICATION_JSON);
Expand Down Expand Up @@ -386,6 +378,7 @@ public String createVM(String userId, String guildId, String vmName, String mach
throw new RuntimeException("Compute API (인스턴스 생성) 호출 도중 에러 발생: ", e);
}
}

public List<Map<String, Object>> getFirewallRules(String userId, String guildId) {
try {
String url = String.format("https://compute.googleapis.com/compute/v1/projects/%s/global/firewalls", PROJECT_ID);
Expand Down