diff --git a/homeassistant/components/sftp_storage/client.py b/homeassistant/components/sftp_storage/client.py index 0779ef40fcb1..35a309addd05 100644 --- a/homeassistant/components/sftp_storage/client.py +++ b/homeassistant/components/sftp_storage/client.py @@ -23,6 +23,7 @@ from homeassistant.components.backup import ( suggested_filename, ) from homeassistant.core import HomeAssistant +from homeassistant.util.async_iterator import ResourceChunkIterator from .const import BUF_SIZE, LOGGER @@ -45,17 +46,13 @@ def get_client_options(cfg: SFTPConfigEntryData) -> SSHClientConnectionOptions: ) -class AsyncFileIterator: - """Returns iterator of remote file located in SFTP Server. +class RemoteFileReader: + """Read a remote file located in SFTP Server over its own SSH connection. - This exists in order to properly close remote file after operation is completed - and to avoid premature closing of file and session if `BackupAgentClient` is used - as context manager. + The connection is opened on the first read, so it outlives the + `BackupAgentClient` which created the reader. """ - _client: BackupAgentClient - _fileobj: SFTPClientFile - def __init__( self, cfg: SFTPConfigEntry, @@ -63,42 +60,52 @@ class AsyncFileIterator: file_path: str, buffer_size: int = BUF_SIZE, ) -> None: - """Initialize `AsyncFileIterator`.""" + """Initialize `RemoteFileReader`.""" self.cfg: SFTPConfigEntry = cfg self.hass: HomeAssistant = hass self.file_path: str = file_path self.buffer_size = buffer_size - self._initialized: bool = False - LOGGER.debug("Opening file: %s in Async File Iterator", file_path) + self._client: BackupAgentClient | None = None + self._fileobj: SFTPClientFile | None = None + self._closed = False - async def _initialize(self) -> None: - """Load file object.""" - self._client: BackupAgentClient = await BackupAgentClient( - self.cfg, self.hass - ).open() - self._fileobj: SFTPClientFile = await self._client.sftp.open( - self.file_path, "rb" - ) + async def _open(self) -> SFTPClientFile | None: + """Open the SSH connection and the remote file.""" + LOGGER.debug("Opening file: %s", self.file_path) + self._client = client = BackupAgentClient(self.cfg, self.hass) + try: + await client.open() + self._fileobj = await client.sftp.open(self.file_path, "rb") + finally: + # Closing while opening can't close a connection which isn't made yet + if self._closed: + client.abort() + if self._closed: + return None + return self._fileobj - self._initialized = True + async def read(self) -> bytes: + """Read the next chunk, empty bytes at the end of the file.""" + if (fileobj := self._fileobj) is None and ( + fileobj := await self._open() + ) is None: + return b"" + return await fileobj.read(self.buffer_size) - def __aiter__(self) -> AsyncIterator[bytes]: - """Return self as iterator.""" - return self + def abort(self) -> None: + """Close the SSH connection without waiting.""" + self._closed = True + if self._client is not None: + self._client.abort() - async def __anext__(self) -> bytes: - """Return next bytes as provided in buffer size.""" - if not self._initialized: - await self._initialize() - - chunk: bytes = await self._fileobj.read(self.buffer_size) - if not chunk: - try: - await self._fileobj.close() - await self._client.close() - finally: - raise StopAsyncIteration - return chunk + async def aclose(self) -> None: + """Close the remote file and the SSH connection.""" + self._closed = True + if (client := self._client) is None: + return + if self._fileobj is not None: + await self._fileobj.close() + await client.close() @dataclass(kw_only=True) @@ -251,13 +258,13 @@ class BackupAgentClient: """Close the `BackupAgentClient` context manager.""" await self.__aexit__(None, None, None) - async def iter_file(self, backup_id: str) -> AsyncFileIterator: - """Return Async File Iterator object. + def abort(self) -> None: + """Close the SSH connection, and with it the SFTP session, without waiting.""" + if self._ssh: + self._ssh.close() - `SFTPClientFile` object (that would be returned with - `sftp.open`) is not an iterator. So we return custom - made class - `AsyncFileIterator` that would allow - iteration on file object. + async def iter_file(self, backup_id: str) -> ResourceChunkIterator: + """Return an async iterator over the backup archive. Raises: ------ @@ -268,7 +275,10 @@ class BackupAgentClient: metadata: BackupMetadata = await self._load_metadata(backup_id) if not await self.sftp.exists(metadata.file_path): raise FileNotFoundError("Backup archive not found on remote location.") - return AsyncFileIterator(self.cfg, self.hass, metadata.file_path, BUF_SIZE) + reader = RemoteFileReader(self.cfg, self.hass, metadata.file_path, BUF_SIZE) + return ResourceChunkIterator( + reader.read, close=reader.abort, aclose=reader.aclose + ) async def list_backup_location(self) -> list[str]: """Return a list of `*.metadata.json` files located in backup location.""" diff --git a/tests/components/sftp_storage/test_backup.py b/tests/components/sftp_storage/test_backup.py index c84a92f3001c..4d1ff8804f7b 100644 --- a/tests/components/sftp_storage/test_backup.py +++ b/tests/components/sftp_storage/test_backup.py @@ -1,15 +1,20 @@ """Test the Backup SFTP Location platform.""" -from io import StringIO +import asyncio +from io import BytesIO, StringIO import json from typing import Any -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock, Mock, patch +from aiohttp import ClientPayloadError from asyncssh.sftp import SFTPError from freezegun.api import FrozenDateTimeFactory import pytest +from pytest_homeassistant.common import get_fixture_path from pytest_homeassistant.typing import ClientSessionGenerator, WebSocketGenerator +from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, async_get_manager +from homeassistant.components.sftp_storage import client as sftp_client from homeassistant.components.sftp_storage.backup import ( async_register_backup_agents_listener, ) @@ -19,7 +24,7 @@ from homeassistant.components.sftp_storage.const import ( ) from homeassistant.core import HomeAssistant -from .asyncssh_mock import SSHClientConnectionMock +from .asyncssh_mock import SFTPOpenMock, SSHClientConnectionMock, async_context_manager from .conftest import ( BACKUP_METADATA, CONFIG_ENTRY_TITLE, @@ -34,6 +39,13 @@ from tests.components.backup.common import ( upload_backup_via_http, ) +# 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 mock_setup_integration( @@ -453,3 +465,225 @@ async def test_listeners_get_cleaned_up(hass: HomeAssistant) -> None: remove_listener() assert DATA_BACKUP_AGENT_LISTENERS not in hass.data + + +@pytest.fixture +def ssh_connections( + mock_ssh_connection: SSHClientConnectionMock, +) -> list[SSHClientConnectionMock]: + """Return the SSH connections opened after the integration was set up. + + A download opens three: to get the backup, to find the archive and to read it. + """ + connections: list[SSHClientConnectionMock] = [] + + @async_context_manager + async def mock_connect(*args: Any, **kwargs: Any) -> SSHClientConnectionMock: + connection = SSHClientConnectionMock() + connection._sftp = mock_ssh_connection._sftp + connection.close = Mock() + connections.append(connection) + return connection + + sftp_client.connect.side_effect = mock_connect + return connections + + +@pytest.fixture +def backup_data() -> bytes: + """Backup data, override in tests to change defaults.""" + return b"backup data" + + +@pytest.fixture +def downloaded_files( + mock_ssh_connection: SSHClientConnectionMock, backup_data: bytes +) -> list[SFTPOpenMock]: + """Mock the backup and return the downloaded backup archive files.""" + sftp = mock_ssh_connection._sftp + sftp._mock_listdir.return_value = [f"{TEST_AGENT_BACKUP.backup_id}.metadata.json"] + sftp._mock_open._mock_read.return_value = json.dumps(BACKUP_METADATA) + files: list[SFTPOpenMock] = [] + + @async_context_manager + async def mock_open(path: str, *args: Any, **kwargs: Any) -> SFTPOpenMock: + if path != BACKUP_METADATA["file_path"]: + return sftp._mock_open + file = SFTPOpenMock() + file._mock_read.side_effect = BytesIO(backup_data).read + files.append(file) + return file + + sftp.open = mock_open + return files + + +@pytest.mark.parametrize( + "backup_data", [pytest.param(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_connection( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + ssh_connections: list[SSHClientConnectionMock], + downloaded_files: list[SFTPOpenMock], + 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": TEST_AGENT_BACKUP.backup_id, + "agent_id": f"{DOMAIN}.{TEST_AGENT_ID}", + "password": password, + } + ) + assert (await client.receive_json())["success"] is success + + assert len(downloaded_files) == 1 + downloaded_files[0].close.assert_awaited_once() + assert [conn.close.call_count for conn in ssh_connections] == [1, 1, 1] + + +@pytest.mark.parametrize( + "backup_data", [pytest.param(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_connection( + hass_client: ClientSessionGenerator, + ssh_connections: list[SSHClientConnectionMock], + downloaded_files: list[SFTPOpenMock], + 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/{TEST_AGENT_BACKUP.backup_id}?agent_id={DOMAIN}.{TEST_AGENT_ID}{query}" + ) + assert resp.status == 200 + await resp.read() + + assert len(downloaded_files) == 1 + downloaded_files[0].close.assert_awaited_once() + assert [conn.close.call_count for conn in ssh_connections] == [1, 1, 1] + + +async def test_agents_download_closes_connection_on_read_error( + hass_client: ClientSessionGenerator, + mock_ssh_connection: SSHClientConnectionMock, + ssh_connections: list[SSHClientConnectionMock], + downloaded_files: list[SFTPOpenMock], +) -> None: + """Test the download is closed when reading the backup fails.""" + open_file = mock_ssh_connection._sftp.open + + @async_context_manager + async def mock_open(path: str, *args: Any, **kwargs: Any) -> SFTPOpenMock: + file = await open_file(path, *args, **kwargs) + if path == BACKUP_METADATA["file_path"]: + file._mock_read.side_effect = SFTPError(0, "read failed") + return file + + mock_ssh_connection._sftp.open = mock_open + client = await hass_client() + + resp = await client.get( + f"/api/backup/download/{TEST_AGENT_BACKUP.backup_id}?agent_id={DOMAIN}.{TEST_AGENT_ID}" + ) + with pytest.raises(ClientPayloadError): + await resp.read() + + assert len(downloaded_files) == 1 + assert [conn.close.call_count for conn in ssh_connections] == [1, 1, 1] + + +async def test_agents_download_closes_connection_on_open_error( + hass_client: ClientSessionGenerator, + mock_ssh_connection: SSHClientConnectionMock, + ssh_connections: list[SSHClientConnectionMock], + downloaded_files: list[SFTPOpenMock], +) -> None: + """Test the download is closed when opening the backup fails.""" + open_file = mock_ssh_connection._sftp.open + + @async_context_manager + async def mock_open(path: str, *args: Any, **kwargs: Any) -> SFTPOpenMock: + if path == BACKUP_METADATA["file_path"]: + raise SFTPError(0, "no file") + return await open_file(path, *args, **kwargs) + + mock_ssh_connection._sftp.open = mock_open + client = await hass_client() + + resp = await client.get( + f"/api/backup/download/{TEST_AGENT_BACKUP.backup_id}?agent_id={DOMAIN}.{TEST_AGENT_ID}" + ) + with pytest.raises(ClientPayloadError): + await resp.read() + + assert not downloaded_files + assert [conn.close.call_count for conn in ssh_connections] == [1, 1, 1] + + +async def test_agents_download_closed_while_connecting( + hass: HomeAssistant, + mock_ssh_connection: SSHClientConnectionMock, + ssh_connections: list[SSHClientConnectionMock], + downloaded_files: list[SFTPOpenMock], +) -> None: + """Test the connection is closed if the download is closed while connecting. + + The backup integration doesn't close a download from another task while it is + read, so the download stream is used directly. + """ + agent = async_get_manager(hass).backup_agents[f"{DOMAIN}.{TEST_AGENT_ID}"] + stream = await agent.async_download_backup(TEST_AGENT_BACKUP.backup_id) + + connect = sftp_client.connect.side_effect + connecting = asyncio.Event() + connected = asyncio.Event() + + @async_context_manager + async def paused_connect(*args: Any, **kwargs: Any) -> SSHClientConnectionMock: + connecting.set() + await connected.wait() + return await connect(*args, **kwargs) + + sftp_client.connect.side_effect = paused_connect + open_file = mock_ssh_connection._sftp.open + + @async_context_manager + async def mock_open(path: str, *args: Any, **kwargs: Any) -> SFTPOpenMock: + if path == BACKUP_METADATA["file_path"]: + raise SFTPError(0, "no file") + return await open_file(path, *args, **kwargs) + + mock_ssh_connection._sftp.open = mock_open + + read = asyncio.create_task(anext(stream)) + await connecting.wait() + stream.close() + connected.set() + with pytest.raises(SFTPError, match="no file"): + await read + + assert not downloaded_files + # One connection to find the archive, one to read it + assert [conn.close.call_count for conn in ssh_connections] == [1, 1]