package handler import ( configcore "bitrix_balancer_api/core/config" "bitrix_balancer_api/core/utilscore" "bitrix_balancer_api/core/variables" "context" "log" "net/http" "strconv" "time" ) // AccessCodeVerifier middleware для проверки API Signature для валидного клиента func AccessCodeVerifier(cfg *configcore.Config) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if cfg.Secrets.ApiPublicBase == "" || cfg.Secrets.ApiPrivateBase == "" { http.Error(w, "Servers secrets not configured", http.StatusInternalServerError) return } authHeader := r.Header.Get("X-Signature") timestampStr := r.Header.Get("X-Timestamp") if authHeader == "" || timestampStr == "" { http.Error(w, "Unauthorized client", http.StatusUnauthorized) return } timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64) if err != nil { http.Error(w, "Invalid timestamp", http.StatusBadRequest) return } timestampTime := time.Unix(timestampUnix, 0).UTC() now := time.Now().UTC() timestampTimeRounded := time.Date( timestampTime.Year(), timestampTime.Month(), timestampTime.Day(), timestampTime.Hour(), timestampTime.Minute(), 0, 0, time.UTC, ) nowRounded := time.Date( now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), 0, 0, time.UTC, ) threeMinutesAgo := nowRounded.Add(-3 * time.Minute) if timestampTimeRounded.Before(threeMinutesAgo) { log.Printf("Timestamp expired - received: %v (rounded: %v), current: %v (rounded: %v), 3min ago: %v", timestampTime, timestampTimeRounded, now, nowRounded, threeMinutesAgo) http.Error(w, "Timestamp expired", http.StatusUnauthorized) return } if timestampTimeRounded.After(nowRounded) { log.Printf("Timestamp in future - received: %v (rounded: %v), current: %v (rounded: %v)", timestampTime, timestampTimeRounded, now, nowRounded) http.Error(w, "Timestamp in future", http.StatusUnauthorized) return } expectedSignature := utilscore.GenerateHMACSignature(cfg.Secrets.ApiPublicBase, timestampStr, cfg.Secrets.ApiPrivateBase) if !utilscore.HmacEquals(expectedSignature, authHeader) { http.Error(w, "Unauthorized client", http.StatusUnauthorized) return } ctx := context.WithValue(r.Context(), variables.AccessContextKey, authHeader) next.ServeHTTP(w, r.WithContext(ctx)) }) } }