Skip to content

FloatField will crash if the input is a number that is too big #8725

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Nov 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -919,7 +919,8 @@ class FloatField(Field):
'invalid': _('A valid number is required.'),
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
'max_string_length': _('String value too large.')
'max_string_length': _('String value too large.'),
'overflow': _('Integer value too large to convert to float')
}
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.

Expand All @@ -945,6 +946,8 @@ def to_internal_value(self, data):
return float(data)
except (TypeError, ValueError):
self.fail('invalid')
except OverflowError:
self.fail('overflow')

def to_representation(self, value):
return float(value)
Expand Down
9 changes: 9 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
import math
import os
import re
import uuid
Expand Down Expand Up @@ -1072,6 +1073,14 @@ class TestMinMaxFloatField(FieldValues):
field = serializers.FloatField(min_value=1, max_value=3)


class TestFloatFieldOverFlowError(TestCase):
def test_overflow_error_float_field(self):
field = serializers.FloatField()
with pytest.raises(serializers.ValidationError) as exec_info:
field.to_internal_value(data=math.factorial(171))
assert "Integer value too large to convert to float" in str(exec_info.value.detail)


class TestDecimalField(FieldValues):
"""
Valid and invalid values for `DecimalField`.
Expand Down