Close backup download stream in coudflare_r2 when not fully read (#188684)

This commit is contained in:
Erik Montnemery
2026-10-26 12:51:55 +01:00
committed by GitHub
parent 44a2e172fd
commit bd125a78a8
4 changed files with 165 additions and 14 deletions
@@ -19,12 +19,15 @@ from homeassistant.components.backup import (
)
from homeassistant.const import CONF_PREFIX
from homeassistant.core import HomeAssistant, callback
from homeassistant.util.async_iterator import ResourceChunkIterator
from . import R2ConfigEntry
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
# We set the threshold to 20 MiB to avoid too many parts.
@@ -125,7 +128,10 @@ class R2BackupAgent(BackupAgent):
response = await self._client.get_object(
Bucket=self._bucket, Key=self._with_prefix(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(
@@ -1,5 +1,9 @@
"""Tests for the Cloudflare R2 integration."""
import asyncio
from unittest.mock import MagicMock
from aiobotocore.response import StreamingBody
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.core import HomeAssistant
@@ -12,3 +16,11 @@ async def setup_integration(
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
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)))
+24 -12
View File
@@ -1,6 +1,6 @@
"""Common fixtures for the Cloudflare R2 tests."""
from collections.abc import AsyncIterator, Generator
from collections.abc import Generator
import json
from unittest.mock import AsyncMock, MagicMock, patch
@@ -14,14 +14,27 @@ from homeassistant.components.cloudflare_r2.backup import (
)
from homeassistant.components.cloudflare_r2.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 test_backup(request: pytest.FixtureRequest) -> None:
def test_backup(request: pytest.FixtureRequest, backup_protected: bool) -> None:
"""Test backup fixture."""
return AgentBackup(
addons=[],
@@ -33,13 +46,13 @@ def test_backup(request: pytest.FixtureRequest) -> None:
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(test_backup: AgentBackup) -> Generator[AsyncMock]:
def mock_client(test_backup: AgentBackup, backup_data: bytes) -> Generator[AsyncMock]:
"""Mock the R2 client (S3-compatible)."""
with patch(
"aiobotocore.session.AioSession.create_client",
@@ -58,14 +71,13 @@ def mock_client(test_backup: AgentBackup) -> Generator[AsyncMock]:
client.create_multipart_upload.return_value = {"UploadId": "upload_id"}
client.upload_part.return_value = {"ETag": "etag"}
class MockStream:
async def iter_chunks(self) -> AsyncIterator[bytes]:
yield b"backup data"
async def read(self) -> bytes:
return json.dumps(test_backup.as_dict()).encode()
client.get_object.return_value = {"Body": MockStream()}
objects = {
tar_file: backup_data,
metadata_file: json.dumps(test_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
+122 -1
View File
@@ -1,15 +1,19 @@
"""Test the Cloudflare R2 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 ANY, AsyncMock, Mock, call, patch
from aiobotocore.response import StreamingBody
from aiohttp import ClientConnectionError, ClientPayloadError
from botocore.exceptions import BotoCoreError, 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,
@@ -40,6 +44,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,
@@ -660,3 +672,112 @@ async def test_agent_list_backups_parametrized(
mock_client.get_paginator.return_value.paginate.assert_called_once_with(
**expected_list_kwargs
)
@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()