Files
a301_server/pkg/middleware/idempotency.go
tolelom 23bec776ab
All checks were successful
Server CI/CD / deploy (push) Successful in 1m36s
fix: 코드 리뷰 기반 보안·안정성 개선 (14건)
- unsafe 타입 단언 → safe assertion (chain handler 11곳, auth Logout)
- Repository 에러 시 nil 반환으로 통일 (chain, auth, announcement)
- string ID → uint 파싱으로 타입 안전성 확보 (auth, announcement)
- CORS AllowHeaders에 Idempotency-Key, X-API-Key 추가
- /verify 엔드포인트 rate limiter 적용
- Redis 호출에 context timeout 적용 (auth, idempotency 미들웨어)
- chain handler 에러 응답에서 내부 정보 노출 방지
- f.Close() 에러 검사 추가 (download service 2곳)
- 공지사항 Delete 404 응답 추가
- 회원가입 롤백 시 Delete 에러 로깅

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 14:47:00 +09:00

69 lines
1.7 KiB
Go

package middleware
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
"a301_server/pkg/database"
"github.com/gofiber/fiber/v2"
)
const idempotencyTTL = 10 * time.Minute
const redisTimeout = 5 * time.Second
type cachedResponse struct {
StatusCode int `json:"s"`
Body json.RawMessage `json:"b"`
}
// Idempotency 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()
}
// 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()
// Check if this key was already processed
cached, err := database.RDB.Get(ctx, redisKey).Bytes()
if err == nil && len(cached) > 0 {
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)
}
}
// Process the request
if err := c.Next(); err != nil {
return err
}
// Cache successful responses (2xx)
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 {
if err := database.RDB.Set(ctx, redisKey, data, idempotencyTTL).Err(); err != nil {
log.Printf("WARNING: idempotency cache write failed (key=%s): %v", key, err)
}
}
}
return nil
}