python icon indicating copy to clipboard operation
python copied to clipboard

parse_quantity/format_quantity accept invalid binary suffixes mi, ni and ui

Open ArfiArfath21 opened this issue 1 month ago • 1 comments

kubernetes.utils.parse_quantity and format_quantity accept mi, ni and ui as valid suffixes. Kubernetes only defines Ki, Mi, Gi, Ti, Pi and Ei in base 1024 (see quantity.go).

The code already rejects ki as an "SI inconsistency", but any other lowercase prefix from the table that ends in i slips through as a base-1024 negative exponent:

from decimal import Decimal
from kubernetes.utils.quantity import parse_quantity, format_quantity

parse_quantity("1mi")                  # Decimal('0.0009765625')  (expected ValueError)
parse_quantity("1ni")                  # Decimal('9.31322574615478515625E-10')
parse_quantity("1ui")                  # Decimal('9.5367431640625E-7')
parse_quantity("1ki")                  # ValueError, as intended

format_quantity(Decimal(1), "mi")      # '1024mi'  (expected ValueError)

A typo such as 512mi for a memory limit (meant 512Mi) is silently parsed as a tiny number instead of raising, so it is easy to compute with a wrong value.

I have a small fix with tests ready (limit binary suffixes to KMGTPE followed by i). Happy to open a PR once you confirm the direction and I have signed the CLA.

Disclosure: I found this while reviewing kubernetes/utils with the help of an AI assistant (Claude Code). I ran the snippet above myself against master.

ArfiArfath21 avatar Oct 16 '26 18:10 ArfiArfath21

Validating the binary suffix against a strict whitelist of ['Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei'] is the correct approach to prevent silent misinterpretation of user input. Since parse_quantity already handles ki as an error, we should unify this by refactoring the suffix validation logic into a shared helper function that maps case-sensitive binary units. Please open the PR with your proposed tests; I am interested to see how you handle the suffix matching logic without introducing regressive behavior for standard decimal units like m or u.

eliottramanda26 avatar Oct 18 '26 15:10 eliottramanda26