|
| 1 | +package com.stackup.stackup.github.application; |
| 2 | + |
| 3 | +import static org.assertj.core.api.Assertions.assertThat; |
| 4 | +import static org.assertj.core.api.Assertions.assertThatThrownBy; |
| 5 | +import static org.mockito.Mockito.when; |
| 6 | + |
| 7 | +import com.stackup.stackup.common.exception.ApiErrorCode; |
| 8 | +import com.stackup.stackup.common.exception.DomainException; |
| 9 | +import com.stackup.stackup.github.infrastructure.GithubTokenCipher; |
| 10 | +import com.stackup.stackup.user.domain.User; |
| 11 | +import com.stackup.stackup.user.domain.UserRepository; |
| 12 | +import java.util.Optional; |
| 13 | +import org.junit.jupiter.api.Test; |
| 14 | +import org.junit.jupiter.api.extension.ExtendWith; |
| 15 | +import org.mockito.InjectMocks; |
| 16 | +import org.mockito.Mock; |
| 17 | +import org.mockito.junit.jupiter.MockitoExtension; |
| 18 | + |
| 19 | +/** |
| 20 | + * AI 서버가 레포 분석 시점에 위임받는 GitHub access token 은 `repo` 스코프다 — |
| 21 | + * 비공개 레포까지 읽을 수 있는 살아있는 자격증명이라 위임 조건이 좁아야 한다. |
| 22 | + */ |
| 23 | +@ExtendWith(MockitoExtension.class) |
| 24 | +class InternalGithubTokenServiceTest { |
| 25 | + |
| 26 | + @Mock UserRepository userRepository; |
| 27 | + @Mock GithubTokenCipher tokenCipher; |
| 28 | + @InjectMocks InternalGithubTokenService service; |
| 29 | + |
| 30 | + @Test |
| 31 | + void returnsDecryptedTokenForActiveUser() { |
| 32 | + User user = User.createGithubUser(1L, "u", null, null, "enc"); |
| 33 | + when(userRepository.findByIdAndDeletedFalse(1L)).thenReturn(Optional.of(user)); |
| 34 | + when(tokenCipher.decrypt("enc")).thenReturn("gho_plain"); |
| 35 | + |
| 36 | + assertThat(service.fetchPlainAccessToken(1L)).isEqualTo("gho_plain"); |
| 37 | + } |
| 38 | + |
| 39 | + // 탈퇴한 계정은 삭제 여부에서 먼저 막는다. 토큰이 비어 있어서 막히는 것에만 기대면 |
| 40 | + // 백필 전 데이터·향후 실수에 그대로 뚫린다. |
| 41 | + @Test |
| 42 | + void refusesWithdrawnUserEvenIfTokenRowStillPresent() { |
| 43 | + when(userRepository.findByIdAndDeletedFalse(1L)).thenReturn(Optional.empty()); |
| 44 | + |
| 45 | + assertThatThrownBy(() -> service.fetchPlainAccessToken(1L)) |
| 46 | + .isInstanceOf(DomainException.class) |
| 47 | + .extracting(e -> ((DomainException) e).getErrorCode()) |
| 48 | + .isEqualTo(ApiErrorCode.USER_NOT_FOUND); |
| 49 | + } |
| 50 | + |
| 51 | + // Google 로 가입한 계정은 GitHub 토큰이 없다 — NPE 가 500 으로 새지 않게 도메인 에러로. |
| 52 | + @Test |
| 53 | + void refusesGoogleOnlyAccountWithDomainError() { |
| 54 | + User google = User.createGoogleUser("g-1", "u", null, null); |
| 55 | + when(userRepository.findByIdAndDeletedFalse(1L)).thenReturn(Optional.of(google)); |
| 56 | + |
| 57 | + assertThatThrownBy(() -> service.fetchPlainAccessToken(1L)) |
| 58 | + .isInstanceOf(DomainException.class) |
| 59 | + .extracting(e -> ((DomainException) e).getErrorCode()) |
| 60 | + .isEqualTo(ApiErrorCode.AUTH_GITHUB_NOT_LINKED); |
| 61 | + } |
| 62 | +} |
0 commit comments