package handlers import ( configcore "bitrix_balancer_api/core/config" dbcore "bitrix_balancer_api/core/db/methods" redismodule "bitrix_balancer_api/core/lib/internally/redis" "bitrix_balancer_api/core/securecore" "bitrix_balancer_api/core/typescore" "bitrix_balancer_api/core/utilscore" "bitrix_balancer_api/core/variables" "context" "encoding/json" "errors" "fmt" "net/http" "strconv" "strings" "time" "github.com/sirupsen/logrus" ) // JWTVerifier middleware для проверки JWT токена и соответствия IP func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *redismodule.ModuleRedis) 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.AuthJWT.AdminSecret == "" { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, }).Error("JWTVerifier: AdminSecret is empty") http.Error(w, "Internal server error", http.StatusInternalServerError) return } authHeader := r.Header.Get("Authorization") if authHeader == "" { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, }).Warn("JWTVerifier: Authorization header is empty") http.Error(w, "Unauthorized", http.StatusUnauthorized) return } deviceID := r.Header.Get("x-device-id") if deviceID == "" { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, }).Warn("JWTVerifier: x-device-id header is empty") http.Error(w, "Unauthorized device", http.StatusUnauthorized) return } if redisModule == nil { logrus.Error("JWTVerifier: Redis storage not initialized") http.Error(w, "Internal server error: Redis storage not initialized", http.StatusInternalServerError) return } parts := strings.Split(authHeader, " ") if len(parts) != 2 || parts[0] != "Bearer" { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "auth_header": authHeader, }).Warn("JWTVerifier: Invalid authorization header format") http.Error(w, "Invalid authorization header", http.StatusUnauthorized) return } tokenString := parts[1] _, claims, err := securecore.VerifyToken(tokenString, cfg.Secrets.AuthJWT.AdminSecret) if err != nil { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "error": err.Error(), }).Warn("JWTVerifier: Token verification failed") http.Error(w, "Invalid token", http.StatusUnauthorized) return } userIDFloat, ok := claims[securecore.IDContextKey.String()].(float64) if !ok { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, }).Warn("JWTVerifier: Missing user_id in token claims") http.Error(w, "Invalid token: missing user_id", http.StatusUnauthorized) return } userID := uint64(userIDFloat) adminList, _, errW := adminDB.GetAdminsListDB(typescore.ListDbOptions{ Filtering: &typescore.Admin{ ID: &userID, IsBlocked: utilscore.PointerToBool(false), }, }) if errW != nil || len(adminList) == 0 { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "user_id": userID, "error": errW, }).Warn("JWTVerifier: Admin not found or blocked") http.Error(w, "Admin not found or blocked", http.StatusUnauthorized) return } if adminList[0].IsBlocked == nil || *adminList[0].IsBlocked { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "user_id": userID, }).Warn("JWTVerifier: Account is blocked") http.Error(w, "Forbidden: account is blocked", http.StatusUnauthorized) return } ctx := context.WithValue(r.Context(), securecore.IDContextKey, userID) sessionJSON, err := redisModule.Get(ctx, fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, userID)) if err != nil || sessionJSON == "" { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "user_id": userID, "error": err, }).Warn("JWTVerifier: User session not found in Redis") http.Error(w, "User session not found. Please authorize again", http.StatusUnauthorized) return } var session typescore.UsersSessions if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "user_id": userID, "error": err.Error(), }).Warn("JWTVerifier: Failed to unmarshal session") http.Error(w, "Failed to get user session data. Please authorize again", http.StatusUnauthorized) return } if !securecore.FindDeviceID(session.AuthorizedDevices, deviceID) { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "user_id": userID, "device_id": deviceID, }).Warn("JWTVerifier: Device not authorized") http.Error(w, "Unauthorized device", http.StatusUnauthorized) return } logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "user_id": userID, "device_id": deviceID, }).Debug("JWTVerifier: Request authorized") next.ServeHTTP(w, r.WithContext(ctx)) }) } } // AccessCodeVerifier middleware для проверки Access Code для валидного фронта 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) { // 🆕 Логируем начало проверки logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "method": r.Method, "remote": r.RemoteAddr, }).Debug("AccessCodeVerifier: Starting verification") // Проверка 1: Секреты в конфиге if cfg.Secrets.ApiPublicAdmin == "" || cfg.Secrets.ApiPrivateAdmin == "" { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "api_public_empty": cfg.Secrets.ApiPublicAdmin == "", "api_private_empty": cfg.Secrets.ApiPrivateAdmin == "", }).Error("AccessCodeVerifier: API secrets not configured") http.Error(w, "Internal server error", http.StatusInternalServerError) return } // Получаем заголовки authHeader := r.Header.Get("ApiKey") timestampStr := r.Header.Get("X-Timestamp") deviceID := r.Header.Get("x-device-id") logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "has_api_key": authHeader != "", "has_timestamp": timestampStr != "", "device_id": deviceID, }).Debug("AccessCodeVerifier: Headers received") // Проверка 2: Наличие заголовков if authHeader == "" || timestampStr == "" { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "api_key_empty": authHeader == "", "timestamp_empty": timestampStr == "", "all_headers": r.Header, }).Warn("AccessCodeVerifier: Missing required headers") http.Error(w, "Unauthorized client", http.StatusUnauthorized) return } // Проверка 3: Парсинг timestamp timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64) if err != nil { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "timestamp": timestampStr, "error": err.Error(), }).Warn("AccessCodeVerifier: Invalid timestamp format") http.Error(w, "Invalid timestamp", http.StatusBadRequest) return } // Конвертируем Unix timestamp в time.Time 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, ) logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "timestamp_received": timestampTime.Format(time.RFC3339), "timestamp_rounded": timestampTimeRounded.Format(time.RFC3339), "now": now.Format(time.RFC3339), "now_rounded": nowRounded.Format(time.RFC3339), }).Debug("AccessCodeVerifier: Timestamp parsed") // Проверка 4: Timestamp не старше 3 минут threeMinutesAgo := nowRounded.Add(-3 * time.Minute) if timestampTimeRounded.Before(threeMinutesAgo) { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "timestamp": timestampTimeRounded.Format(time.RFC3339), "three_minutes_ago": threeMinutesAgo.Format(time.RFC3339), "now": nowRounded.Format(time.RFC3339), }).Warn("AccessCodeVerifier: Timestamp expired") http.Error(w, "Timestamp expired", http.StatusUnauthorized) return } // Проверка 5: Timestamp не в будущем if timestampTimeRounded.After(nowRounded) { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "timestamp": timestampTimeRounded.Format(time.RFC3339), "now": nowRounded.Format(time.RFC3339), }).Warn("AccessCodeVerifier: Timestamp in future") http.Error(w, "Timestamp in future", http.StatusUnauthorized) return } // Проверка 6: Генерация и сравнение подписи expectedSignature := utilscore.GenerateHMACSignature( cfg.Secrets.ApiPublicAdmin, timestampStr, cfg.Secrets.ApiPrivateAdmin, ) logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "public_key": cfg.Secrets.ApiPublicAdmin[:min(10, len(cfg.Secrets.ApiPublicAdmin))] + "...", "timestamp": timestampStr, "expected_signature": expectedSignature[:min(20, len(expectedSignature))] + "...", "received_signature": authHeader[:min(20, len(authHeader))] + "...", "signatures_match": expectedSignature == authHeader, }).Debug("AccessCodeVerifier: Comparing signatures") // Безопасное сравнение if !utilscore.HmacEquals(expectedSignature, authHeader) { logrus.WithFields(logrus.Fields{ "path": r.URL.Path, "expected_signature": expectedSignature, "received_signature": authHeader, "expected_length": len(expectedSignature), "received_length": len(authHeader), }).Warn("AccessCodeVerifier: Signature mismatch") http.Error(w, "Unauthorized client", http.StatusUnauthorized) return } logrus.WithFields(logrus.Fields{ "path": r.URL.Path, }).Debug("AccessCodeVerifier: Verification successful") ctx := context.WithValue(r.Context(), securecore.AccessContextKey, authHeader) next.ServeHTTP(w, r.WithContext(ctx)) }) } } // GetIDFromContext извлекает user id из контекста func GetIDFromContext(ctx context.Context) (uint64, error) { address, ok := ctx.Value(securecore.IDContextKey).(uint64) if !ok { return 0, errors.New("no id found in context") } return address, nil } // GetIPFromContext извлекает user ip из контекста func GetIPFromContext(ctx context.Context) (string, error) { address, ok := ctx.Value(securecore.IpContextKey).(string) if !ok { return "", errors.New("no ip found in context") } return address, nil } // min возвращает минимальное из двух int func min(a, b int) int { if a < b { return a } return b }