Skip to content

Commit b537587

Browse files
Fix DurationType regex vulnerability and add tests (#160)
1 parent f9aa7cb commit b537587

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

src/celpy/celtypes.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1347,7 +1347,10 @@ def __new__(
13471347
raise ValueError("range error: {seconds}")
13481348
return super().__new__(cls, seconds=seconds, microseconds=nanos // 1000)
13491349
elif isinstance(seconds, str):
1350-
duration_pat = re.compile(r"^[-+]?([0-9]*(\.[0-9]*)?[a-z]+)+$")
1350+
valid_units = sorted(cls.scale.keys(), key=len, reverse=True)
1351+
units_pattern = r"(?:" + r"|".join(map(re.escape, valid_units)) + r")"
1352+
1353+
duration_pat = re.compile(rf"^[-+]?([0-9]*(\.[0-9]*)?{units_pattern})+$")
13511354

13521355
duration_match = duration_pat.match(seconds)
13531356
if not duration_match:
@@ -1369,7 +1372,7 @@ def __new__(
13691372
seconds = sign * fsum(
13701373
map(
13711374
lambda n_u: float(n_u.group(1)) * cls.scale[n_u.group(3)],
1372-
re.finditer(r"([0-9]*(\.[0-9]*)?)([a-z]+)", seconds),
1375+
re.finditer(rf"([0-9]*(\.[0-9]*)?)({units_pattern})", seconds),
13731376
)
13741377
)
13751378
except KeyError:

tests/test_celtypes.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,17 @@ def test_duration_type():
409409
assert DurationType("-2m30s").getSeconds() == IntType(-150)
410410
with pytest.raises(ValueError):
411411
DurationType("-2w30z")
412+
assert int(DurationType("1.5h").total_seconds()) == 5400
413+
assert DurationType("300ms").getMilliseconds() == IntType(300)
414+
assert DurationType("2ms").total_seconds() == 0.002
415+
with pytest.raises(ValueError):
416+
DurationType("300msec")
417+
with pytest.raises(ValueError):
418+
DurationType("2hours")
419+
with pytest.raises(ValueError):
420+
DurationType("15sec")
421+
with pytest.raises(ValueError):
422+
DurationType("2m30sx")
412423

413424

414425
def test_function_type():

0 commit comments

Comments
 (0)