Files
romm/backend/tests/handler/sync/test_ssh_handler.py
Georges-Antoine Assi f66950551a fix(sync): bind device tokens to their device; dial only known push-pull hosts (#5460)
* fix(sync): bind device tokens to their device; dial only known push-pull hosts

A client token paired to one device could read, reconfigure, delete, sync
saves for and record play sessions as any other device of the same user.
Device CRUD, sync negotiate/complete, push-pull trigger, the save device
resolver and play-session ingest now treat another device as not found for
a bound token, through a shared require_token_device helper. GET /api/devices
lists only the bound device.

Push-pull let any user with devices.write point ssh_host at any host and
port, and the connection error surfaced through the sync session, so the
worker could be used to probe the internal network. The SSH handler now
refuses a host with no trusted key or CA in the admin's known_hosts before
dialling it, which keeps LAN handhelds working while nothing else is
reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(device): revoke a deleted device's tokens; scope registration matches

Addresses Greptile review on #5460. Deleting a device now deletes the client
tokens paired to it, since the foreign key's SET NULL turned them into unbound
tokens that reach every device. Registration with a bound token only matches
its own device by fingerprint, so it can no longer reset syncs or overwrite
capabilities on another device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): bind heartbeat, sync session and online reads; pin push-pull ports

pr-ready step 2 (code-review xhigh --fix).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(device): one require_device helper; parse known_hosts once

pr-ready step 3 (simplify).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(sync): narrow await_args before reading known_hosts

pr-ready step 4 (review-polish).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(sync): plainer comments on the push-pull allowlist and token revoke

pr-ready step 5 (humanizer).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(device): keep bound tokens off other tokens; cascade tokens with their device

A device-bound token can no longer create tokens, or regenerate, pair or
revoke a token of another device or an unbound one. The save session_id
counter only counts a session of the caller's bound device.

client_tokens.device_id now cascades on device delete (0159), so no path
can leave an unbound token behind, and deleting a device records a
client_token.revoke audit event for each token it takes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(env): drop the push-pull allowlist note from env.template

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 08:57:33 -05:00

453 lines
14 KiB
Python

