T09 · Insecure Skill Coding Practices
- Location
ad_budget_governor.py:135- Finding
Non-finite and negative numeric values bypass budget enforcement
- Content
View full analysis
tuple[bool, Optional[str]]: """Gate for any spend action on any platform. Call BEFORE spending.""" status = get_status() if status["ledger_read_error"]: return False, ( "Spend ledger unreadable — true spend cannot be verified. " "Failing closed: blocking this spend until the ledger is repaired." ) if status["cap_usd"] <= 0: return False, "No budget cap has been set yet. Call set_cap() first." if status["at_cap"]: return False, ( f"Rolling {_ROLLING_WINDOW_DAYS}-day cap reached " f"(${status['spent_usd']:.2f} / ${status['cap_usd']:.2f})." ) if amount_usd > status["remaining_usd"]: return False, ( f"This spend (${amount_usd:.2f}) would exceed the rolling cap. " f"Remaining: ${status['remaining_usd']:.2f} of ${status['cap_usd']:.2f}." ) return True, None ``` ### Technical Analysis The governor converts requested amounts, ledger amounts, and persisted cap values with `float()` but does not verify that the resulting values are finite or within an acceptable range. Python floating-point values can represent `NaN`, positive infinity, and negative infinity. Comparisons involving `NaN` generally evaluate to false. For example, when `amount_usd` is `float("nan")`, the expression: ```python amount_usd > status["remaining_usd"] ``` is false, allowing execution to reach `return True, None`. A negative requested amount similarly passes whenever the remaining budget is non-negative because it is not greater than the remaining balance. ...[truncated 1484 chars]- Remediation
View remediation
float: try: parsed = float(value) except (TypeError, ValueError) as exc: raise ValueError("Monetary value must be numeric") from exc if not math.isfinite(parsed): raise ValueError("Monetary value must be finite") if parsed < 0 or (parsed == 0 and not allow_zero): raise ValueError("Monetary value must be positive") return parsed ``` 2. Require requested spend amounts and ledger spend amounts to be finite and strictly positive. 3. Require caps to be finite and non-negative. 4. Treat invalid ledger or state values as verification failures and block spending rather than continuing with a partial total. 5. Consider using `decimal.Decimal` for currency calculations to avoid binary floating-point rounding behavior. 6. Configure JSON parsing to reject non-standard constants: ```python def reject_constant(value: str): raise ValueError(f"Invalid JSON numeric constant: {value}") records = json.loads( ledger_path.read_text(), parse_constant=reject_constant, ) ``` 7. Add tests for `NaN`, positive and negative infinity, negative amounts, zero, extremely large values, and malformed numeric strings. ]]>
