feat: DB DI 전환 + download 하위 호환성 + race condition 수정
- middleware(Auth, Idempotency)를 클로저 팩토리 패턴으로 DI 전환 - database.DB/RDB 전역 변수 제거, ConnectMySQL/Redis 값 반환으로 변경 - download API X-API-Version 헤더 + 하위 호환성 규칙 문서화 - SaveGameData PlayTimeDelta 원자적 UPDATE (race condition 해소) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -8,60 +8,63 @@ import (
|
||||
"strings"
|
||||
|
||||
"a301_server/pkg/apperror"
|
||||
"a301_server/pkg/config"
|
||||
"a301_server/pkg/database"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func Auth(c *fiber.Ctx) error {
|
||||
header := c.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
return apperror.ErrUnauthorized
|
||||
}
|
||||
tokenStr := strings.TrimPrefix(header, "Bearer ")
|
||||
|
||||
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (any, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method")
|
||||
// Auth returns a middleware that validates JWT tokens and checks Redis sessions.
|
||||
func Auth(rdb *redis.Client, jwtSecret string) fiber.Handler {
|
||||
secretBytes := []byte(jwtSecret)
|
||||
return func(c *fiber.Ctx) error {
|
||||
header := c.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
return apperror.ErrUnauthorized
|
||||
}
|
||||
return []byte(config.C.JWTSecret), nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
tokenStr := strings.TrimPrefix(header, "Bearer ")
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
userIDFloat, ok := claims["user_id"].(float64)
|
||||
if !ok {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
username, ok := claims["username"].(string)
|
||||
if !ok {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
role, ok := claims["role"].(string)
|
||||
if !ok {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
userID := uint(userIDFloat)
|
||||
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (any, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method")
|
||||
}
|
||||
return secretBytes, nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
|
||||
// Redis 세션 확인
|
||||
ctx, cancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer cancel()
|
||||
key := fmt.Sprintf("session:%d", userID)
|
||||
stored, err := database.RDB.Get(ctx, key).Result()
|
||||
if err != nil || stored != tokenStr {
|
||||
return apperror.Unauthorized("만료되었거나 로그아웃된 세션입니다")
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
userIDFloat, ok := claims["user_id"].(float64)
|
||||
if !ok {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
username, ok := claims["username"].(string)
|
||||
if !ok {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
role, ok := claims["role"].(string)
|
||||
if !ok {
|
||||
return apperror.Unauthorized("유효하지 않은 토큰입니다")
|
||||
}
|
||||
userID := uint(userIDFloat)
|
||||
|
||||
c.Locals("userID", userID)
|
||||
c.Locals("username", username)
|
||||
c.Locals("role", role)
|
||||
return c.Next()
|
||||
// Redis 세션 확인
|
||||
ctx, cancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer cancel()
|
||||
key := fmt.Sprintf("session:%d", userID)
|
||||
stored, err := rdb.Get(ctx, key).Result()
|
||||
if err != nil || stored != tokenStr {
|
||||
return apperror.Unauthorized("만료되었거나 로그아웃된 세션입니다")
|
||||
}
|
||||
|
||||
c.Locals("userID", userID)
|
||||
c.Locals("username", username)
|
||||
c.Locals("role", role)
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func AdminOnly(c *fiber.Ctx) error {
|
||||
@@ -71,14 +74,16 @@ func AdminOnly(c *fiber.Ctx) error {
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
// ServerAuth validates X-API-Key header for server-to-server communication.
|
||||
// ServerAuth returns a middleware that validates X-API-Key header for server-to-server communication.
|
||||
// Uses constant-time comparison to prevent timing attacks.
|
||||
func ServerAuth(c *fiber.Ctx) error {
|
||||
key := c.Get("X-API-Key")
|
||||
expected := config.C.InternalAPIKey
|
||||
if key == "" || expected == "" || subtle.ConstantTimeCompare([]byte(key), []byte(expected)) != 1 {
|
||||
log.Printf("ServerAuth 실패: IP=%s, Path=%s", c.IP(), c.Path())
|
||||
return apperror.Unauthorized("유효하지 않은 API 키입니다")
|
||||
func ServerAuth(apiKey string) fiber.Handler {
|
||||
expectedBytes := []byte(apiKey)
|
||||
return func(c *fiber.Ctx) error {
|
||||
key := c.Get("X-API-Key")
|
||||
if key == "" || len(expectedBytes) == 0 || subtle.ConstantTimeCompare([]byte(key), expectedBytes) != 1 {
|
||||
log.Printf("ServerAuth 실패: IP=%s, Path=%s", c.IP(), c.Path())
|
||||
return apperror.Unauthorized("유효하지 않은 API 키입니다")
|
||||
}
|
||||
return c.Next()
|
||||
}
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"time"
|
||||
|
||||
"a301_server/pkg/apperror"
|
||||
"a301_server/pkg/database"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const idempotencyTTL = 10 * time.Minute
|
||||
@@ -20,95 +20,100 @@ type cachedResponse struct {
|
||||
Body json.RawMessage `json:"b"`
|
||||
}
|
||||
|
||||
// IdempotencyRequired rejects requests without an Idempotency-Key header,
|
||||
// then delegates to Idempotency for cache/replay logic.
|
||||
func IdempotencyRequired(c *fiber.Ctx) error {
|
||||
if c.Get("Idempotency-Key") == "" {
|
||||
return apperror.BadRequest("Idempotency-Key 헤더가 필요합니다")
|
||||
// IdempotencyRequired returns a middleware that rejects requests without an Idempotency-Key header,
|
||||
// then delegates to idempotency cache/replay logic.
|
||||
func IdempotencyRequired(rdb *redis.Client) fiber.Handler {
|
||||
idempotency := Idempotency(rdb)
|
||||
return func(c *fiber.Ctx) error {
|
||||
if c.Get("Idempotency-Key") == "" {
|
||||
return apperror.BadRequest("Idempotency-Key 헤더가 필요합니다")
|
||||
}
|
||||
return idempotency(c)
|
||||
}
|
||||
return Idempotency(c)
|
||||
}
|
||||
|
||||
// Idempotency checks the Idempotency-Key header to prevent duplicate transactions.
|
||||
// Idempotency returns a middleware that checks the Idempotency-Key header to prevent duplicate transactions.
|
||||
// If the same key is seen again within the TTL, the cached response is returned.
|
||||
func Idempotency(c *fiber.Ctx) error {
|
||||
key := c.Get("Idempotency-Key")
|
||||
if key == "" {
|
||||
return c.Next()
|
||||
}
|
||||
if len(key) > 256 {
|
||||
return apperror.BadRequest("Idempotency-Key가 너무 깁니다")
|
||||
}
|
||||
func Idempotency(rdb *redis.Client) fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
key := c.Get("Idempotency-Key")
|
||||
if key == "" {
|
||||
return c.Next()
|
||||
}
|
||||
if len(key) > 256 {
|
||||
return apperror.BadRequest("Idempotency-Key가 너무 깁니다")
|
||||
}
|
||||
|
||||
// userID가 있으면 키에 포함하여 사용자 간 캐시 충돌 방지
|
||||
redisKey := "idempotency:"
|
||||
if uid, ok := c.Locals("userID").(uint); ok {
|
||||
redisKey += fmt.Sprintf("u%d:", uid)
|
||||
}
|
||||
redisKey += key
|
||||
// userID가 있으면 키에 포함하여 사용자 간 캐시 충돌 방지
|
||||
redisKey := "idempotency:"
|
||||
if uid, ok := c.Locals("userID").(uint); ok {
|
||||
redisKey += fmt.Sprintf("u%d:", uid)
|
||||
}
|
||||
redisKey += key
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer cancel()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer cancel()
|
||||
|
||||
// Atomically claim the key using SET NX (only succeeds if key doesn't exist)
|
||||
set, err := database.RDB.SetNX(ctx, redisKey, "processing", idempotencyTTL).Result()
|
||||
if err != nil {
|
||||
// Redis error — let the request through rather than blocking
|
||||
log.Printf("WARNING: idempotency SetNX failed (key=%s): %v", key, err)
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
if !set {
|
||||
// Key already exists — either processing or completed
|
||||
getCtx, getCancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer getCancel()
|
||||
|
||||
cached, err := database.RDB.Get(getCtx, redisKey).Bytes()
|
||||
// Atomically claim the key using SET NX (only succeeds if key doesn't exist)
|
||||
set, err := rdb.SetNX(ctx, redisKey, "processing", idempotencyTTL).Result()
|
||||
if err != nil {
|
||||
// Redis error — let the request through rather than blocking
|
||||
log.Printf("WARNING: idempotency SetNX failed (key=%s): %v", key, err)
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
if !set {
|
||||
// Key already exists — either processing or completed
|
||||
getCtx, getCancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer getCancel()
|
||||
|
||||
cached, err := rdb.Get(getCtx, redisKey).Bytes()
|
||||
if err != nil {
|
||||
return apperror.Conflict("요청이 처리 중입니다")
|
||||
}
|
||||
if string(cached) == "processing" {
|
||||
return apperror.Conflict("요청이 처리 중입니다")
|
||||
}
|
||||
var cr cachedResponse
|
||||
if json.Unmarshal(cached, &cr) == nil {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("X-Idempotent-Replay", "true")
|
||||
return c.Status(cr.StatusCode).Send(cr.Body)
|
||||
}
|
||||
return apperror.Conflict("요청이 처리 중입니다")
|
||||
}
|
||||
if string(cached) == "processing" {
|
||||
return apperror.Conflict("요청이 처리 중입니다")
|
||||
}
|
||||
var cr cachedResponse
|
||||
if json.Unmarshal(cached, &cr) == nil {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("X-Idempotent-Replay", "true")
|
||||
return c.Status(cr.StatusCode).Send(cr.Body)
|
||||
}
|
||||
return apperror.Conflict("요청이 처리 중입니다")
|
||||
}
|
||||
|
||||
// We claimed the key — process the request
|
||||
if err := c.Next(); err != nil {
|
||||
// Processing failed — remove the key so it can be retried
|
||||
delCtx, delCancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer delCancel()
|
||||
if delErr := database.RDB.Del(delCtx, redisKey).Err(); delErr != nil {
|
||||
log.Printf("WARNING: idempotency cache delete failed (key=%s): %v", key, delErr)
|
||||
// We claimed the key — process the request
|
||||
if err := c.Next(); err != nil {
|
||||
// Processing failed — remove the key so it can be retried
|
||||
delCtx, delCancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer delCancel()
|
||||
if delErr := rdb.Del(delCtx, redisKey).Err(); delErr != nil {
|
||||
log.Printf("WARNING: idempotency cache delete failed (key=%s): %v", key, delErr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Cache successful responses (2xx), otherwise remove the key for retry
|
||||
status := c.Response().StatusCode()
|
||||
if status >= 200 && status < 300 {
|
||||
cr := cachedResponse{StatusCode: status, Body: c.Response().Body()}
|
||||
if data, err := json.Marshal(cr); err == nil {
|
||||
writeCtx, writeCancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer writeCancel()
|
||||
if err := database.RDB.Set(writeCtx, redisKey, data, idempotencyTTL).Err(); err != nil {
|
||||
log.Printf("WARNING: idempotency cache write failed (key=%s): %v", key, err)
|
||||
// Cache successful responses (2xx), otherwise remove the key for retry
|
||||
status := c.Response().StatusCode()
|
||||
if status >= 200 && status < 300 {
|
||||
cr := cachedResponse{StatusCode: status, Body: c.Response().Body()}
|
||||
if data, err := json.Marshal(cr); err == nil {
|
||||
writeCtx, writeCancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer writeCancel()
|
||||
if err := rdb.Set(writeCtx, redisKey, data, idempotencyTTL).Err(); err != nil {
|
||||
log.Printf("WARNING: idempotency cache write failed (key=%s): %v", key, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Non-success — allow retry by removing the key
|
||||
delCtx, delCancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer delCancel()
|
||||
if delErr := rdb.Del(delCtx, redisKey).Err(); delErr != nil {
|
||||
log.Printf("WARNING: idempotency cache delete failed (key=%s): %v", key, delErr)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Non-success — allow retry by removing the key
|
||||
delCtx, delCancel := context.WithTimeout(context.Background(), redisTimeout)
|
||||
defer delCancel()
|
||||
if delErr := database.RDB.Del(delCtx, redisKey).Err(); delErr != nil {
|
||||
log.Printf("WARNING: idempotency cache delete failed (key=%s): %v", key, delErr)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user