Skip to content

Commit 69ed168

Browse files
authored
Reject large exponents in Fraction validation (#13944)
1 parent 895c0c2 commit 69ed168

2 files changed

Lines changed: 99 additions & 1 deletion

File tree

‎pydantic-core/src/validators/fraction.rs‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::sync::Arc;
33
use pyo3::exceptions::{PyOverflowError, PyTypeError, PyValueError, PyZeroDivisionError};
44
use pyo3::intern;
55
use pyo3::sync::PyOnceLock;
6-
use pyo3::types::{IntoPyDict, PyDict, PyString, PyType};
6+
use pyo3::types::{IntoPyDict, PyDict, PyInt, PyString, PyType};
77
use pyo3::{PyTypeInfo, prelude::*};
88

99
use crate::build_tools::is_strict;
@@ -156,8 +156,46 @@ impl Validator for FractionValidator {
156156
}
157157
}
158158

159+
/// Maximum absolute value of the exponent accepted in string inputs (e.g. `'1e4300'`).
160+
///
161+
/// `Fraction` computes `10**exp` for exponent notation, producing an integer with `|exp| + 1`
162+
/// decimal digits, which can be very expensive and lead to DoS. Cap it so the result is
163+
/// no larger than what we accept for `int` inputs.
164+
const MAX_FRACTION_EXPONENT: u64 = 4300;
165+
166+
/// Whether the string uses exponent notation with an exponent larger than `MAX_FRACTION_EXPONENT`.
167+
fn exponent_too_large(s: &Bound<'_, PyString>) -> bool {
168+
// Based on https://github.com/python/cpython/blob/v3.14.8/Lib/fractions.py#L257-L283:
169+
170+
// A string that isn't valid UTF-8 is rejected by `Fraction` anyway.
171+
let Ok(str) = s.to_str() else {
172+
return false;
173+
};
174+
// In a valid `Fraction` string, `e`/`E` can only appear as the exponent marker.
175+
let Some(pos) = str.rfind(['e', 'E']) else {
176+
return false;
177+
};
178+
let py = s.py();
179+
// `Fraction` parses the exponent with `int()`:
180+
let Ok(exp) = PyString::new(py, &str[pos + 1..])
181+
.call_method0(intern!(py, "strip"))
182+
.and_then(|exp| PyInt::type_object(py).call1((exp,)))
183+
else {
184+
// Not a valid exponent, `Fraction` will reject the string itself.
185+
return false;
186+
};
187+
// Not fitting in an `i64` means it's way above the limit.
188+
exp.extract::<i64>()
189+
.map_or(true, |exp| exp.unsigned_abs() > MAX_FRACTION_EXPONENT)
190+
}
191+
159192
pub(crate) fn create_fraction<'py>(arg: &Bound<'py, PyAny>, input: impl ToErrorValue) -> ValResult<Bound<'py, PyAny>> {
160193
let py = arg.py();
194+
if let Ok(s) = arg.cast::<PyString>()
195+
&& exponent_too_large(s)
196+
{
197+
return Err(ValError::new(ErrorTypeDefaults::FractionParsing, input));
198+
}
161199
get_fraction_type(py)?
162200
.call1((arg,))
163201
.map_err(|e| handle_fraction_new_error(input, e))

‎tests/types/test_fraction.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import json
2+
import sys
13
from decimal import Decimal
24
from fractions import Fraction
35
from typing import Annotated
@@ -150,6 +152,64 @@ def test_fraction_validation_error(input: object, error_type: str):
150152
ta.validate_python(input)
151153

152154

155+
@pytest.mark.parametrize(
156+
['input_value', 'expected'],
157+
[
158+
('1e4300', Fraction(10**4300)),
159+
('-1E+4300', Fraction(-(10**4300))),
160+
('1e-4300', Fraction(1, 10**4300)),
161+
pytest.param(
162+
'1.5e4_300 ',
163+
Fraction(15 * 10**4299),
164+
marks=pytest.mark.skipif(sys.version_info < (3, 11), reason='Fraction supports underscores since 3.11'),
165+
),
166+
('1e00000000004300', Fraction(10**4300)),
167+
('1e٤٣٠٠', Fraction(10**4300)),
168+
],
169+
)
170+
@pytest.mark.parametrize('mode', ['python', 'json', 'strings'])
171+
def test_fraction_exponent_within_limit(input_value: str, expected: Fraction, mode: str) -> None:
172+
ta = TypeAdapter(Fraction)
173+
174+
if mode == 'python':
175+
assert ta.validate_python(input_value) == expected
176+
elif mode == 'json':
177+
assert ta.validate_json(json.dumps(input_value)) == expected
178+
assert ta.validate_json(json.dumps(input_value), strict=True) == expected
179+
else:
180+
assert ta.validate_strings(input_value) == expected
181+
182+
183+
@pytest.mark.parametrize(
184+
'input_value',
185+
[
186+
'1e4301',
187+
'1e-4301',
188+
'1E+4301',
189+
'1e4_301',
190+
'1.5e4301',
191+
'1e32000000',
192+
'1e-32000000',
193+
'1e99999999999999999999999',
194+
'1e32000000 ',
195+
'1e32000000\x1c',
196+
'1e٣٢٠٠٠٠٠٠', # 32000000 in Arabic-Indic digits
197+
'1e32000000', # 32000000 in fullwidth digits
198+
],
199+
)
200+
@pytest.mark.parametrize('mode', ['python', 'json', 'strings'])
201+
def test_fraction_exponent_too_large(input_value: str, mode: str) -> None:
202+
ta = TypeAdapter(Fraction)
203+
204+
with pytest.raises(ValidationError, check=lambda e: e.errors()[0]['type'] == 'fraction_parsing'):
205+
if mode == 'python':
206+
ta.validate_python(input_value)
207+
elif mode == 'json':
208+
ta.validate_json(json.dumps(input_value), strict=True)
209+
else:
210+
ta.validate_strings(input_value)
211+
212+
153213
@pytest.mark.parametrize(
154214
'input_value,expected',
155215
[

0 commit comments

Comments
 (0)