diff --git a/homeassistant/components/idrive_e2/backup.py b/homeassistant/components/idrive_e2/backup.py index 3bf1e9ead95f..2c7e4321ee0d 100644 --- a/homeassistant/components/idrive_e2/backup.py +++ b/homeassistant/components/idrive_e2/backup.py @@ -19,12 +19,15 @@ from homeassistant.components.backup import ( suggested_filename, ) from homeassistant.core import HomeAssistant, callback +from homeassistant.util.async_iterator import ResourceChunkIterator from . import IDriveE2ConfigEntry from .const import CONF_BUCKET, DATA_BACKUP_AGENT_LISTENERS, DOMAIN _LOGGER = logging.getLogger(__name__) CACHE_TTL = 300 +# Matches the default chunk size of aiobotocore's StreamingBody.iter_chunks +DOWNLOAD_CHUNK_SIZE = 1024 # S3 part size requirements: 5 MiB to 5 GiB per part # https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html @@ -122,7 +125,10 @@ class IDriveE2BackupAgent(BackupAgent): response = await cast(Any, self._client).get_object( Bucket=self._bucket, Key=tar_filename ) - return response["Body"].iter_chunks() + body = response["Body"] + return ResourceChunkIterator( + functools.partial(body.read, DOWNLOAD_CHUNK_SIZE), close=body.close + ) @override async def async_upload_backup( diff --git a/tests/components/idrive_e2/__init__.py b/tests/components/idrive_e2/__init__.py index d6240b42f9e2..d7677c8d3df5 100644 --- a/tests/components/idrive_e2/__init__.py +++ b/tests/components/idrive_e2/__init__.py @@ -1,5 +1,9 @@ """Tests for the IDrive e2 integration.""" +import asyncio +from unittest.mock import MagicMock + +from aiobotocore.response import StreamingBody from pytest_homeassistant.common import MockConfigEntry from homeassistant.core import HomeAssistant @@ -13,3 +17,11 @@ async def setup_integration( result = await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() return result + + +def mock_streaming_body(data: bytes) -> StreamingBody: + """Return a get_object body which streams data from a mocked response.""" + reader = asyncio.StreamReader() + reader.feed_data(data) + reader.feed_eof() + return StreamingBody(MagicMock(content=reader), str(len(data))) diff --git a/tests/components/idrive_e2/conftest.py b/tests/components/idrive_e2/conftest.py index f9c3bf3a44d7..eac34e312fed 100644 --- a/tests/components/idrive_e2/conftest.py +++ b/tests/components/idrive_e2/conftest.py @@ -1,6 +1,6 @@ """Common fixtures for the IDrive e2 tests.""" -from collections.abc import AsyncIterator, Generator +from collections.abc import Generator import json from unittest.mock import AsyncMock, MagicMock, patch @@ -15,14 +15,27 @@ from homeassistant.components.idrive_e2.backup import ( ) from homeassistant.components.idrive_e2.const import DOMAIN +from . import mock_streaming_body from .const import USER_INPUT +@pytest.fixture +def backup_data() -> bytes: + """Backup data, override in tests to change defaults.""" + return b"backup data" + + +@pytest.fixture +def backup_protected() -> bool: + """Backup protected, override in tests to change defaults.""" + return False + + @pytest.fixture( params=[2**20, MULTIPART_MIN_PART_SIZE_BYTES], ids=["small", "large"], ) -def agent_backup(request: pytest.FixtureRequest) -> AgentBackup: +def agent_backup(request: pytest.FixtureRequest, backup_protected: bool) -> AgentBackup: """Test backup fixture.""" return AgentBackup( addons=[], @@ -34,13 +47,13 @@ def agent_backup(request: pytest.FixtureRequest) -> AgentBackup: homeassistant_included=True, homeassistant_version="2024.12.0.dev0", name="Core 2024.12.0.dev0", - protected=False, + protected=backup_protected, size=request.param, ) @pytest.fixture(autouse=True) -def mock_client(agent_backup: AgentBackup) -> Generator[AsyncMock]: +def mock_client(agent_backup: AgentBackup, backup_data: bytes) -> Generator[AsyncMock]: """Mock the IDrive e2 client.""" with patch( "homeassistant.components.idrive_e2.AioSession.create_client", @@ -62,16 +75,13 @@ def mock_client(agent_backup: AgentBackup) -> Generator[AsyncMock]: "Buckets": [{"Name": USER_INPUT[CONF_BUCKET]}] } - # To simplify this mock, we assume that backup is always - # "iterated" over, while metadata is always "read" as a whole - class MockStream: - async def iter_chunks(self) -> AsyncIterator[bytes]: - yield b"backup data" - - async def read(self) -> bytes: - return json.dumps(agent_backup.as_dict()).encode() - - client.get_object.return_value = {"Body": MockStream()} + objects = { + tar_file: backup_data, + metadata_file: json.dumps(agent_backup.as_dict()).encode(), + } + client.get_object.side_effect = lambda **kwargs: { + "Body": mock_streaming_body(objects[kwargs["Key"].rsplit("/", 1)[-1]]) + } client.head_bucket.return_value = {} create_client.return_value.__aenter__.return_value = client diff --git a/tests/components/idrive_e2/test_backup.py b/tests/components/idrive_e2/test_backup.py index cf93b91a4d5d..fff00a01ab4b 100644 --- a/tests/components/idrive_e2/test_backup.py +++ b/tests/components/idrive_e2/test_backup.py @@ -1,15 +1,19 @@ """Test the IDrive e2 backup platform.""" +import asyncio from collections.abc import AsyncGenerator from datetime import timedelta from io import StringIO import json +from typing import Any from unittest.mock import AsyncMock, Mock, patch +from aiobotocore.response import StreamingBody +from aiohttp import ClientConnectionError, ClientPayloadError from botocore.exceptions import ConnectTimeoutError from freezegun.api import FrozenDateTimeFactory import pytest -from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry, get_fixture_path from pytest_homeassistant.typing import ( ClientSessionGenerator, MagicMock, @@ -41,6 +45,14 @@ MIB = 2**20 CHUNK_SIZES_MIB = (12, 12, 10, 12, 5) +# Protected with password "hunter2", padded beyond the 4 MiB read buffer so the +# backup is not read to the end when checking the password or decrypting it +PROTECTED_BACKUP_DATA = ( + get_fixture_path("test_backups/c0cb53bd.tar", BACKUP_DOMAIN).read_bytes() + + b"\0" * 12 * 2**20 +) + + @pytest.fixture(autouse=True) async def setup_backup_integration( hass: HomeAssistant, @@ -584,3 +596,112 @@ async def test_list_backups_with_pagination( "backup1", "backup2", } + + +@pytest.fixture +def downloaded_bodies(mock_client: MagicMock) -> list[StreamingBody]: + """Return the bodies of downloaded backup archives.""" + bodies: list[StreamingBody] = [] + get_object = mock_client.get_object.side_effect + + def get_object_and_track(**kwargs: Any) -> dict[str, Any]: + response = get_object(**kwargs) + if kwargs["Key"].endswith(".tar"): + bodies.append(response["Body"]) + return response + + mock_client.get_object.side_effect = get_object_and_track + return bodies + + +@pytest.mark.parametrize( + ("backup_protected", "backup_data"), + [pytest.param(True, PROTECTED_BACKUP_DATA, id="protected_backup")], +) +@pytest.mark.parametrize( + ("password", "success"), + [ + pytest.param("hunter2", True, id="correct_password"), + pytest.param("wrong", False, id="wrong_password"), + ], +) +async def test_can_decrypt_on_download_closes_body( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + mock_config_entry: MockConfigEntry, + downloaded_bodies: list[StreamingBody], + password: str, + success: bool, +) -> None: + """Test the download is closed after checking the password of a backup.""" + client = await hass_ws_client(hass) + + await client.send_json_auto_id( + { + "type": "backup/can_decrypt_on_download", + "backup_id": "23e64aec", + "agent_id": f"{DOMAIN}.{mock_config_entry.entry_id}", + "password": password, + } + ) + assert (await client.receive_json())["success"] is success + + assert len(downloaded_bodies) == 1 + downloaded_bodies[0].close.assert_called_once() + + +@pytest.mark.parametrize( + ("backup_protected", "backup_data"), + [pytest.param(True, PROTECTED_BACKUP_DATA, id="protected_backup")], +) +@pytest.mark.parametrize( + "query", + [ + pytest.param("", id="no_password"), + pytest.param("&password=hunter2", id="correct_password"), + pytest.param("&password=wrong", id="wrong_password"), + ], +) +async def test_agents_download_closes_body( + hass_client: ClientSessionGenerator, + mock_config_entry: MockConfigEntry, + downloaded_bodies: list[StreamingBody], + query: str, +) -> None: + """Test the download is closed when the backup is downloaded.""" + client = await hass_client() + + resp = await client.get( + f"/api/backup/download/23e64aec?agent_id={DOMAIN}.{mock_config_entry.entry_id}{query}" + ) + assert resp.status == 200 + await resp.read() + + assert len(downloaded_bodies) == 1 + downloaded_bodies[0].close.assert_called_once() + + +async def test_agents_download_closes_body_on_read_error( + hass_client: ClientSessionGenerator, + mock_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the download is closed when reading the backup fails.""" + reader = asyncio.StreamReader() + reader.set_exception(ClientConnectionError()) + response = MagicMock(content=reader) + get_object = mock_client.get_object.side_effect + mock_client.get_object.side_effect = lambda **kwargs: ( + {"Body": StreamingBody(response, "11")} + if kwargs["Key"].endswith(".tar") + else get_object(**kwargs) + ) + client = await hass_client() + + resp = await client.get( + f"/api/backup/download/23e64aec?agent_id={DOMAIN}.{mock_config_entry.entry_id}" + ) + with pytest.raises(ClientPayloadError): + await resp.read() + + response.close.assert_called_once()