From 2dcf17d23da828411bba262332124f2808b73c05 Mon Sep 17 00:00:00 2001 From: Hrittik RoyChoudhury Date: Thu, 5 Nov 2026 20:58:59 +0530 Subject: [PATCH 1/9] Raise ICalDecodeError for calendar data that is not UTF-8 AI: Claude Opus 5.5 drafted the code, tests and docs. I reviewed them. --- docs/how-to/parse-errors.rst | 35 ++++++++++ docs/how-to/upgrade.rst | 27 +++++++- news/1793.breaking | 1 + src/icalendar/__init__.py | 4 ++ src/icalendar/error.py | 66 +++++++++++++++++++ src/icalendar/parser/ical/component.py | 18 +++-- src/icalendar/parser_tools.py | 13 +++- src/icalendar/tests/prop/test_unit.py | 11 ++-- .../tests/test_issue_1793_invalid_utf8.py | 54 +++++++++++++++ src/icalendar/tests/test_unit_parser_tools.py | 4 +- 10 files changed, 214 insertions(+), 19 deletions(-) create mode 100644 news/1793.breaking create mode 100644 src/icalendar/tests/test_issue_1793_invalid_utf8.py diff --git a/docs/how-to/parse-errors.rst b/docs/how-to/parse-errors.rst index cbaec5db4..2ab99d244 100644 --- a/docs/how-to/parse-errors.rst +++ b/docs/how-to/parse-errors.rst @@ -139,3 +139,38 @@ When you access a property descriptor like :attr:`event.DTSTART ` raises an :class:`~icalendar.error.ICalDecodeError`. + +.. code-block:: pycon + + >>> from icalendar import ICalDecodeError + >>> data = b"BEGIN:VCALENDAR\r\nPRODID:R\xe9union\r\nEND:VCALENDAR\r\n" + >>> try: + ... Calendar.from_ical(data) + ... except ICalDecodeError as e: + ... print(f"Line {e.line_number}: {e.value!r}") + Line 2: b'\xe9' + +icalendar does not guess the encoding, because a wrong guess silently turns the text into different characters. +If you know the encoding of the data, decode it yourself and pass the string. + +.. code-block:: pycon + + >>> calendar = Calendar.from_ical(data.decode("cp1252")) + >>> print(calendar["PRODID"]) + Réunion + +If you prefer the behavior of earlier versions of icalendar, which replaced the invalid bytes with the replacement character ``�``, decode the data with ``errors="replace"``. + +.. code-block:: pycon + + >>> calendar = Calendar.from_ical(data.decode("utf-8", errors="replace")) + >>> print(calendar["PRODID"]) + R�union diff --git a/docs/how-to/upgrade.rst b/docs/how-to/upgrade.rst index 55ee9bad2..34413cc87 100644 --- a/docs/how-to/upgrade.rst +++ b/docs/how-to/upgrade.rst @@ -66,12 +66,11 @@ The example below shows how to correctly access binary data: >>> v_binary.bytes[:4] # correct access for PNG image data b'\x89PNG' -For backward compatibility, if corrupt data is acceptable and you need to get the bytes as a Unicode string, use :meth:`~icalendar.parser_tools.to_unicode` as shown in the following code: +For backward compatibility, if corrupt data is acceptable and you need to get the bytes as a Unicode string, decode them with ``errors="replace"`` as shown in the following code: .. code-block:: pycon - >>> from icalendar.parser_tools import to_unicode - >>> string = to_unicode(v_binary.bytes) # corrupts data + >>> string = v_binary.bytes.decode("utf-8", errors="replace") # corrupts data .. _removed-from-icalendar-parser-string: @@ -86,6 +85,28 @@ These functions have been removed from :mod:`icalendar.parser.string`: * ``unescape_char`` * ``unescape_string`` +.. _from-ical-not-utf-8: + +``Component.from_ical`` raises an error for data that is not UTF-8 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +:meth:`Component.from_ical ` used to replace bytes that are not valid UTF-8 with ``�``, which silently corrupted the text. +It now raises an :class:`~icalendar.error.ICalDecodeError` instead. + +If you know the encoding of the data, decode it yourself and pass the string: + +.. code-block:: python + + calendar = Calendar.from_ical(data.decode("cp1252")) + +If you want the previous behavior, decode the data with ``errors="replace"``: + +.. code-block:: python + + calendar = Calendar.from_ical(data.decode("utf-8", errors="replace")) + +See :doc:`parse-errors` for more information. + .. _upgrade-7.0.0: diff --git a/news/1793.breaking b/news/1793.breaking new file mode 100644 index 000000000..796f19692 --- /dev/null +++ b/news/1793.breaking @@ -0,0 +1 @@ +Changed :meth:`Calendar.from_ical ` to raise :class:`~icalendar.error.ICalDecodeError` when the data is not valid UTF-8. Previously, it silently replaced the invalid bytes with ``�``. If you know the encoding of the data, decode it yourself before parsing, as described in :ref:`from-ical-not-utf-8`. I used AI to assist me with this change. @Hrittik20 diff --git a/src/icalendar/__init__.py b/src/icalendar/__init__.py index 919dac284..40b93532c 100644 --- a/src/icalendar/__init__.py +++ b/src/icalendar/__init__.py @@ -34,10 +34,12 @@ ) from icalendar.error import ( BrokenCalendarProperty, + CalendarDecodeError, ComponentEndMissing, ComponentStartMissing, FeatureWillBeRemovedInFutureVersion, GloballyUniqueTZIDGuessed, + ICalDecodeError, ICalParsingError, IncompleteAlarmInformation, IncompleteComponent, @@ -124,6 +126,7 @@ "Available", "BrokenCalendarProperty", "Calendar", + "CalendarDecodeError", "Component", "ComponentEndMissing", "ComponentFactory", @@ -133,6 +136,7 @@ "FeatureWillBeRemovedInFutureVersion", "FreeBusy", "GloballyUniqueTZIDGuessed", + "ICalDecodeError", "ICalParsingError", "Image", "IncompleteAlarmInformation", diff --git a/src/icalendar/error.py b/src/icalendar/error.py index 3c10b6c46..43aa36146 100644 --- a/src/icalendar/error.py +++ b/src/icalendar/error.py @@ -55,6 +55,70 @@ def __init__( super().__init__(full_message) +class CalendarDecodeError(InvalidCalendar): + """The calendar data could not be decoded. + + :rfc:`5545#section-3.1.4` requires iCalendar data to be UTF-8. + icalendar does not guess another encoding, + because a wrong guess silently turns the text into different characters. + + If you know the encoding of the data, decode it yourself and pass the string + to :meth:`Calendar.from_ical `. + See :doc:`/how-to/parse-errors` for examples. + If you get such calendars from a well-known application, + please open an issue related to :issue:`1793`. + + The original :class:`UnicodeDecodeError` is chained as ``__cause__``. + + .. versionadded:: 0.0.0 + """ + + encoding: str + """The encoding that was used to decode the data.""" + + value: bytes + """The bytes that could not be decoded.""" + + start: int + """The position of the first byte that could not be decoded.""" + + line_number: int + """The line of the bytes that could not be decoded, starting at 1.""" + + def __init__(self, error: UnicodeDecodeError) -> None: + """Create a new CalendarDecodeError. + + Parameters: + error: The error raised while decoding the data. + """ + value = error.object[error.start : error.end] + line_number = error.object.count(b"\n", 0, error.start) + 1 + super().__init__( + f"Could not decode {value!r} at position {error.start} (line " + f"{line_number}) as {error.encoding}. RFC 5545 requires iCalendar " + "data to be UTF-8. To find out how to proceed, see " + "https://icalendar.readthedocs.io/en/stable/reference/api/" + "icalendar.error.html#icalendar.error.CalendarDecodeError " + "and https://github.com/collective/icalendar/issues/1793" + ) + self.encoding = error.encoding + self.value = value + self.start = error.start + self.line_number = line_number + + +class ICalDecodeError(CalendarDecodeError, ICalParsingError): + """The iCalendar data could not be decoded. + + :meth:`Component.from_ical ` + raises this error, so you can catch it as either + :class:`~icalendar.error.CalendarDecodeError` or + :class:`~icalendar.error.ICalParsingError`. + + .. versionadded:: 0.0.0 + """ + + class BrokenCalendarProperty(InvalidCalendar): """A property could not be parsed and its value is broken. @@ -399,9 +463,11 @@ def __init__( __all__ = [ "BrokenCalendarProperty", + "CalendarDecodeError", "ComponentEndMissing", "ComponentStartMissing", "FeatureWillBeRemovedInFutureVersion", + "ICalDecodeError", "ICalParsingError", "IncompleteAlarmInformation", "IncompleteComponent", diff --git a/src/icalendar/parser/ical/component.py b/src/icalendar/parser/ical/component.py index 7f87b0972..cf2c61b40 100644 --- a/src/icalendar/parser/ical/component.py +++ b/src/icalendar/parser/ical/component.py @@ -4,7 +4,12 @@ from typing import TYPE_CHECKING, ClassVar -from icalendar.error import ICalParsingError, InvalidToken +from icalendar.error import ( + CalendarDecodeError, + ICalDecodeError, + ICalParsingError, + InvalidToken, +) from icalendar.parser.content_line import Contentline, Contentlines from icalendar.parser.property import split_on_unescaped_comma from icalendar.prop import vBroken @@ -79,11 +84,12 @@ def contains_uid(self, uid: str) -> bool: def initialize_parsing(self): self._stack: list[Component] = [] self._components: list[Component] = [] - self._data = self._content_lines = ( - self._data - if isinstance(self._data, list) - else Contentlines.from_ical(self._data) - ) + if not isinstance(self._data, list): + try: + self._data = Contentlines.from_ical(self._data) + except CalendarDecodeError as error: + raise ICalDecodeError(error.__cause__) from error.__cause__ + self._content_lines = self._data self._content_lines_iterator = iter(self._content_lines) def handle_line_parse_error(self, exception: Exception): diff --git a/src/icalendar/parser_tools.py b/src/icalendar/parser_tools.py index a2d368789..701bbe11e 100644 --- a/src/icalendar/parser_tools.py +++ b/src/icalendar/parser_tools.py @@ -2,6 +2,8 @@ from __future__ import annotations +from icalendar.error import CalendarDecodeError + SEQUENCE_TYPES = (list, tuple) DEFAULT_ENCODING = "utf-8" ICAL_TYPE = str | bytes @@ -34,14 +36,21 @@ def to_unicode(value: ICAL_TYPE, encoding: str = "utf-8-sig") -> str: Parameters: value: The value to convert. encoding: The encoding to use in the conversion. + + Raises: + ~icalendar.error.CalendarDecodeError: If ``value`` cannot be decoded. + + .. versionchanged:: 0.0.0 + Raise :class:`~icalendar.error.CalendarDecodeError` instead of + replacing bytes that cannot be decoded. """ if isinstance(value, str): return value if isinstance(value, bytes): try: return value.decode(encoding) - except UnicodeDecodeError: - return value.decode("utf-8-sig", "replace") + except UnicodeDecodeError as error: + raise CalendarDecodeError(error) from error else: return value diff --git a/src/icalendar/tests/prop/test_unit.py b/src/icalendar/tests/prop/test_unit.py index 0a34e8b4b..fe22cd56a 100644 --- a/src/icalendar/tests/prop/test_unit.py +++ b/src/icalendar/tests/prop/test_unit.py @@ -3,6 +3,7 @@ import pytest +from icalendar.error import CalendarDecodeError from icalendar.parser import Parameters from icalendar.prop.factory import TypesFactory @@ -228,13 +229,9 @@ def test_prop_vText(self): ).parts() assert vText.from_ical(value) == "A string with; some\\ characters in\\it" - # We are forgiving to utf-8 encoding errors: - # We intentionally use a string with unexpected encoding - # - assert vText.from_ical(b"Ol\xe9") == "Ol�" - - # Notice how accented E character, encoded with latin-1, got replaced - # with the official U+FFFD REPLACEMENT CHARACTER. + # Bytes with an unexpected encoding are not replaced, see issue 1793. + with pytest.raises(CalendarDecodeError): + vText.from_ical(b"Ol\xe9") def test_prop_vTime(self): from icalendar.prop import vTime diff --git a/src/icalendar/tests/test_issue_1793_invalid_utf8.py b/src/icalendar/tests/test_issue_1793_invalid_utf8.py new file mode 100644 index 000000000..9cf62b51e --- /dev/null +++ b/src/icalendar/tests/test_issue_1793_invalid_utf8.py @@ -0,0 +1,54 @@ +"""Calendar data that is not valid UTF-8 raises an error instead of being corrupted. + +See https://github.com/collective/icalendar/issues/1793 +""" + +import pytest + +from icalendar import ( + Calendar, + CalendarDecodeError, + ICalDecodeError, + ICalParsingError, + LazyCalendar, +) + +# \xe9 is "é" in cp1252, but not valid UTF-8 +CP1252_CALENDAR = ( + b"BEGIN:VCALENDAR\r\n" + b"VERSION:2.0\r\n" + b"BEGIN:VEVENT\r\n" + b"SUMMARY:R\xe9union\r\n" + b"END:VEVENT\r\n" + b"END:VCALENDAR\r\n" +) + + +@pytest.mark.parametrize("calendar_class", [Calendar, LazyCalendar]) +def test_from_ical_raises_for_invalid_utf8(calendar_class): + with pytest.raises(ICalDecodeError): + calendar_class.from_ical(CP1252_CALENDAR) + + +def test_error_can_be_caught_as_parsing_or_decode_error(): + with pytest.raises(ICalParsingError): + Calendar.from_ical(CP1252_CALENDAR) + with pytest.raises(CalendarDecodeError): + Calendar.from_ical(CP1252_CALENDAR) + + +def test_error_information(): + with pytest.raises(ICalDecodeError) as exc_info: + Calendar.from_ical(CP1252_CALENDAR) + error = exc_info.value + assert error.encoding == "utf-8" + assert error.value == b"\xe9" + assert error.start == CP1252_CALENDAR.index(b"\xe9") + assert error.line_number == 4 + assert isinstance(error.__cause__, UnicodeDecodeError) + assert "issues/1793" in str(error) + + +def test_decode_with_known_encoding(): + calendar = Calendar.from_ical(CP1252_CALENDAR.decode("cp1252")) + assert calendar.events[0]["SUMMARY"] == "Réunion" diff --git a/src/icalendar/tests/test_unit_parser_tools.py b/src/icalendar/tests/test_unit_parser_tools.py index 849a90fc1..7cbc3ad9e 100644 --- a/src/icalendar/tests/test_unit_parser_tools.py +++ b/src/icalendar/tests/test_unit_parser_tools.py @@ -1,5 +1,6 @@ import unittest +from icalendar.error import CalendarDecodeError from icalendar.parser_tools import data_encode, from_unicode, to_unicode @@ -10,7 +11,8 @@ def test_parser_tools_to_unicode(self): assert to_unicode(b"spam") == "spam" assert to_unicode(b"\xc6\xb5") == "Ƶ" assert to_unicode(b"\xc6\xb5") == "Ƶ" - assert to_unicode(b"\xc6\xb5", encoding="ascii") == "Ƶ" + with self.assertRaises(CalendarDecodeError): + to_unicode(b"\xc6\xb5", encoding="ascii") assert to_unicode(1) == 1 assert to_unicode(None) is None From ef087d34a23203c5585601069aa42d862ef99e08 Mon Sep 17 00:00:00 2001 From: Hrittik <49366463+Hrittik20@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:07:54 +0530 Subject: [PATCH 2/9] Update src/icalendar/error.py Co-authored-by: Steve Piercy --- src/icalendar/error.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/icalendar/error.py b/src/icalendar/error.py index 69a26ccbd..bfadeee0c 100644 --- a/src/icalendar/error.py +++ b/src/icalendar/error.py @@ -66,7 +66,7 @@ class CalendarDecodeError(InvalidCalendar): to :meth:`Calendar.from_ical `. See :doc:`/how-to/parse-errors` for examples. If you get such calendars from a well-known application, - please open an issue related to :issue:`1793`. + open an issue related to :issue:`1793`. The original :class:`UnicodeDecodeError` is chained as ``__cause__``. From 974e29b3fad1d39df7d3a5b7a240a460a6da7156 Mon Sep 17 00:00:00 2001 From: Hrittik <49366463+Hrittik20@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:08:05 +0530 Subject: [PATCH 3/9] Update src/icalendar/error.py Co-authored-by: Steve Piercy --- src/icalendar/error.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/icalendar/error.py b/src/icalendar/error.py index bfadeee0c..f054d6417 100644 --- a/src/icalendar/error.py +++ b/src/icalendar/error.py @@ -58,7 +58,8 @@ def __init__( class CalendarDecodeError(InvalidCalendar): """The calendar data could not be decoded. - :rfc:`5545#section-3.1.4` requires iCalendar data to be UTF-8. + :rfc:`5545#section-3.1.4` sets the default character set encoding + of iCalendar data to UTF-8. icalendar does not guess another encoding, because a wrong guess silently turns the text into different characters. From f275417b317f0c35e0fa61ae9b7d17f571910da0 Mon Sep 17 00:00:00 2001 From: Hrittik <49366463+Hrittik20@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:08:13 +0530 Subject: [PATCH 4/9] Update src/icalendar/error.py Co-authored-by: Steve Piercy --- src/icalendar/error.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/icalendar/error.py b/src/icalendar/error.py index f054d6417..b78536f0d 100644 --- a/src/icalendar/error.py +++ b/src/icalendar/error.py @@ -72,7 +72,10 @@ class CalendarDecodeError(InvalidCalendar): The original :class:`UnicodeDecodeError` is chained as ``__cause__``. .. versionadded:: 0.0.0 - """ + + Parameters: + error: The error raised while decoding the data. + """" encoding: str """The encoding that was used to decode the data.""" From 82db4ced4e4171ff3c27ba0ef920f9812f91e66b Mon Sep 17 00:00:00 2001 From: Hrittik <49366463+Hrittik20@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:08:26 +0530 Subject: [PATCH 5/9] Update src/icalendar/error.py Co-authored-by: Steve Piercy --- src/icalendar/error.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/icalendar/error.py b/src/icalendar/error.py index b78536f0d..d9ead8157 100644 --- a/src/icalendar/error.py +++ b/src/icalendar/error.py @@ -90,11 +90,6 @@ class CalendarDecodeError(InvalidCalendar): """The line of the bytes that could not be decoded, starting at 1.""" def __init__(self, error: UnicodeDecodeError) -> None: - """Create a new CalendarDecodeError. - - Parameters: - error: The error raised while decoding the data. - """ value = error.object[error.start : error.end] line_number = error.object.count(b"\n", 0, error.start) + 1 super().__init__( From 193623ef1f651400d25d46bf0c88378c2d55a654 Mon Sep 17 00:00:00 2001 From: Hrittik <49366463+Hrittik20@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:08:37 +0530 Subject: [PATCH 6/9] Update src/icalendar/parser_tools.py Co-authored-by: Steve Piercy --- src/icalendar/parser_tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/icalendar/parser_tools.py b/src/icalendar/parser_tools.py index 12d589ad9..70398a3b1 100644 --- a/src/icalendar/parser_tools.py +++ b/src/icalendar/parser_tools.py @@ -37,7 +37,7 @@ def to_unicode(value: ICAL_TYPE, encoding: str = "utf-8-sig") -> str: """Converts a value to Unicode, even if it is already a Unicode string. Parameters: - value: The value to convert. + value: Required. The value to convert. encoding: The encoding to use in the conversion. Raises: From 9b2fb919f5b51a10fd9e104cd48be113b0a474bf Mon Sep 17 00:00:00 2001 From: Hrittik <49366463+Hrittik20@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:08:46 +0530 Subject: [PATCH 7/9] Update news/1793.breaking Co-authored-by: Steve Piercy --- news/1793.breaking | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/news/1793.breaking b/news/1793.breaking index 796f19692..8d971c827 100644 --- a/news/1793.breaking +++ b/news/1793.breaking @@ -1 +1 @@ -Changed :meth:`Calendar.from_ical ` to raise :class:`~icalendar.error.ICalDecodeError` when the data is not valid UTF-8. Previously, it silently replaced the invalid bytes with ``�``. If you know the encoding of the data, decode it yourself before parsing, as described in :ref:`from-ical-not-utf-8`. I used AI to assist me with this change. @Hrittik20 +Changed :meth:`Calendar.from_ical ` to raise :class:`~icalendar.error.ICalDecodeError` when the data is not valid UTF-8. Previously, it silently replaced the invalid bytes with ``�``. If you know the encoding of the data, decode it yourself before parsing, as described in :ref:`from-ical-not-utf-8`. I used AI to assist me with this change. :user:`Hrittik20` From 570f36d8caa4f2546be1a01aec05dd8c6d40b8ed Mon Sep 17 00:00:00 2001 From: Hrittik <49366463+Hrittik20@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:08:56 +0530 Subject: [PATCH 8/9] Update docs/how-to/parse-errors.rst Co-authored-by: Steve Piercy --- docs/how-to/parse-errors.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/how-to/parse-errors.rst b/docs/how-to/parse-errors.rst index 2ab99d244..a43414570 100644 --- a/docs/how-to/parse-errors.rst +++ b/docs/how-to/parse-errors.rst @@ -144,7 +144,7 @@ When you access a property descriptor like :attr:`event.DTSTART ` raises an :class:`~icalendar.error.ICalDecodeError`. From 61232b819cae55a7da838d7de6e4d30a63da7bc9 Mon Sep 17 00:00:00 2001 From: Hrittik RoyChoudhury Date: Mon, 23 Nov 2026 19:16:17 +0530 Subject: [PATCH 9/9] Fix CalendarDecodeError docstring and sync error message with docs --- src/icalendar/error.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/icalendar/error.py b/src/icalendar/error.py index d9ead8157..8e5620f30 100644 --- a/src/icalendar/error.py +++ b/src/icalendar/error.py @@ -75,7 +75,7 @@ class CalendarDecodeError(InvalidCalendar): Parameters: error: The error raised while decoding the data. - """" + """ encoding: str """The encoding that was used to decode the data.""" @@ -94,8 +94,8 @@ def __init__(self, error: UnicodeDecodeError) -> None: line_number = error.object.count(b"\n", 0, error.start) + 1 super().__init__( f"Could not decode {value!r} at position {error.start} (line " - f"{line_number}) as {error.encoding}. RFC 5545 requires iCalendar " - "data to be UTF-8. To find out how to proceed, see " + f"{line_number}) as {error.encoding}. RFC 5545 sets the default " + "encoding of iCalendar data to UTF-8. To find out how to proceed, see " "https://icalendar.readthedocs.io/en/stable/reference/api/" "icalendar.error.html#icalendar.error.CalendarDecodeError " "and https://github.com/collective/icalendar/issues/1793"