From a0b70473fc08611aa7ecdc50ce4404e882d9e7f9 Mon Sep 17 00:00:00 2001 From: Eric Eastwood Date: Wed, 29 Jan 2025 18:14:02 -0600 Subject: [PATCH] Raise an error if someone is using an incorrect suffix in a config duration string (#18112) Previously, a value like `5q` would be interpreted as 5 milliseconds. We should just raise an error instead of letting someone run with a misconfiguration. --- changelog.d/18112.bugfix | 1 + synapse/config/_base.py | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 changelog.d/18112.bugfix diff --git a/changelog.d/18112.bugfix b/changelog.d/18112.bugfix new file mode 100644 index 000000000..61c94280d --- /dev/null +++ b/changelog.d/18112.bugfix @@ -0,0 +1 @@ +Raise an error if someone is using an incorrect suffix in a config duration string. diff --git a/synapse/config/_base.py b/synapse/config/_base.py index adce34c03..912346a42 100644 --- a/synapse/config/_base.py +++ b/synapse/config/_base.py @@ -221,9 +221,13 @@ class Config: The number of milliseconds in the duration. Raises: - TypeError, if given something other than an integer or a string + TypeError: if given something other than an integer or a string, or the + duration is using an incorrect suffix. ValueError: if given a string not of the form described above. """ + # For integers, we prefer to use `type(value) is int` instead of + # `isinstance(value, int)` because we want to exclude subclasses of int, such as + # bool. if type(value) is int: # noqa: E721 return value elif isinstance(value, str): @@ -246,9 +250,20 @@ class Config: if suffix in sizes: value = value[:-1] size = sizes[suffix] + elif suffix.isdigit(): + # No suffix is treated as milliseconds. + value = value + size = 1 + else: + raise TypeError( + f"Bad duration suffix {value} (expected no suffix or one of these suffixes: {sizes.keys()})" + ) + return int(value) * size else: - raise TypeError(f"Bad duration {value!r}") + raise TypeError( + f"Bad duration type {value!r} (expected int or string duration)" + ) @staticmethod def abspath(file_path: str) -> str: