rbg
rbg copied to clipboard
Fix unsafe integer conversion in instance_utils.go
File: pkg/reconciler/instance/utils/instance_utils.go
Line: 145
Rule: go/incorrect-integer-conversion
Severity: High
Issue
The current implementation converts a string to int (architecture-dependent size) and then downcasts to int32 without bounds checking:
list := strings.Split(pod.Name, "-")
componentId = list[len(list)-1]
id, _ := strconv.Atoi(componentId) // ❌ Unsafe conversion
return int32(id)
If the integer parsed from the pod name exceeds math.MaxInt32 (2147483647) or is below math.MinInt32 (-2147483648), the conversion to int32 will silently wrap, causing undefined behavior (e.g., negative IDs, overflow bugs).
Recommended Fix
Replace strconv.Atoi with explicit bounds checking or use strconv.ParseInt with a 32-bit size:
Option 1 (ParseInt with bitSize=32):
idStr := list[len(list)-1]
id, err := strconv.ParseInt(idStr, 10, 32) // ✅ Automatically enforces 32-bit bounds
if err != nil {
return 0 // or handle error appropriately
}
return int32(id)
Option 2 (Atoi + Manual Bounds Check):
idStr := list[len(list)-1]
id, err := strconv.Atoi(idStr)
if err != nil {
return 0
}
// Explicit bounds check
if id < math.MinInt32 || id > math.MaxInt32 {
return 0 // or handle overflow
}
return int32(id)
Why This Matters
- Security Impact: Unchecked conversions enable integer overflow exploits (e.g., resource exhaustion, bypassing checks).
- 📏 Correctness: Values outside
int32range corrupt data silently. - ⚠️ CodeQL Alert: This violates go/incorrect-integer-conversion (reference:
strconv.Atoi→int32).