import hashlib
import shutil
import zipfile
from collections.abc import Mapping, Sequence
from datetime import datetime, timezone
from pathlib import Path, PurePath
from types import TracebackType
from typing import Any, Self, overload
from unittest.mock import ANY, AsyncMock, MagicMock
import asyncssh
import pytest
from anyio import Path as AnyioPath
from tests._zipfile_shim import reload_zipfile
from handler.filesystem.assets_handler import hash_save_file
from handler.sync import ssh_handler
from handler.sync.ssh_handler import SSHSyncHandler, get_ssh_sync_handler
class _FakeSFTP:
def __init__(self, source: Path):
self._source = source
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def get(self, remote_path: str, local_path: str) -> None:
shutil.copyfile(self._source, local_path)
class TestDownloadSave:
@pytest.fixture
def remote_zip(self, tmp_path: Path) -> Path:
path = tmp_path / "remote.zip"
reload_zipfile()
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_STORED) as zf:
zf.writestr("card/save.bin", b"identical save contents" * 64)
return path
@pytest.mark.asyncio
async def test_a_zipped_save_is_hashed_like_the_server_save(
self, tmp_path: Path, remote_zip: Path
):
remote_bytes = await AnyioPath(remote_zip).read_bytes()
conn = MagicMock()
conn.start_sftp_client.return_value = _FakeSFTP(remote_zip)
handler = SSHSyncHandler.__new__(SSHSyncHandler)
local_path, content_hash = await handler.download_save(
conn, "/saves/remote.zip", str(tmp_path / "local.zip")
)
assert await AnyioPath(local_path).read_bytes() == remote_bytes
assert content_hash == hash_save_file(remote_zip)
assert (
content_hash != hashlib.md5(remote_bytes, usedforsecurity=False).hexdigest()
)
@pytest.fixture
def keys_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
path = tmp_path / "keys"
monkeypatch.setattr(ssh_handler, "SYNC_SSH_KEYS_PATH", str(path))
return path
HOST_KEY = (
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOoOcFphVSisS5UKyUEUiJctlahXQzEK9QHClKgIPr0d"
)
@pytest.fixture
def known_hosts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
path = tmp_path / "known_hosts"
path.write_text(
f"deck.local {HOST_KEY}\n[deck.local]:2222 {HOST_KEY}\n"
f"192.168.1.20 {HOST_KEY}\n[odin.local]:2222 {HOST_KEY}\n"
)
monkeypatch.setattr(ssh_handler, "SYNC_SSH_KNOWN_HOSTS_PATH", str(path))
return path
@pytest.fixture
def handler(keys_dir: Path) -> SSHSyncHandler:
return SSHSyncHandler()
@pytest.fixture
def ssh_connect(mocker):
return mocker.patch.object(asyncssh, "connect", AsyncMock(return_value=MagicMock()))
def _connect_kwargs(ssh_connect: AsyncMock) -> Mapping[str, Any]:
call = ssh_connect.await_args
assert call is not None
return call.kwargs
class TestInit:
def test_creates_the_keys_directory(self, keys_dir: Path):
SSHSyncHandler()
assert keys_dir.is_dir()
def test_an_unwritable_keys_directory_is_a_clear_error(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
blocker = tmp_path / "not_a_dir"
blocker.write_text("")
monkeypatch.setattr(ssh_handler, "SYNC_SSH_KEYS_PATH", str(blocker / "keys"))
with pytest.raises(RuntimeError, match="not writable"):
SSHSyncHandler()
class TestConnect:
async def test_uses_the_key_named_after_the_device(
self, handler: SSHSyncHandler, keys_dir: Path, known_hosts: Path, ssh_connect
):
(keys_dir / "deck-1.pem").write_text("key")
await handler.connect(
{"ssh_host": "deck.local", "ssh_password": "unused"}, device_id="deck-1"
)
ssh_connect.assert_awaited_once_with(
host="deck.local",
port=22,
username="root",
known_hosts=ANY,
client_keys=[str(keys_dir / "deck-1.pem")],
)
# The allowlist check and the connection share one parse of the file.
call = ssh_connect.await_args
assert call is not None
assert isinstance(call.kwargs["known_hosts"], asyncssh.SSHKnownHosts)
async def test_a_key_path_in_the_config_is_ignored(
self, handler: SSHSyncHandler, keys_dir: Path, known_hosts: Path, ssh_connect
):
(keys_dir / "deck-1.pem").write_text("key")
(keys_dir / "someone-elses-deck.pem").write_text("key")
await handler.connect(
{
"ssh_host": "deck.local",
"ssh_port": 2222,
"ssh_username": "deck",
"ssh_key_path": str(keys_dir / "someone-elses-deck.pem"),
},
device_id="deck-1",
)
kwargs = _connect_kwargs(ssh_connect)
assert (kwargs["port"], kwargs["username"]) == (2222, "deck")
assert kwargs["client_keys"] == [str(keys_dir / "deck-1.pem")]
async def test_a_key_path_in_the_config_is_not_a_way_in(
self, handler: SSHSyncHandler, keys_dir: Path, known_hosts: Path, ssh_connect
):
(keys_dir / "someone-elses-deck.pem").write_text("key")
with pytest.raises(ValueError, match="No SSH authentication method"):
await handler.connect(
{
"ssh_host": "deck.local",
"ssh_key_path": str(keys_dir / "someone-elses-deck.pem"),
},
device_id="deck-1",
)
ssh_connect.assert_not_awaited()
@pytest.mark.parametrize("device_id", ["", "../keys/deck-1", "sub/deck-1"])
async def test_a_device_id_that_is_not_a_plain_name_has_no_key(
self,
handler: SSHSyncHandler,
keys_dir: Path,
known_hosts: Path,
ssh_connect,
device_id: str,
):
(keys_dir / "deck-1.pem").write_text("key")
(keys_dir / "sub").mkdir()
(keys_dir / "sub" / "deck-1.pem").write_text("key")
(keys_dir / ".pem").write_text("key")
with pytest.raises(ValueError, match="No SSH authentication method"):
await handler.connect({"ssh_host": "deck.local"}, device_id=device_id)
async def test_falls_back_to_a_password_without_a_key(
self, handler: SSHSyncHandler, known_hosts: Path, ssh_connect
):
await handler.connect(
{"ssh_host": "deck.local", "ssh_password": "hunter2"}, device_id="deck-1"
)
kwargs = _connect_kwargs(ssh_connect)
assert kwargs["password"] == "hunter2"
assert "client_keys" not in kwargs
async def test_refuses_without_any_credentials(
self, handler: SSHSyncHandler, known_hosts: Path, ssh_connect
):
with pytest.raises(ValueError, match="No SSH authentication method"):
await handler.connect({"ssh_host": "deck.local"}, device_id="deck-1")
ssh_connect.assert_not_awaited()
async def test_refuses_without_a_known_hosts_file(
self,
handler: SSHSyncHandler,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
ssh_connect,
):
monkeypatch.setattr(
ssh_handler, "SYNC_SSH_KNOWN_HOSTS_PATH", str(tmp_path / "missing")
)
with pytest.raises(FileNotFoundError, match="known_hosts"):
await handler.connect(
{"ssh_host": "deck.local", "ssh_password": "hunter2"},
device_id="deck-1",
)
ssh_connect.assert_not_awaited()
@pytest.mark.parametrize(
"host, port",
[("192.168.1.20", 22), ("odin.local", 2222)],
)
async def test_connects_to_a_host_in_known_hosts(
self, handler: SSHSyncHandler, known_hosts: Path, ssh_connect, host, port
):
await handler.connect(
{"ssh_host": host, "ssh_port": port, "ssh_password": "hunter2"},
device_id="deck-1",
)
kwargs = _connect_kwargs(ssh_connect)
assert (kwargs["host"], kwargs["port"]) == (host, port)
@pytest.mark.parametrize(
"host, port",
[
("127.0.0.1", 22),
("10.0.0.5", 6379),
("odin.local", 22),
("deck.local", 6379),
("192.168.1.20", 2222),
],
)
async def test_refuses_a_host_missing_from_known_hosts(
self, handler: SSHSyncHandler, known_hosts: Path, ssh_connect, host, port
):
with pytest.raises(ValueError, match="not in"):
await handler.connect(
{"ssh_host": host, "ssh_port": port, "ssh_password": "hunter2"},
device_id="deck-1",
)
ssh_connect.assert_not_awaited()
@pytest.fixture
def revoked_known_hosts(self, known_hosts: Path) -> Path:
known_hosts.write_text(f"@revoked deck.local {HOST_KEY}\n")
return known_hosts
async def test_a_revoked_key_does_not_admit_the_host(
self, handler: SSHSyncHandler, revoked_known_hosts: Path, ssh_connect
):
with pytest.raises(ValueError, match="not in"):
await handler.connect(
{"ssh_host": "deck.local", "ssh_password": "hunter2"},
device_id="deck-1",
)
ssh_connect.assert_not_awaited()
SFTPPath = bytes | str | PurePath
REGULAR = asyncssh.constants.FILEXFER_TYPE_REGULAR
DIRECTORY = asyncssh.constants.FILEXFER_TYPE_DIRECTORY
class _ListingSFTP(asyncssh.SFTPClient):
def __init__(
self,
tree: dict[str, dict[str, asyncssh.SFTPAttrs | Exception]],
) -> None:
self._tree = tree
self.mkdirs: list[str] = []
self.puts: list[tuple[str, str]] = []
self.mkdir_error: Exception | None = None
async def __aenter__(self) -> Self:
return self
async def __aexit__(
self,
_exc_type: type[BaseException] | None,
_exc_value: BaseException | None,
_traceback: TracebackType | None,
) -> bool:
return False
@overload
async def listdir(self, path: bytes) -> Sequence[bytes]: ...
@overload
async def listdir(self, path: str | PurePath = ...) -> Sequence[str]: ...
async def listdir(self, path: SFTPPath = ".") -> Sequence[bytes] | Sequence[str]:
if str(path) not in self._tree:
raise asyncssh.SFTPNoSuchFile(f"{path!r} not found")
return list(self._tree[str(path)])
async def stat(
self, path: SFTPPath, flags: int = 0, **kwargs: Any
) -> asyncssh.SFTPAttrs:
directory, _, name = str(path).rpartition("/")
entry = self._tree[directory][name]
if isinstance(entry, Exception):
raise entry
return entry
async def mkdir(
self, path: SFTPPath, attrs: asyncssh.SFTPAttrs | None = None
) -> None:
self.mkdirs.append(str(path))
if self.mkdir_error:
raise self.mkdir_error
async def put(
self,
localpaths: SFTPPath | Sequence[SFTPPath],
remotepath: SFTPPath | None = None,
**kwargs: Any,
) -> None:
self.puts.append((str(localpaths), str(remotepath)))
def _conn(sftp: _ListingSFTP) -> MagicMock:
conn = MagicMock()
conn.start_sftp_client.return_value = sftp
return conn
def _file(size: int, mtime: int) -> asyncssh.SFTPAttrs:
return asyncssh.SFTPAttrs(type=REGULAR, size=size, mtime=mtime)
class TestListRemoteSaves:
async def test_lists_regular_files_with_their_platform(
self, handler: SSHSyncHandler
):
sftp = _ListingSFTP(
{
"/saves/gba": {
"zelda.srm": _file(512, 1_700_000_000),
"states": asyncssh.SFTPAttrs(type=DIRECTORY),
}
}
)
[save] = await handler.list_remote_saves(
_conn(sftp), [{"platform_slug": "gba", "path": "/saves/gba"}]
)
assert (save.path, save.file_name, save.platform_slug) == (
"/saves/gba/zelda.srm",
"zelda.srm",
"gba",
)
assert save.file_size == 512
assert save.mtime == datetime.fromtimestamp(1_700_000_000, tz=timezone.utc)
async def test_filters_by_extension(self, handler: SSHSyncHandler):
sftp = _ListingSFTP(
{"/saves/snes": {"mario.srm": _file(1, 1), "mario.png": _file(1, 1)}}
)
saves = await handler.list_remote_saves(
_conn(sftp),
[{"platform_slug": "snes", "path": "/saves/snes", "extension": ".srm"}],
)
assert [save.file_name for save in saves] == ["mario.srm"]
async def test_a_missing_directory_skips_only_that_platform(
self, handler: SSHSyncHandler
):
sftp = _ListingSFTP({"/saves/gba": {"zelda.srm": _file(1, 1)}})
saves = await handler.list_remote_saves(
_conn(sftp),
[
{"platform_slug": "snes", "path": "/saves/snes"},
{"platform_slug": "gba", "path": "/saves/gba"},
],
)
assert [save.platform_slug for save in saves] == ["gba"]
async def test_a_file_that_cannot_be_read_is_skipped(self, handler: SSHSyncHandler):
sftp = _ListingSFTP(
{
"/saves/gba": {
"locked.srm": asyncssh.SFTPError(3, "permission denied"),
"zelda.srm": _file(1, 1),
}
}
)
saves = await handler.list_remote_saves(
_conn(sftp), [{"platform_slug": "gba", "path": "/saves/gba"}]
)
assert [save.file_name for save in saves] == ["zelda.srm"]
class TestUploadSave:
async def test_creates_the_directory_and_uploads(self, handler: SSHSyncHandler):
sftp = _ListingSFTP({})
await handler.upload_save(_conn(sftp), "/tmp/local.srm", "/saves/gba/a.srm")
assert sftp.mkdirs == ["/saves/gba"]
assert sftp.puts == [("/tmp/local.srm", "/saves/gba/a.srm")]
async def test_an_existing_directory_does_not_stop_the_upload(
self, handler: SSHSyncHandler
):
sftp = _ListingSFTP({})
sftp.mkdir_error = asyncssh.SFTPFailure("already exists")
await handler.upload_save(_conn(sftp), "/tmp/local.srm", "/saves/gba/a.srm")
assert sftp.puts == [("/tmp/local.srm", "/saves/gba/a.srm")]
def test_the_handler_is_created_once(keys_dir: Path):
get_ssh_sync_handler.cache_clear()
try:
assert get_ssh_sync_handler() is get_ssh_sync_handler()
finally:
get_ssh_sync_handler.cache_clear()