T09 · Insecure Skill Coding Practices
Error
- Location
- token_tamer.py:83
- Finding
- Negative Token Counts Can Reduce Recorded Spending and Bypass Budget Enforcement<![CDATA[ ## Vulnerability Details **File Location**: `token_tamer.py:83-101`, `token_tamer.py:218-244`, `token_tamer.py:326-327` **Vulnerability Type**: Insufficient numeric input validation **Risk Level**: High ### Vulnerable Code ```python def calculate_cost(self, provider: str, model: str, input_tokens: int, output_tokens: int) -> float: """Calculate cost for a usage event.""" # Look up pricing key = f"{provider}/{model}" if key not in self.pricing: # Try provider wildcard key = f"{provider}/*" if key not in self.pricing: # Unknown model, return 0 and warn print(f"Warning: No pricing data for {provider}/{model}", file=sys.stderr) return 0.0 pricing = self.pricing[key] # Calculate cost (pricing is per million tokens) input_cost = (input_tokens / 1_000_000) * pricing['input'] output_cost = (output_tokens / 1_000_000) * pricing['output'] return input_cost + output_cost ``` ```python def log_usage(self, provider: str, model: str, input_tokens: int, output_tokens: int, task: Optional[str] = None, session: Optional[str] = None, metadata: Optional[Dict] = None) -> Tuple[float, str]: """Log API usage and return cost + status.""" # Calculate cost cost = self.calculator.calculate_cost(provider, model, input_tokens, output_tokens) # Create record record = UsageRecord(provider, model, input_tokens, output_tokens, cost, task, session, metadata) # Check budget before logging daily_cost = self.get_daily_cost() status, message = self.budget_tracker.check_budget('daily', daily_cost + cost) ``` ```python parser.add_argument('--input-tokens', type=int, help='Input tokens') parser.add_argument('--output-tokens', type=int, help='Output tokens') ``` ### Technical Analysis The CLI and public `log_usage()` API accept arbitrary integers without checking that token counts are non-negative. `calculate_cost()` directly multiplies thes ...[truncated 1611 chars]
- Remediation
- <![CDATA[ ## Remediation Suggestions - Validate token counts at every public entry point before calculating or storing costs. - Require `input_tokens` and `output_tokens` to be non-negative integers. Consider setting a reasonable configurable upper bound. - Reject booleans explicitly when validating programmatic input because Python treats `bool` as a subclass of `int`. - Validate configured prices as finite, non-negative numeric values. - Validate `estimated_cost` in `check_before_call()` as finite and non-negative. - Do not silently normalize invalid values to zero; raise a clear exception and do not alter the ledger. - Add regression tests for negative values, excessively large values, booleans, non-finite estimates, and malformed pricing. Example validation: ```python def validate_token_count(name: str, value: int) -> None: if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise ValueError(f"{name} must be a non-negative integer") validate_token_count("input_tokens", input_tokens) validate_token_count("output_tokens", output_tokens) ``` ]]>
