fix: 아키텍처 리뷰 HIGH/MEDIUM 이슈 10건 수정
HIGH (3건): - 런처 파일 업로드 시 PE 헤더 검증 + 500MB 크기 제한 추가 - 체인 노드 URL 파싱 시 scheme/host 유효성 검증 - Dockerfile 비루트 사용자(app:1000) 실행 MEDIUM (7건): - SSAFY username 충돌 시 랜덤 suffix로 최대 3회 재시도 - 내부 API username 검증 validID(256자) → validUsername(3~50자) 분리 - 동시 업로드 경합 방지 sync.Mutex 추가 - 프로덕션 환경변수 검증 강화 (DB_PASSWORD, OPERATOR_KEY_HEX, INTERNAL_API_KEY) - Redis 에러 시 멱등성 요청 통과 → 503 거부로 변경 - CORS AllowOrigins 환경변수화 (CORS_ALLOW_ORIGINS) - Refresh 엔드포인트 rate limiting 추가 (IP당 5 req/min) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -426,9 +426,6 @@ func (s *Service) SSAFYLogin(code, state string) (accessToken, refreshToken stri
|
||||
|
||||
ssafyID := userInfo.UserID
|
||||
// SSAFY ID에서 영문 소문자+숫자만 추출하여 안전한 username 생성
|
||||
// NOTE: Username collision is handled by the DB unique constraint.
|
||||
// If collision occurs, the transaction will rollback and return a generic error.
|
||||
// A retry with random suffix could improve UX but is not critical.
|
||||
safeID := sanitizeForUsername(ssafyID)
|
||||
if safeID == "" {
|
||||
safeID = hex.EncodeToString(randomBytes[:8])
|
||||
@@ -437,32 +434,47 @@ func (s *Service) SSAFYLogin(code, state string) (accessToken, refreshToken stri
|
||||
if len(username) > 50 {
|
||||
username = username[:50]
|
||||
}
|
||||
// DB unique constraint 충돌 시 랜덤 suffix로 최대 3회 재시도
|
||||
maxRetries := 3
|
||||
baseUsername := username
|
||||
|
||||
err = s.repo.Transaction(func(txRepo *Repository) error {
|
||||
user = &User{
|
||||
Username: username,
|
||||
PasswordHash: string(hash),
|
||||
Role: RoleUser,
|
||||
SsafyID: &ssafyID,
|
||||
}
|
||||
if err := txRepo.Create(user); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.walletCreator != nil {
|
||||
if err := s.walletCreator(user.ID); err != nil {
|
||||
return fmt.Errorf("wallet creation failed: %w", err)
|
||||
for attempt := 0; attempt < maxRetries; attempt++ {
|
||||
if attempt > 0 {
|
||||
suffix := hex.EncodeToString(randomBytes[attempt*2 : attempt*2+4])
|
||||
username = baseUsername + "_" + suffix
|
||||
if len(username) > 50 {
|
||||
username = username[:50]
|
||||
}
|
||||
}
|
||||
if s.profileCreator != nil {
|
||||
if err := s.profileCreator(user.ID); err != nil {
|
||||
return fmt.Errorf("profile creation failed: %w", err)
|
||||
err = s.repo.Transaction(func(txRepo *Repository) error {
|
||||
user = &User{
|
||||
Username: username,
|
||||
PasswordHash: string(hash),
|
||||
Role: RoleUser,
|
||||
SsafyID: &ssafyID,
|
||||
}
|
||||
if err := txRepo.Create(user); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.walletCreator != nil {
|
||||
if err := s.walletCreator(user.ID); err != nil {
|
||||
return fmt.Errorf("wallet creation failed: %w", err)
|
||||
}
|
||||
}
|
||||
if s.profileCreator != nil {
|
||||
if err := s.profileCreator(user.ID); err != nil {
|
||||
return fmt.Errorf("profile creation failed: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
return nil
|
||||
})
|
||||
log.Printf("SSAFY user creation attempt %d failed: %v", attempt+1, err)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("SSAFY user creation transaction failed: %v", err)
|
||||
return "", "", nil, fmt.Errorf("계정 생성 실패: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,10 @@ func validID(s string) bool {
|
||||
return s != "" && len(s) <= maxIDLength
|
||||
}
|
||||
|
||||
func validUsername(s string) bool {
|
||||
return len(s) >= 3 && len(s) <= 50
|
||||
}
|
||||
|
||||
// chainError classifies chain errors into appropriate HTTP responses.
|
||||
// TxError (on-chain execution failure) maps to 422 with the chain's error detail.
|
||||
// Other errors (network, timeout, build failures) remain 500.
|
||||
@@ -640,8 +644,8 @@ func (h *Handler) InternalGrantReward(c *fiber.Ctx) error {
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return apperror.ErrBadRequest
|
||||
}
|
||||
if !validID(req.Username) {
|
||||
return apperror.BadRequest("username은 필수입니다")
|
||||
if !validUsername(req.Username) {
|
||||
return apperror.BadRequest("username은 3~50자여야 합니다")
|
||||
}
|
||||
result, err := h.svc.GrantRewardByUsername(req.Username, req.TokenAmount, req.Assets)
|
||||
if err != nil {
|
||||
@@ -672,8 +676,8 @@ func (h *Handler) InternalMintAsset(c *fiber.Ctx) error {
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return apperror.ErrBadRequest
|
||||
}
|
||||
if !validID(req.TemplateID) || !validID(req.Username) {
|
||||
return apperror.BadRequest("templateId와 username은 필수입니다")
|
||||
if !validID(req.TemplateID) || !validUsername(req.Username) {
|
||||
return apperror.BadRequest("templateId와 username은 필수입니다 (username: 3~50자)")
|
||||
}
|
||||
result, err := h.svc.MintAssetByUsername(req.TemplateID, req.Username, req.Properties)
|
||||
if err != nil {
|
||||
@@ -695,8 +699,8 @@ func (h *Handler) InternalMintAsset(c *fiber.Ctx) error {
|
||||
// @Router /api/internal/chain/balance [get]
|
||||
func (h *Handler) InternalGetBalance(c *fiber.Ctx) error {
|
||||
username := c.Query("username")
|
||||
if !validID(username) {
|
||||
return apperror.BadRequest("username은 필수입니다")
|
||||
if !validUsername(username) {
|
||||
return apperror.BadRequest("username은 3~50자여야 합니다")
|
||||
}
|
||||
result, err := h.svc.GetBalanceByUsername(username)
|
||||
if err != nil {
|
||||
@@ -720,8 +724,8 @@ func (h *Handler) InternalGetBalance(c *fiber.Ctx) error {
|
||||
// @Router /api/internal/chain/assets [get]
|
||||
func (h *Handler) InternalGetAssets(c *fiber.Ctx) error {
|
||||
username := c.Query("username")
|
||||
if !validID(username) {
|
||||
return apperror.BadRequest("username은 필수입니다")
|
||||
if !validUsername(username) {
|
||||
return apperror.BadRequest("username은 3~50자여야 합니다")
|
||||
}
|
||||
offset, limit := parsePagination(c)
|
||||
result, err := h.svc.GetAssetsByUsername(username, offset, limit)
|
||||
@@ -745,8 +749,8 @@ func (h *Handler) InternalGetAssets(c *fiber.Ctx) error {
|
||||
// @Router /api/internal/chain/inventory [get]
|
||||
func (h *Handler) InternalGetInventory(c *fiber.Ctx) error {
|
||||
username := c.Query("username")
|
||||
if !validID(username) {
|
||||
return apperror.BadRequest("username은 필수입니다")
|
||||
if !validUsername(username) {
|
||||
return apperror.BadRequest("username은 3~50자여야 합니다")
|
||||
}
|
||||
result, err := h.svc.GetInventoryByUsername(username)
|
||||
if err != nil {
|
||||
|
||||
@@ -11,13 +11,17 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const maxLauncherSize = 500 * 1024 * 1024 // 500MB
|
||||
|
||||
var versionRe = regexp.MustCompile(`v\d+\.\d+(\.\d+)?`)
|
||||
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
gameDir string
|
||||
repo *Repository
|
||||
gameDir string
|
||||
uploadMu sync.Mutex
|
||||
}
|
||||
|
||||
func NewService(repo *Repository, gameDir string) *Service {
|
||||
@@ -37,6 +41,9 @@ func (s *Service) LauncherFilePath() string {
|
||||
}
|
||||
|
||||
func (s *Service) UploadLauncher(body io.Reader, baseURL string) (*Info, error) {
|
||||
s.uploadMu.Lock()
|
||||
defer s.uploadMu.Unlock()
|
||||
|
||||
if err := os.MkdirAll(s.gameDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("디렉토리 생성 실패: %w", err)
|
||||
}
|
||||
@@ -49,9 +56,7 @@ func (s *Service) UploadLauncher(body io.Reader, baseURL string) (*Info, error)
|
||||
return nil, fmt.Errorf("파일 생성 실패: %w", err)
|
||||
}
|
||||
|
||||
// NOTE: Partial uploads (client closes cleanly mid-transfer) are saved.
|
||||
// The hashGameExeFromZip check mitigates this for game uploads but not for launcher uploads.
|
||||
n, err := io.Copy(f, body)
|
||||
n, err := io.Copy(f, io.LimitReader(body, maxLauncherSize+1))
|
||||
if closeErr := f.Close(); closeErr != nil && err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
@@ -61,6 +66,16 @@ func (s *Service) UploadLauncher(body io.Reader, baseURL string) (*Info, error)
|
||||
}
|
||||
return nil, fmt.Errorf("파일 저장 실패: %w", err)
|
||||
}
|
||||
if n > maxLauncherSize {
|
||||
os.Remove(tmpPath)
|
||||
return nil, fmt.Errorf("런처 파일이 너무 큽니다 (최대 %dMB)", maxLauncherSize/1024/1024)
|
||||
}
|
||||
|
||||
// PE 헤더 검증 (MZ magic bytes)
|
||||
if err := validatePEHeader(tmpPath); err != nil {
|
||||
os.Remove(tmpPath)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := os.Rename(tmpPath, finalPath); err != nil {
|
||||
if removeErr := os.Remove(tmpPath); removeErr != nil {
|
||||
@@ -88,6 +103,9 @@ func (s *Service) UploadLauncher(body io.Reader, baseURL string) (*Info, error)
|
||||
|
||||
// Upload streams the body directly to disk, then extracts metadata from the zip.
|
||||
func (s *Service) Upload(filename string, body io.Reader, baseURL string) (*Info, error) {
|
||||
s.uploadMu.Lock()
|
||||
defer s.uploadMu.Unlock()
|
||||
|
||||
if err := os.MkdirAll(s.gameDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("디렉토리 생성 실패: %w", err)
|
||||
}
|
||||
@@ -153,6 +171,22 @@ func (s *Service) Upload(filename string, body io.Reader, baseURL string) (*Info
|
||||
return info, s.repo.Save(info)
|
||||
}
|
||||
|
||||
func validatePEHeader(path string) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("파일 검증 실패: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
header := make([]byte, 2)
|
||||
if _, err := io.ReadFull(f, header); err != nil {
|
||||
return fmt.Errorf("유효하지 않은 실행 파일입니다")
|
||||
}
|
||||
if header[0] != 'M' || header[1] != 'Z' {
|
||||
return fmt.Errorf("유효하지 않은 실행 파일입니다")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hashFileToHex(path string) string {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"time"
|
||||
|
||||
"a301_server/pkg/apperror"
|
||||
"a301_server/pkg/config"
|
||||
"a301_server/pkg/metrics"
|
||||
"a301_server/pkg/middleware"
|
||||
|
||||
@@ -36,7 +37,7 @@ func New() *fiber.App {
|
||||
}))
|
||||
app.Use(middleware.SecurityHeaders)
|
||||
app.Use(cors.New(cors.Config{
|
||||
AllowOrigins: "https://a301.tolelom.xyz",
|
||||
AllowOrigins: config.C.CORSAllowOrigins,
|
||||
AllowHeaders: "Origin, Content-Type, Authorization, Idempotency-Key, X-API-Key, X-Requested-With",
|
||||
AllowMethods: "GET, POST, PUT, PATCH, DELETE",
|
||||
AllowCredentials: true,
|
||||
@@ -72,6 +73,21 @@ func APILimiter() fiber.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// RefreshLimiter returns a rate limiter for refresh token endpoint (5 req/min per IP).
|
||||
// Separate from AuthLimiter to avoid NAT collisions while still preventing abuse.
|
||||
func RefreshLimiter() fiber.Handler {
|
||||
return limiter.New(limiter.Config{
|
||||
Max: 5,
|
||||
Expiration: 1 * time.Minute,
|
||||
KeyGenerator: func(c *fiber.Ctx) string {
|
||||
return "refresh:" + c.IP()
|
||||
},
|
||||
LimitReached: func(c *fiber.Ctx) error {
|
||||
return apperror.ErrRateLimited
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ChainUserLimiter returns a rate limiter for chain transactions (20 req/min per user).
|
||||
func ChainUserLimiter() fiber.Handler {
|
||||
return limiter.New(limiter.Config{
|
||||
|
||||
Reference in New Issue
Block a user