Skip to content

Fix DecimalField crash on long numbers when max_digits is None - #10123

Open
mohamed-alired wants to merge 1 commit into
encode:mainfrom
mohamed-alired:fix-decimalfield-unbounded-precision
Open

mohamed-alired wants to merge 1 commit into
encode:mainfrom
mohamed-alired:fix-decimalfield-unbounded-precision

Conversation

@mohamed-alired

Copy link
Copy Markdown
Contributor

Description

DecimalField.quantize() only sets the decimal context precision when max_digits is given. With max_digits=None (documented as allowed, and covered by TestNoMaxDigitsDecimalField) it keeps the default context precision of 28, so Decimal.quantize() raises decimal.InvalidOperation for any value that needs more digits once quantized. The exception is not caught, so the request fails with a 500:

class S(serializers.Serializer):
    amount = serializers.DecimalField(max_digits=None, decimal_places=2)

S(data={'amount': '1' * 27}).is_valid()  # also '1e30', 10 ** 30
# decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

to_representation() has the same problem for such values.

This change:

  • gives the context enough precision for the quantized value when max_digits is None, bounded by MAX_STRING_LENGTH like the input string itself, so a short input with a huge exponent (e.g. '1e999999999') cannot make the server build an enormous number;
  • reports values beyond that bound as a validation error (max_string_length) instead of a 500.

Behaviour with max_digits set is unchanged.

Tests: TestNoMaxDigitsLargeDecimalField covers 27-digit and 1e30 inputs, an integer input, an oversized exponent and a 30-digit output. It fails on main with InvalidOperation and passes with this change.

quantize() only set the decimal context precision when max_digits was
given, so with max_digits=None it kept the default precision of 28 and
Decimal.quantize() raised InvalidOperation for any value needing more
digits (e.g. '1' * 27 with decimal_places=2, or '1e30'): a 500 instead
of a valid value.

Give the context enough precision for the quantized value, bounded by
MAX_STRING_LENGTH like the input itself, and report values beyond that
bound (e.g. '1e1000') as a validation error.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant