From e1b60a85f54b2335da60f3040a00c3c62e724ade Mon Sep 17 00:00:00 2001 From: FayezBast Date: Thu, 26 Nov 2026 02:12:35 +0200 Subject: [PATCH] ngclient: Normalize streaming download errors Wrap streaming failures in DownloadError and close unread or incomplete urllib3 responses before returning their connections to the pool. Signed-off-by: FayezBast --- tests/test_fetcher_ng.py | 156 +++++++++++++++++++++++++++++++- tuf/ngclient/fetcher.py | 66 ++++++++++---- tuf/ngclient/urllib3_fetcher.py | 69 ++++++++++---- 3 files changed, 253 insertions(+), 38 deletions(-) diff --git a/tests/test_fetcher_ng.py b/tests/test_fetcher_ng.py index c956de20ac..fa5ef1c154 100644 --- a/tests/test_fetcher_ng.py +++ b/tests/test_fetcher_ng.py @@ -10,18 +10,50 @@ import sys import tempfile import unittest +from collections.abc import Generator, Iterator from typing import ClassVar -from unittest.mock import Mock, patch +from unittest.mock import MagicMock, Mock, call, patch import urllib3 from tests import utils from tuf.api import exceptions from tuf.ngclient import Urllib3Fetcher +from tuf.ngclient.fetcher import FetcherInterface logger = logging.getLogger(__name__) +class TestFetcherInterface(unittest.TestCase): + def test_custom_fetcher_stream_error(self) -> None: + stream_error = OSError("stream interrupted") + + class CustomFetcher(FetcherInterface): + def _fetch(self, url: str) -> Iterator[bytes]: + yield url.encode() + raise stream_error + + url = "https://example.com/file" + chunks = CustomFetcher().fetch(url) + self.assertEqual(next(chunks), url.encode()) + with self.assertRaises(exceptions.DownloadError) as cm: + next(chunks) + self.assertIs(cm.exception.__cause__, stream_error) + + @patch.object(Urllib3Fetcher, "_fetch") + def test_close_before_iteration(self, fetch: Mock) -> None: + stream = MagicMock(spec=Generator) + fetch.return_value = stream + + url = "https://example.com/file" + chunks = Urllib3Fetcher().fetch(url) + fetch.assert_called_once_with(url) + assert hasattr(chunks, "close") + chunks.close() + stream.close.assert_called_once_with() + stream.__next__.assert_not_called() + + class TestFetcher(unittest.TestCase): """Test Urllib3Fetcher class.""" @@ -59,6 +91,21 @@ def setUp(self) -> None: # Instantiate a concrete instance of FetcherInterface self.fetcher = Urllib3Fetcher() + def _pooled_response( + self, data: bytes, headers: dict[str, str] | None = None + ) -> tuple[urllib3.response.HTTPResponse, Mock]: + transport = Mock() + response = urllib3.response.HTTPResponse( + body=io.BytesIO(data), + status=200, + headers=headers, + preload_content=False, + pool=transport.pool, + connection=transport.connection, + ) + self.addCleanup(response.close) + return response, transport + # Simple fetch. def test_fetch(self) -> None: with tempfile.TemporaryFile() as temp_file: @@ -162,6 +209,113 @@ def test_download_bytes_read_timeout(self, mock_session_get: Mock) -> None: with self.assertRaises(exceptions.SlowRetrievalError): self.fetcher.download_bytes(self.url, self.file_length) + @patch.object(urllib3.PoolManager, "request") + def test_download_bytes_interrupted_stream(self, request: Mock) -> None: + stream_error = urllib3.exceptions.ProtocolError("stream interrupted") + + def interrupted_stream() -> Iterator[bytes]: + yield b"part" + raise stream_error + + response = request.return_value + response.status = 200 + response.stream.return_value = interrupted_stream() + + with self.assertRaises(exceptions.DownloadError) as cm: + self.fetcher.download_bytes(self.url, self.file_length) + self.assertIs(cm.exception.__cause__, stream_error) + response.release_conn.assert_called_once_with() + + @patch.object(urllib3.PoolManager, "request") + def test_close_stream(self, request: Mock) -> None: + response = request.return_value + response.status = 200 + response.stream.return_value = iter([b"first", b"second"]) + + chunks = self.fetcher.fetch(self.url) + self.assertEqual(next(chunks), b"first") + assert hasattr(chunks, "close") + chunks.close() + response.close.assert_called_once_with() + response.release_conn.assert_called_once_with() + + @patch.object(urllib3.PoolManager, "request") + def test_close_unread_response(self, request: Mock) -> None: + response, transport = self._pooled_response(b"unread data") + request.return_value = response + + chunks = self.fetcher.fetch(self.url) + request.assert_called_once() + assert hasattr(chunks, "close") + chunks.close() + chunks.close() + + self.assertEqual(list(chunks), []) + self.assertEqual(response.tell(), 0) + self.assertTrue(response.closed) + self.assertEqual( + transport.mock_calls, + [ + call.connection.close(), + call.pool._put_conn(transport.connection), + ], + ) + + @patch.object(urllib3.PoolManager, "request") + def test_close_response_on_decode_error(self, request: Mock) -> None: + data = b"uncompressed response content" + response, transport = self._pooled_response( + data, {"Content-Encoding": "gzip"} + ) + request.return_value = response + self.fetcher.chunk_size = 8 + + with self.assertRaises(exceptions.DownloadError) as cm: + self.fetcher.download_bytes(self.url, len(data)) + + self.assertIsInstance( + cm.exception.__cause__, urllib3.exceptions.DecodeError + ) + self.assertLess(response.tell(), len(data)) + self.assertTrue(response.closed) + self.assertEqual( + transport.mock_calls, + [ + call.connection.close(), + call.pool._put_conn(transport.connection), + ], + ) + + @patch.object(urllib3.PoolManager, "request") + def test_complete_read_releases_connection(self, request: Mock) -> None: + data = b"complete response content" + response, transport = self._pooled_response(data) + request.return_value = response + + self.assertEqual(self.fetcher.download_bytes(self.url, len(data)), data) + self.assertEqual( + transport.mock_calls, [call.pool._put_conn(transport.connection)] + ) + + @patch.object(Urllib3Fetcher, "_fetch") + @patch("tuf.ngclient.fetcher.tempfile.TemporaryFile") + def test_download_bytes_local_write_error( + self, temporary_file: Mock, fetch: Mock + ) -> None: + stream = MagicMock(spec=Generator) + stream.__next__.return_value = b"part" + stream.close.side_effect = OSError("close failed") + fetch.return_value = stream + write_error = OSError("local write failed") + temporary_file.return_value.__enter__.return_value.write.side_effect = ( + write_error + ) + + with self.assertRaises(OSError) as cm: + self.fetcher.download_bytes(self.url, self.file_length) + self.assertIs(cm.exception, write_error) + stream.close.assert_called_once_with() + # Read/connect session timeout error @patch.object( urllib3.PoolManager, diff --git a/tuf/ngclient/fetcher.py b/tuf/ngclient/fetcher.py index 8f1228ebc1..0a6250ff70 100644 --- a/tuf/ngclient/fetcher.py +++ b/tuf/ngclient/fetcher.py @@ -8,7 +8,7 @@ import logging import tempfile from collections.abc import Iterator -from contextlib import contextmanager +from contextlib import contextmanager, suppress from typing import IO from tuf.api import exceptions @@ -16,7 +16,29 @@ logger = logging.getLogger(__name__) -# Classes +class _DownloadIterator(Iterator[bytes]): + """Normalize stream errors and forward explicit close calls.""" + + def __init__(self, chunks: Iterator[bytes], url: str) -> None: + self._chunks = chunks + self._url = url + + def __next__(self) -> bytes: + try: + return next(self._chunks) + except (StopIteration, exceptions.DownloadError): + raise + except Exception as e: + raise exceptions.DownloadError( + f"Failed to download {self._url}" + ) from e + + def close(self) -> None: + close = getattr(self._chunks, "close", None) + if close is not None: + close() + + class FetcherInterface(metaclass=abc.ABCMeta): """Defines an interface for abstract network download. @@ -37,7 +59,7 @@ def _fetch(self, url: str) -> Iterator[bytes]: Implementations may raise any errors but the ones that are not ``DownloadErrors`` will be wrapped in a ``DownloadError`` by - ``fetch()``. + ``fetch()``, including errors raised while iterating over the chunks. Args: url: URL string that represents a file location. @@ -63,15 +85,16 @@ def fetch(self, url: str) -> Iterator[bytes]: Returns: Bytes iterator """ - # Ensure that fetch() only raises DownloadErrors, regardless of the - # fetcher implementation + # Start the download now so connection and HTTP errors stay immediate. try: - return self._fetch(url) - except exceptions.DownloadError as e: - raise e + chunks = self._fetch(url) + except exceptions.DownloadError: + raise except Exception as e: raise exceptions.DownloadError(f"Failed to download {url}") from e + return _DownloadIterator(chunks, url) + @contextmanager def download_file(self, url: str, max_length: int) -> Iterator[IO]: """Download file from given ``url``. @@ -99,15 +122,24 @@ def download_file(self, url: str, max_length: int) -> Iterator[IO]: with tempfile.TemporaryFile() as temp_file: chunks = self.fetch(url) - for chunk in chunks: - number_of_bytes_received += len(chunk) - if number_of_bytes_received > max_length: - raise exceptions.DownloadLengthMismatchError( - f"Downloaded {number_of_bytes_received} bytes exceeding" - f" the maximum allowed length of {max_length}" - ) - - temp_file.write(chunk) + try: + for chunk in chunks: + number_of_bytes_received += len(chunk) + if number_of_bytes_received > max_length: + raise exceptions.DownloadLengthMismatchError( + f"Downloaded {number_of_bytes_received} bytes " + "exceeding the maximum allowed length of " + f"{max_length}" + ) + + temp_file.write(chunk) + except BaseException: + # Preserve the original error if closing the stream fails. + with suppress(Exception): + close = getattr(chunks, "close", None) + if close is not None: + close() + raise logger.debug( "Downloaded %d out of %d bytes", diff --git a/tuf/ngclient/urllib3_fetcher.py b/tuf/ngclient/urllib3_fetcher.py index baec8fe9df..0b47a4c7a6 100644 --- a/tuf/ngclient/urllib3_fetcher.py +++ b/tuf/ngclient/urllib3_fetcher.py @@ -8,6 +8,8 @@ from __future__ import annotations import logging +from collections.abc import Iterator +from contextlib import suppress from typing import TYPE_CHECKING # Imports @@ -19,13 +21,43 @@ from tuf.ngclient.fetcher import FetcherInterface if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Generator # Globals logger = logging.getLogger(__name__) -# Classes +def _discard_response(response: urllib3.response.BaseHTTPResponse) -> None: + """Close the response before returning its connection to the pool.""" + response.close() + response.release_conn() + + +class _ResponseStream(Iterator[bytes]): + """Own the response until the chunk generator starts reading.""" + + def __init__( + self, + response: urllib3.response.BaseHTTPResponse, + chunks: Generator[bytes, None, None], + ) -> None: + self._unread_response: urllib3.response.BaseHTTPResponse | None = ( + response + ) + self._chunks = chunks + + def __next__(self) -> bytes: + self._unread_response = None + return next(self._chunks) + + def close(self) -> None: + response = self._unread_response + self._unread_response = None + self._chunks.close() + if response is not None: + _discard_response(response) + + class Urllib3Fetcher(FetcherInterface): """An implementation of ``FetcherInterface`` based on the urllib3 library. @@ -92,29 +124,26 @@ def _fetch(self, url: str) -> Iterator[bytes]: response.status, ) - return self._chunks(response) + return _ResponseStream(response, self._chunks(response)) def _chunks( self, response: urllib3.response.BaseHTTPResponse - ) -> Iterator[bytes]: - """A generator function to be returned by fetch. - - This way the caller of fetch can differentiate between connection - and actual data download. - """ - + ) -> Generator[bytes, None, None]: + """Stream the response body and manage its connection on exit.""" try: yield from response.stream(self.chunk_size) - except urllib3.exceptions.TimeoutError as e: - # Raised directly when the gap timeout expires mid-stream: - # ReadTimeoutError is a TimeoutError but not a MaxRetryError. - raise exceptions.SlowRetrievalError from e - except urllib3.exceptions.MaxRetryError as e: - if isinstance(e.reason, urllib3.exceptions.TimeoutError): + except GeneratorExit: + _discard_response(response) + raise + except BaseException as e: + # Preserve the original failure if discarding the response fails. + with suppress(Exception): + _discard_response(response) + if isinstance(e, urllib3.exceptions.TimeoutError) or ( + isinstance(e, urllib3.exceptions.MaxRetryError) + and isinstance(e.reason, urllib3.exceptions.TimeoutError) + ): raise exceptions.SlowRetrievalError from e - # Any other reason: propagate rather than ending the stream - # silently, which would look like a complete download. raise - - finally: + else: response.release_conn()