#36715: intcomma filter crashes on non-finite numbers
----------------------------+--------------------------------------------
Reporter: Tim Graham | Type: Bug
Status: new | Component: contrib.humanize
Version: 5.2 | Severity: Normal
Keywords: | Triage Stage: Accepted
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 1 | UI/UX: 0
----------------------------+--------------------------------------------
From Skrc Prst (skrcprst) on HackerOne:
When looking at humanize filters I discovered intcomma filter does not
robustly handle values that are not a finite number, like Inf, -Inf,
Infinity, -Infinity, NaN or sNaN, and raises a TypeError that is not
caught in the calling code.
{{{#!python
diff --git a/tests/humanize_tests/tests.py b/tests/humanize_tests/tests.py
index ab967e2874..8b90245311 100644
--- a/tests/humanize_tests/tests.py
+++ b/tests/humanize_tests/tests.py
@@ -153,6 +153,7 @@ class HumanizeTests(SimpleTestCase):
"-1234567.1234567",
Decimal("1234567.1234567"),
Decimal("-1234567.1234567"),
+ Decimal("Infinity"),
None,
"1234567",
"-1234567",
}}}
Observe a crash:
{{{
# Format values with more than 200 digits (an arbitrary
cutoff) using
# scientific notation to avoid high memory usage in
{:f}'.format().
_, digits, exponent = number.as_tuple()
> if abs(exponent) + len(digits) > 200:
^^^^^^^^^^^^^
E TypeError: bad operand type for abs(): 'str'
}}}
The code could be fortified with something like:
{{{#!python
diff --git a/django/utils/numberformat.py b/django/utils/numberformat.py
index cf8b2d219c..1f9ae840a5 100644
--- a/django/utils/numberformat.py
+++ b/django/utils/numberformat.py
@@ -48,6 +48,10 @@ def format(
if abs(number) < cutoff:
number = Decimal("0")
+ if not number.is_finite():
+ # like NaN or Infinity
+ return str(number)
+
# Format values with more than 200 digits (an arbitrary cutoff)
using
# scientific notation to avoid high memory usage in
{:f}'.format().
_, digits, exponent = number.as_tuple()
}}}
--
Ticket URL: <
https://code.djangoproject.com/ticket/36715>
Django <
https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.