fix: 코드 리뷰 기반 보안·안정성 개선 2차
All checks were successful
Server CI/CD / deploy (push) Successful in 1m26s

보안:
- RPC 응답 HTTP 상태코드 검증 (chain/client)
- SSAFY OAuth 에러 응답 내부 로깅으로 변경 (제3자 상세 노출 제거)
- resolveUsername에서 username 노출 제거
- LIKE 쿼리 특수문자 이스케이프 (bossraid/repository)
- 파일명 경로 순회 방지 + 길이 제한 (download/handler)
- ServerAuth 실패 로깅 추가

안정성:
- AutoMigrate 에러 시 서버 종료
- GetLatest() 에러 시 nil 반환 (초기화 안 된 포인터 방지)
- 멱등성 캐시 저장 시 새 context 사용
- SSAFY HTTP 클라이언트 타임아웃 10s
- io.ReadAll/rand.Read 에러 처리
- Login에서 DB 에러/Not Found 구분

검증 강화:
- 중복 플레이어 검증 (bossraid/service)
- username 길이 제한 50자 (auth/handler, bossraid/handler)
- 역할 변경 시 세션 무효화
- 지갑 복호화 실패 로깅

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-13 17:48:05 +09:00
parent 61cf47070d
commit cc751653c4
12 changed files with 85 additions and 19 deletions

View File

@@ -13,6 +13,8 @@ import (
"strings"
"time"
"gorm.io/gorm"
"a301_server/pkg/config"
"github.com/golang-jwt/jwt/v5"
"github.com/redis/go-redis/v9"
@@ -21,6 +23,8 @@ import (
const refreshTokenExpiry = 7 * 24 * time.Hour
var ssafyHTTPClient = &http.Client{Timeout: 10 * time.Second}
type Claims struct {
UserID uint `json:"user_id"`
Username string `json:"username"`
@@ -45,7 +49,10 @@ func (s *Service) SetWalletCreator(fn func(userID uint) error) {
func (s *Service) Login(username, password string) (accessToken, refreshToken string, user *User, err error) {
user, err = s.repo.FindByUsername(username)
if err != nil {
return "", "", nil, fmt.Errorf("아이디 또는 비밀번호가 올바르지 않습니다")
if err == gorm.ErrRecordNotFound {
return "", "", nil, fmt.Errorf("아이디 또는 비밀번호가 올바르지 않습니다")
}
return "", "", nil, fmt.Errorf("로그인 처리 중 오류가 발생했습니다")
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
@@ -221,7 +228,7 @@ func (s *Service) ExchangeSSAFYCode(code string) (*SSAFYTokenResponse, error) {
"code": {code},
}
resp, err := http.Post(
resp, err := ssafyHTTPClient.Post(
"https://project.ssafy.com/ssafy/oauth2/token",
"application/x-www-form-urlencoded;charset=utf-8",
strings.NewReader(data.Encode()),
@@ -231,9 +238,13 @@ func (s *Service) ExchangeSSAFYCode(code string) (*SSAFYTokenResponse, error) {
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("SSAFY 토큰 응답 읽기 실패: %v", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("SSAFY 토큰 발급 실패 (status %d): %s", resp.StatusCode, string(body))
log.Printf("SSAFY 토큰 발급 실패 (status %d): %s", resp.StatusCode, string(body))
return nil, fmt.Errorf("SSAFY 인증에 실패했습니다")
}
var tokenResp SSAFYTokenResponse
@@ -245,19 +256,26 @@ func (s *Service) ExchangeSSAFYCode(code string) (*SSAFYTokenResponse, error) {
// GetSSAFYUserInfo fetches user info from SSAFY using an access token.
func (s *Service) GetSSAFYUserInfo(accessToken string) (*SSAFYUserInfo, error) {
req, _ := http.NewRequest("GET", "https://project.ssafy.com/ssafy/resources/userInfo", nil)
req, err := http.NewRequest("GET", "https://project.ssafy.com/ssafy/resources/userInfo", nil)
if err != nil {
return nil, fmt.Errorf("SSAFY 사용자 정보 요청 생성 실패: %v", err)
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-type", "application/x-www-form-urlencoded;charset=utf-8")
resp, err := http.DefaultClient.Do(req)
resp, err := ssafyHTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("SSAFY 사용자 정보 요청 실패: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("SSAFY 사용자 정보 응답 읽기 실패: %v", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("SSAFY 사용자 정보 조회 실패 (status %d): %s", resp.StatusCode, string(body))
log.Printf("SSAFY 사용자 정보 조회 실패 (status %d): %s", resp.StatusCode, string(body))
return nil, fmt.Errorf("SSAFY 사용자 정보를 가져올 수 없습니다")
}
var userInfo SSAFYUserInfo
@@ -284,7 +302,9 @@ func (s *Service) SSAFYLogin(code string) (accessToken, refreshToken string, use
if err != nil {
// 신규 사용자 자동 가입
randomBytes := make([]byte, 16)
rand.Read(randomBytes)
if _, err := rand.Read(randomBytes); err != nil {
return "", "", nil, fmt.Errorf("보안 난수 생성 실패: %v", err)
}
randomPassword := hex.EncodeToString(randomBytes)
hash, err := bcrypt.GenerateFromPassword([]byte(randomPassword), bcrypt.DefaultCost)