diff --git a/docs/how-to/parse-errors.rst b/docs/how-to/parse-errors.rst index cbaec5db4..a43414570 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 e40136ca0..0b9d4f344 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-8.0.0-prek: diff --git a/news/1793.breaking b/news/1793.breaking new file mode 100644 index 000000000..8d971c827 --- /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. :user:`Hrittik20` diff --git a/src/icalendar/__init__.py b/src/icalendar/__init__.py index 1684a0e07..f158de813 100644 --- a/src/icalendar/__init__.py +++ b/src/icalendar/__init__.py @@ -35,10 +35,12 @@ ) from icalendar.error import ( BrokenCalendarProperty, + CalendarDecodeError, ComponentEndMissing, ComponentStartMissing, FeatureWillBeRemovedInFutureVersion, GloballyUniqueTZIDGuessed, + ICalDecodeError, ICalParsingError, IncompleteAlarmInformation, IncompleteComponent, @@ -126,6 +128,7 @@ "Available", "BrokenCalendarProperty", "Calendar", + "CalendarDecodeError", "Component", "ComponentEndMissing", "ComponentFactory", @@ -135,6 +138,7 @@ "FeatureWillBeRemovedInFutureVersion", "FreeBusy", "GloballyUniqueTZIDGuessed", + "ICalDecodeError", "ICalParsingError", "Image", "IncompleteAlarmInformation", diff --git a/src/icalendar/error.py b/src/icalendar/error.py index d49cad92c..8e5620f30 100644 --- a/src/icalendar/error.py +++ b/src/icalendar/error.py @@ -55,6 +55,69 @@ def __init__( super().__init__(full_message) +class CalendarDecodeError(InvalidCalendar): + """The calendar data could not be decoded. + + :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. + + 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, + open an issue related to :issue:`1793`. + + 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.""" + + 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: + 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 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" + ) + 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. @@ -403,9 +466,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 085df53e0..acf97a638 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 @@ -78,11 +83,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 4a200327f..70398a3b1 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 + #: The supported sequence types. SEQUENCE_TYPES = (list, tuple) #: The default encoding to use when encoding or decoding iCalendar data. @@ -35,16 +37,23 @@ 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: + ~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