From e4b32a096a0379b40ed70f7cd69c01d56f875cfa Mon Sep 17 00:00:00 2001 From: nutcas3 Date: Sat, 25 Apr 2026 05:28:33 +0300 Subject: [PATCH] feat: Add overflow protection to credit addition in charging engine - Add current balance retrieval before credit increment operation - Add checked_add validation to prevent u64 overflow when adding credits - Add InvalidInput error return when credit addition would cause overflow - Add overflow check between get and incr operations on Redis credit key --- .../charging-engine/src/charging/credit_management.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/apps/charging-engine/src/charging/credit_management.rs b/apps/charging-engine/src/charging/credit_management.rs index 14e7c0f..f37e863 100644 --- a/apps/charging-engine/src/charging/credit_management.rs +++ b/apps/charging-engine/src/charging/credit_management.rs @@ -21,6 +21,17 @@ impl crate::charging::ChargingEngine { .map_err(|e| crate::errors::ChargingError::RedisConnection(e.to_string()))?; let key = format!("credit:{}", ip); + + // Check for potential overflow before incrementing + let current_balance: Option = redis::AsyncCommands::get(&mut conn, &key).await + .map_err(|e| crate::errors::ChargingError::RedisOperation(e.to_string()))?; + + if let Some(existing_balance) = current_balance { + if existing_balance.checked_add(bytes_to_add).is_none() { + return Err(ChargingError::InvalidInput("Credit addition would overflow".to_string())); + } + } + let new_balance: u64 = redis::AsyncCommands::incr(&mut conn, &key, bytes_to_add).await .map_err(|e| crate::errors::ChargingError::RedisOperation(e.to_string()))?;