From 0bf2923edb103c67cee2e958e54f9a0fc3318db1 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 17 Nov 2026 03:07:49 -0500 Subject: [PATCH 1/4] chore(deploy): harden systemd unit sandboxing and add automated verify test - flake.nix: add pkgs.systemd to testTools (nativeCheckInputs and devShell packages) so systemd-analyze is hermetically available in both local dev and isolated Nix sandbox CI (Defect 1 / CR-03) - deploy/lg-smtv-mcp.service: add StartLimitIntervalSec=60s and StartLimitBurst=5 in [Unit] to prevent unbounded restart loops (CR-02); add safe sandboxing baseline in [Service] (NoNewPrivileges, PrivateTmp, UMask=0077, ProtectSystem=full, kernel/bus isolation directives, CapabilityBoundingSet=) dropping offline exposure score from 9.0 UNSAFE to 4.9 OK (CR-02, Issue #17) - tests/test_deploy.py: add unit tests verifying template placeholders, directive presence, systemd-analyze verify exit code, and security exposure score reduction under 5.0 (CR-03) - README.md: document adopted hardening baseline, score reduction (9.0 -> 4.9), and technical compatibility constraints that ruled out ProtectHome, ProtectSystem=strict, and PrivateNetwork (AC1, AC4) --- README.md | 21 +++++++++- deploy/lg-smtv-mcp.service | 18 +++++++++ flake.nix | 8 +++- tests/test_deploy.py | 80 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 124 insertions(+), 3 deletions(-) create mode 100644 tests/test_deploy.py diff --git a/README.md b/README.md index 945bfdf..223cb73 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ A Python Model Context Protocol (MCP) server for persistent, local-network contr The server is deliberately **LLM-free**: it exposes bounded, deterministic operations so external AI agents (such as Antigravity, Claude, or a vision-guided decision loop) can reason over UI state and control the television without embedding model APIs into the daemon. > **Status: M2 delivered — capture, E2E hardening, and `systemd` deployment.** -> Configuration validation, error taxonomy, [`tv_core`](src/lg_smtv_mcp/tv_core/) (SSAP multiplexer, `PointerClient`, `TvManager`), FastMCP server & Bearer auth ([`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py)), `pair` / `serve` CLI ([`cli.py`](src/lg_smtv_mcp/cli.py)), full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)), and Developer Mode SFTP screenshot capture ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)) are implemented and tested. Milestone M2 is delivered; `systemd` unit sandboxing hardening is tracked separately in [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17). +> Configuration validation, error taxonomy, [`tv_core`](src/lg_smtv_mcp/tv_core/) (SSAP multiplexer, `PointerClient`, `TvManager`), FastMCP server & Bearer auth ([`server.py`](src/lg_smtv_mcp/server.py), [`auth.py`](src/lg_smtv_mcp/auth.py)), `pair` / `serve` CLI ([`cli.py`](src/lg_smtv_mcp/cli.py)), full-stack offline E2E verification ([`test_e2e_mvp.py`](tests/test_e2e_mvp.py)), and Developer Mode SFTP screenshot capture ([`capture.py`](src/lg_smtv_mcp/tv_core/capture.py)) are implemented and tested. Milestone M2 is delivered; `systemd` unit sandboxing hardening is implemented in [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17). --- @@ -191,6 +191,25 @@ The repository includes a unit template at [`deploy/lg-smtv-mcp.service`](deploy The HTTP server binds to `127.0.0.1` by default and requires `MCP_BEARER_TOKEN`. Use a trusted reverse proxy or VPN if clients need remote access. When exposing the server remotely, set **both** `HOST=0.0.0.0` (or the LAN bind address) **and** `ALLOWED_HOSTS=` in `.env`; the DNS-rebinding check in `auth.py` rejects any request whose `Host` header is not in the allowlist. +### Sandboxing & Security Profile + +The unit template includes a tested systemd sandboxing baseline (Issue [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)), reducing the `systemd-analyze --offline=yes security` exposure score from **9.0 UNSAFE** to **4.9 OK**: + +- **Adopted Directives:** + - `StartLimitIntervalSec=60s` / `StartLimitBurst=5`: Bounded restart budget prevents runaway restart loops on persistent environment errors (e.g. missing `.env`). + - `NoNewPrivileges=yes`: Prevents process escalation or setuid execution. + - `PrivateTmp=yes`: Restricts `/tmp` visibility to an isolated per-service namespace. + - `UMask=0077`: Ensures files created by the service are private to the service user. + - `ProtectSystem=full`: Mounts `/usr`, `/boot`, and `/etc` read-only. + - `ProtectControlGroups=yes`, `ProtectKernelModules=yes`, `ProtectKernelTunables=yes`, `ProtectKernelLogs=yes`, `ProtectClock=yes`, `ProtectHostname=yes`: Prevents tampering with kernel and OS interfaces. + - `RestrictRealtime=yes`, `RestrictSUIDSGID=yes`, `LockPersonality=yes`: Restricts privilege escalation vectors. + - `CapabilityBoundingSet=`: Drops all Linux kernel capabilities. + +- **Rejected Directives (Compatibility Constraints):** + - `ProtectHome=yes` / `ProtectHome=read-only`: Ruled out because `nix develop` requires read-write access to `~/.cache/nix/fetcher-locks` for flake evaluation, and the repository checkout resides under the operator's user directory. + - `ProtectSystem=strict`: Ruled out because `nix develop` requires writable `/tmp` for development shell temporary files (`/tmp/nix-shell.*`). + - `PrivateNetwork=yes`: Ruled out because the MCP daemon must communicate over the local network to the TV via SSAP (`wss://:3001`), Developer Mode SSH/SFTP (`:9922`), and Wake-on-LAN UDP broadcasts. + ### Developer Mode SSH Capture Setup Enable Developer Mode and the TV's Key Server in the Developer Mode app. Run pairing from the configured checkout as the same service user so the client key and SSH key are saved where the service can read them: diff --git a/deploy/lg-smtv-mcp.service b/deploy/lg-smtv-mcp.service index 1c165b1..7f7f9a9 100644 --- a/deploy/lg-smtv-mcp.service +++ b/deploy/lg-smtv-mcp.service @@ -2,6 +2,8 @@ Description=LG webOS Smart TV MCP server Wants=network-online.target After=network-online.target +StartLimitIntervalSec=60s +StartLimitBurst=5 [Service] Type=simple @@ -13,5 +15,21 @@ ExecStart=/usr/bin/env nix develop --command python -m lg_smtv_mcp serve Restart=on-failure RestartSec=5s +# Sandboxing baseline (Issue #17) +NoNewPrivileges=yes +PrivateTmp=yes +UMask=0077 +ProtectSystem=full +ProtectControlGroups=yes +ProtectKernelModules=yes +ProtectKernelTunables=yes +ProtectKernelLogs=yes +ProtectClock=yes +ProtectHostname=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +CapabilityBoundingSet= + [Install] WantedBy=multi-user.target diff --git a/flake.nix b/flake.nix index 56f4e30..fb33567 100644 --- a/flake.nix +++ b/flake.nix @@ -25,6 +25,10 @@ ps.pytest-asyncio ]; + testTools = [ + pkgs.systemd + ]; + pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps); in { @@ -39,7 +43,7 @@ ps.pytestCheckHook pkgs.ruff pkgs.pyright - ] ++ testDeps; + ] ++ testDeps ++ testTools; preCheck = '' ruff check . ruff format --check . @@ -52,7 +56,7 @@ pythonEnv pkgs.pyright pkgs.ruff - ]; + ] ++ testTools; shellHook = '' export PYTHONPATH="$PWD/src:${PYTHONPATH:-}" if [ -d .git ] && [ -d .githooks ]; then diff --git a/tests/test_deploy.py b/tests/test_deploy.py new file mode 100644 index 0000000..d988596 --- /dev/null +++ b/tests/test_deploy.py @@ -0,0 +1,80 @@ +"""Unit tests verifying deploy/lg-smtv-mcp.service template and sandboxing directives.""" + +import shutil +import subprocess +from pathlib import Path + +import pytest + +SERVICE_TEMPLATE_PATH = Path(__file__).resolve().parent.parent / "deploy" / "lg-smtv-mcp.service" + + +def test_service_template_exists(): + assert SERVICE_TEMPLATE_PATH.is_file(), f"Template missing at {SERVICE_TEMPLATE_PATH}" + + +def test_service_template_contains_placeholders_and_hardening_directives(): + content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8") + + # Placeholders + assert "" in content + assert "" in content + assert "" in content + + # CR-02: Bounded restart limit in [Unit] + assert "StartLimitIntervalSec=" in content + assert "StartLimitBurst=" in content + + # Hardening baseline (Issue #17) + assert "NoNewPrivileges=yes" in content + assert "PrivateTmp=yes" in content + assert "UMask=0077" in content + assert "ProtectSystem=full" in content + assert "CapabilityBoundingSet=" in content + + +def test_systemd_analyze_verify_on_substituted_template(tmp_path: Path): + systemd_analyze = shutil.which("systemd-analyze") + if not systemd_analyze: + pytest.fail("systemd-analyze not found in PATH; ensure pkgs.systemd is in testTools") + + content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8") + substituted = ( + content.replace("", "kiskaadee") + .replace("", "/home/kiskaadee/Projects/active/lg-smtv-mcp") + .replace("", "/run/current-system/sw/bin") + ) + + test_unit_file = tmp_path / "lg-smtv-mcp.service" + test_unit_file.write_text(substituted, encoding="utf-8") + + cmd = [systemd_analyze, "verify", str(test_unit_file)] + res = subprocess.run(cmd, capture_output=True, text=True) + assert res.returncode == 0, f"systemd-analyze verify failed: {res.stderr}" + + +def test_systemd_analyze_security_exposure_score_reduction(tmp_path: Path): + systemd_analyze = shutil.which("systemd-analyze") + if not systemd_analyze: + pytest.fail("systemd-analyze not found in PATH; ensure pkgs.systemd is in testTools") + + content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8") + substituted = ( + content.replace("", "kiskaadee") + .replace("", "/home/kiskaadee/Projects/active/lg-smtv-mcp") + .replace("", "/run/current-system/sw/bin") + ) + + test_unit_file = tmp_path / "lg-smtv-mcp.service" + test_unit_file.write_text(substituted, encoding="utf-8") + + cmd = [systemd_analyze, "--offline=yes", "security", str(test_unit_file)] + res = subprocess.run(cmd, capture_output=True, text=True) + assert res.returncode == 0, f"systemd-analyze security failed: {res.stderr}" + + # Verify score is in the OK bracket (<= 5.0), down from baseline 9.0 UNSAFE + lines = [line for line in res.stdout.splitlines() if "Overall exposure level" in line] + assert lines, "No exposure level reported" + score_line = lines[0] + # Expect: → Overall exposure level for ...: X.Y OK :-) + assert "OK" in score_line, f"Exposure level not in OK bracket: {score_line}" From 52ec28f278352e26a2eab3e37f499f783dd9c4b1 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 17 Nov 2026 09:53:30 -0500 Subject: [PATCH 2/4] test(deploy): harden test seams with section-aware parsing and fault-safe fixtures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses CR-01 to CR-05 from review 10 on PR #18. - tests/test_deploy.py: resolve CR-01 — replace substring assertions with configparser section-aware exact key/value checks; CapabilityBoundingSet= now asserts empty string ''; commented-out directives are correctly rejected since configparser strips comment lines; assert 'Unknown key'/ 'Unknown lvalue' absent in systemd-analyze verify stderr so wrong-section misplacements are caught even at exit 0 - tests/test_deploy.py: resolve CR-02 — replace hardcoded personal identifiers ('kiskaadee', '/home/kiskaadee/...') with neutral 'testuser' and pytest tmp_path-derived paths in all substitution fixtures - tests/test_deploy.py: resolve CR-03 — split the monolithic test_service_template_contains_placeholders_and_hardening_directives into three single-behavior tests: test_service_template_exists, test_service_template_declares_deployment_placeholders, and test_service_template_bounds_restart_limit_in_unit_section - tests/test_deploy.py: resolve CR-04 — add timeout=30.0 to all subprocess.run calls to prevent silent CI hangs - tests/test_deploy.py: resolve CR-05 — regex-parse numeric exposure score from systemd-analyze security output and assert score <= 5.0 in lieu of checking 'OK' label substring; test renamed to test_systemd_analyze_security_reports_ok_exposure_bracket - tests/test_deploy.py: resolve CR-08 — extract shared systemd_analyze_bin and substituted_service_file pytest fixtures, eliminating duplicated shutil.which calls and substitution setup across subprocess tests Fault injection confirmed red before green for all sensitive seams: Fault A: StartLimitIntervalSec/Burst in [Service] → section-mismatch fail Fault B: CapabilityBoundingSet=CAP_NET_RAW → non-empty string fail Fault C: # NoNewPrivileges=yes (commented) → None != 'yes' fail Fault D: sandboxing block removed → 9.0 UNSAFE score, regex no-match fail Verification: 144 passed, ruff/pyright/pytest all green --- tests/test_deploy.py | 144 ++++++++++++++++++++++++++++--------------- 1 file changed, 95 insertions(+), 49 deletions(-) diff --git a/tests/test_deploy.py b/tests/test_deploy.py index d988596..9ba9ca4 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -1,5 +1,7 @@ """Unit tests verifying deploy/lg-smtv-mcp.service template and sandboxing directives.""" +import configparser +import re import shutil import subprocess from pathlib import Path @@ -9,72 +11,116 @@ import pytest SERVICE_TEMPLATE_PATH = Path(__file__).resolve().parent.parent / "deploy" / "lg-smtv-mcp.service" +def _parse_service_template(content: str) -> configparser.ConfigParser: + """Parse a systemd unit file while stripping comments and preserving empty values.""" + parser = configparser.ConfigParser( + comment_prefixes=("#", ";"), + inline_comment_prefixes=None, + strict=False, + allow_no_value=True, + ) + parser.read_string(content) + return parser + + +@pytest.fixture +def systemd_analyze_bin() -> str: + binary = shutil.which("systemd-analyze") + if not binary: + pytest.fail("systemd-analyze not found in PATH; ensure pkgs.systemd is in testTools") + return binary + + +@pytest.fixture +def substituted_service_file(tmp_path: Path, systemd_analyze_bin: str) -> Path: + content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8") + workdir = tmp_path / "workdir" + workdir.mkdir() + # Use neutral non-personal values derived from tmp_path (CR-02) + substituted = ( + content.replace("", "testuser") + .replace("", str(workdir)) + .replace("", str(Path(systemd_analyze_bin).parent)) + ) + test_unit_file = tmp_path / "lg-smtv-mcp.service" + test_unit_file.write_text(substituted, encoding="utf-8") + return test_unit_file + + def test_service_template_exists(): assert SERVICE_TEMPLATE_PATH.is_file(), f"Template missing at {SERVICE_TEMPLATE_PATH}" -def test_service_template_contains_placeholders_and_hardening_directives(): +def test_service_template_declares_deployment_placeholders(): content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8") - - # Placeholders assert "" in content assert "" in content assert "" in content - # CR-02: Bounded restart limit in [Unit] - assert "StartLimitIntervalSec=" in content - assert "StartLimitBurst=" in content - - # Hardening baseline (Issue #17) - assert "NoNewPrivileges=yes" in content - assert "PrivateTmp=yes" in content - assert "UMask=0077" in content - assert "ProtectSystem=full" in content - assert "CapabilityBoundingSet=" in content - - -def test_systemd_analyze_verify_on_substituted_template(tmp_path: Path): - systemd_analyze = shutil.which("systemd-analyze") - if not systemd_analyze: - pytest.fail("systemd-analyze not found in PATH; ensure pkgs.systemd is in testTools") +def test_service_template_bounds_restart_limit_in_unit_section(): content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8") - substituted = ( - content.replace("", "kiskaadee") - .replace("", "/home/kiskaadee/Projects/active/lg-smtv-mcp") - .replace("", "/run/current-system/sw/bin") - ) + parser = _parse_service_template(content) - test_unit_file = tmp_path / "lg-smtv-mcp.service" - test_unit_file.write_text(substituted, encoding="utf-8") + assert "Unit" in parser, "Missing [Unit] section in service template" + unit_section = parser["Unit"] + # CR-01: Assert exact keys and values in [Unit], not substring matches + assert unit_section.get("startlimitintervalsec") == "60s" + assert unit_section.get("startlimitburst") == "5" - cmd = [systemd_analyze, "verify", str(test_unit_file)] - res = subprocess.run(cmd, capture_output=True, text=True) + +def test_service_template_enables_sandboxing_baseline_in_service_section(): + content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8") + parser = _parse_service_template(content) + + assert "Service" in parser, "Missing [Service] section in service template" + service_section = parser["Service"] + + # CR-01: Section-aware exact-value checks; comments stripped, CapabilityBoundingSet="" enforced + assert service_section.get("nonewprivileges") == "yes" + assert service_section.get("privatetmp") == "yes" + assert service_section.get("umask") == "0077" + assert service_section.get("protectsystem") == "full" + assert service_section.get("capabilityboundingset") == "" + assert service_section.get("protectcontrolgroups") == "yes" + assert service_section.get("protectkernelmodules") == "yes" + assert service_section.get("protectkerneltunables") == "yes" + assert service_section.get("protectkernellogs") == "yes" + assert service_section.get("protectclock") == "yes" + assert service_section.get("protecthostname") == "yes" + assert service_section.get("restrictrealtime") == "yes" + assert service_section.get("restrictsuidsgid") == "yes" + assert service_section.get("lockpersonality") == "yes" + + +def test_systemd_analyze_verify_succeeds_on_substituted_template( + systemd_analyze_bin: str, substituted_service_file: Path +): + cmd = [systemd_analyze_bin, "verify", str(substituted_service_file)] + # CR-04: Subprocess timeout prevents CI hang + res = subprocess.run(cmd, capture_output=True, text=True, timeout=30.0) + + # CR-01: Fail on warnings such as 'Unknown key' or 'Unknown lvalue' that exit 0 + assert "Unknown key" not in res.stderr, f"Unknown key in template: {res.stderr}" + assert "Unknown lvalue" not in res.stderr, f"Unknown lvalue in template: {res.stderr}" assert res.returncode == 0, f"systemd-analyze verify failed: {res.stderr}" -def test_systemd_analyze_security_exposure_score_reduction(tmp_path: Path): - systemd_analyze = shutil.which("systemd-analyze") - if not systemd_analyze: - pytest.fail("systemd-analyze not found in PATH; ensure pkgs.systemd is in testTools") - - content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8") - substituted = ( - content.replace("", "kiskaadee") - .replace("", "/home/kiskaadee/Projects/active/lg-smtv-mcp") - .replace("", "/run/current-system/sw/bin") - ) - - test_unit_file = tmp_path / "lg-smtv-mcp.service" - test_unit_file.write_text(substituted, encoding="utf-8") - - cmd = [systemd_analyze, "--offline=yes", "security", str(test_unit_file)] - res = subprocess.run(cmd, capture_output=True, text=True) +def test_systemd_analyze_security_reports_ok_exposure_bracket( + systemd_analyze_bin: str, substituted_service_file: Path +): + cmd = [systemd_analyze_bin, "--offline=yes", "security", str(substituted_service_file)] + # CR-04: Subprocess timeout prevents CI hang + res = subprocess.run(cmd, capture_output=True, text=True, timeout=30.0) assert res.returncode == 0, f"systemd-analyze security failed: {res.stderr}" - # Verify score is in the OK bracket (<= 5.0), down from baseline 9.0 UNSAFE + # CR-05: Regex-parse the numeric exposure score and assert it satisfies the OK bracket (<= 5.0) lines = [line for line in res.stdout.splitlines() if "Overall exposure level" in line] - assert lines, "No exposure level reported" + assert lines, "No exposure level reported by systemd-analyze security" score_line = lines[0] - # Expect: → Overall exposure level for ...: X.Y OK :-) - assert "OK" in score_line, f"Exposure level not in OK bracket: {score_line}" + + match = re.search(r"Overall exposure level.*:\s*([0-9]+\.[0-9]+)\s+OK", score_line) + assert match is not None, f"Could not parse numeric score and OK status from: {score_line}" + + score = float(match.group(1)) + assert score <= 5.0, f"Exposure score {score} exceeds OK bracket threshold 5.0" From 9195d91d7d443a026799dfc33e64c89863cfad44 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 17 Nov 2026 10:01:38 -0500 Subject: [PATCH 3/4] docs(deploy): correct ProtectSystem=strict rejection rationale MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - README.md: replace the incorrect claim that ProtectSystem=strict was rejected because nix develop needs writable /tmp; systemd.exec(5) keeps /tmp and /var/tmp writable under strict when PrivateTmp=yes is set, which this unit already adopts - README.md: state the real compatibility constraint instead — strict mounts the whole filesystem read-only including ~/.cache/nix/fetcher-locks and the checkout, matching the documented ProtectHome constraint — so issue #17 AC#4 records an accurate reason --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 223cb73..545b549 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,7 @@ The unit template includes a tested systemd sandboxing baseline (Issue [#17](htt - **Rejected Directives (Compatibility Constraints):** - `ProtectHome=yes` / `ProtectHome=read-only`: Ruled out because `nix develop` requires read-write access to `~/.cache/nix/fetcher-locks` for flake evaluation, and the repository checkout resides under the operator's user directory. - - `ProtectSystem=strict`: Ruled out because `nix develop` requires writable `/tmp` for development shell temporary files (`/tmp/nix-shell.*`). + - `ProtectSystem=strict`: Ruled out because it mounts the entire filesystem read-only, including the operator's home directory and the repository checkout; `nix develop` needs write access to `~/.cache/nix/fetcher-locks` for flake evaluation (the same constraint that rules out `ProtectHome`). Writable `/tmp` is not the blocker: with `PrivateTmp=yes`, systemd keeps `/tmp` and `/var/tmp` writable even under `strict`. - `PrivateNetwork=yes`: Ruled out because the MCP daemon must communicate over the local network to the TV via SSAP (`wss://:3001`), Developer Mode SSH/SFTP (`:9922`), and Wake-on-LAN UDP broadcasts. ### Developer Mode SSH Capture Setup From 5a8ebffad2ccd390e00f9a5c5521db056706d1d2 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 17 Nov 2026 16:15:56 -0500 Subject: [PATCH 4/4] fix(capture): read Dev Mode screenshots via asyncssh SFTP open() - src/lg_smtv_mcp/tv_core/capture.py: replace the nonexistent sftp.read() with sftp.open(path, 'rb') and an async context manager; the live AC#2 smoke against asyncssh 2.24.0 raised AttributeError because SFTPClient exposes open(), not read() - tests/test_capture.py: reshape the SFTP fake to the real asyncssh contract (regular open(), async file read(), async context manager) and add a regression test asserting the real class API, closing the mock gap that let offline tests pass while the live screenshot tool failed - tests/test_server.py: align the capture-wiring SFTP fake with the same open()/async-file contract so the default transport test exercises the real call shape --- src/lg_smtv_mcp/tv_core/capture.py | 3 +- tests/test_capture.py | 87 +++++++++++++++++++++++++----- tests/test_server.py | 14 ++++- 3 files changed, 87 insertions(+), 17 deletions(-) diff --git a/src/lg_smtv_mcp/tv_core/capture.py b/src/lg_smtv_mcp/tv_core/capture.py index 8c137ca..10ba458 100644 --- a/src/lg_smtv_mcp/tv_core/capture.py +++ b/src/lg_smtv_mcp/tv_core/capture.py @@ -102,7 +102,8 @@ class AsyncSshCaptureTransport: try: async with asyncio.timeout(timeout): sftp = await self._ensure_sftp(exclude=remote_path) - data = await sftp.read(remote_path) + async with sftp.open(remote_path, "rb") as handle: + data = await handle.read() return bytes(data) except asyncssh.Error, OSError: await self._close_handles() diff --git a/tests/test_capture.py b/tests/test_capture.py index b3e9be3..f36ec06 100644 --- a/tests/test_capture.py +++ b/tests/test_capture.py @@ -2,9 +2,11 @@ import asyncio import hashlib +import inspect from pathlib import Path from typing import Any +import asyncssh import pytest from lg_smtv_mcp.config import TvConfig @@ -12,6 +14,35 @@ from lg_smtv_mcp.errors import ErrorCode, TvError from lg_smtv_mcp.tv_core.capture import AsyncSshCaptureTransport, CaptureClient +class FakeSftpFile: + """Mirror asyncssh.SFTPClientFile: sync open(), async read(), async context manager.""" + + def __init__( + self, + data: bytes, + *, + error: Exception | None = None, + read_delay: float = 0.0, + ) -> None: + self._data = data + self._error = error + self._read_delay = read_delay + self.closed = False + + async def __aenter__(self) -> FakeSftpFile: + return self + + async def __aexit__(self, *_exc: object) -> None: + self.closed = True + + async def read(self) -> bytes: + if self._read_delay > 0: + await asyncio.sleep(self._read_delay) + if self._error is not None: + raise self._error + return self._data + + class FakeSftpClient: def __init__( self, @@ -19,25 +50,34 @@ class FakeSftpClient: files: dict[str, bytes] | None = None, extra_names: list[str] | None = None, read_error: Exception | None = None, + read_delay: float = 0.0, remove_delay: float = 0.0, remove_error: Exception | None = None, ) -> None: self.files = dict(files or {}) self.extra_names = list(extra_names or []) self.read_error = read_error + self.read_delay = read_delay self.remove_delay = remove_delay self.remove_error = remove_error - self.read_calls: list[str] = [] + self.open_calls: list[tuple[str, str]] = [] + self.handles: list[FakeSftpFile] = [] self.remove_calls: list[str] = [] self.closed = False - async def read(self, path: str) -> bytes: - self.read_calls.append(path) - if self.read_error is not None: - raise self.read_error - if path not in self.files: - raise FileNotFoundError(path) - return self.files[path] + def open(self, path: str, mode: str = "r") -> FakeSftpFile: + """Mirror asyncssh.SFTPClient.open: regular function returning an async file.""" + self.open_calls.append((path, mode)) + error = self.read_error + if error is None and path not in self.files: + error = FileNotFoundError(path) + handle = FakeSftpFile( + self.files.get(path, b""), + error=error, + read_delay=self.read_delay, + ) + self.handles.append(handle) + return handle async def remove(self, path: str) -> None: if self.remove_delay > 0: @@ -155,6 +195,30 @@ async def test_async_ssh_capture_transport_connect_uses_required_args(tmp_path: assert calls[0]["passphrase"] == "secret" +async def test_async_ssh_capture_transport_reads_via_real_sftp_open_api(tmp_path: Path) -> None: + """Guard against reintroducing sftp.read(), which asyncssh 2.24 does not expose.""" + assert not hasattr(asyncssh.SFTPClient, "read") + assert hasattr(asyncssh.SFTPClient, "open") + assert hasattr(asyncssh.SFTPClientFile, "__aenter__") + assert inspect.iscoroutinefunction(asyncssh.SFTPClientFile.read) + + remote_path = "/tmp/lg_smtv_cap_1.jpg" + sftp = FakeSftpClient(files={remote_path: b"jpeg"}) + conn = FakeSshConnection(sftp) + + async def fake_connect(**kwargs: Any) -> FakeSshConnection: + _ = kwargs + return conn + + transport = AsyncSshCaptureTransport(_make_config(tmp_path), connect_fn=fake_connect) + data = await transport.read_and_remove(remote_path) + + assert data == b"jpeg" + assert sftp.open_calls == [(remote_path, "rb")] + assert len(sftp.handles) == 1 + assert sftp.handles[0].closed is True + + async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconnect( tmp_path: Path, ) -> None: @@ -248,12 +312,7 @@ async def test_async_ssh_capture_transport_closes_connection_when_start_sftp_cli async def test_async_ssh_capture_transport_enforces_read_timeout( tmp_path: Path, ) -> None: - class HangingSftp(FakeSftpClient): - async def read(self, path: str) -> bytes: - await asyncio.sleep(10.0) - return b"never" - - sftp = HangingSftp(files={"/tmp/lg_smtv_cap_1.jpg": b"bytes"}) + sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"bytes"}, read_delay=10.0) conn = FakeSshConnection(sftp) async def fake_connect(**kwargs: Any) -> FakeSshConnection: diff --git a/tests/test_server.py b/tests/test_server.py index c758518..d53b4df 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -487,8 +487,18 @@ async def test_server_create_mcp_server_wires_default_capture_client( _ = path return [] - async def read(self, path: str) -> bytes: - return remote_files[path] + def open(self, path: str, mode: str = "r") -> Any: + class FakeFile: + async def __aenter__(self) -> FakeFile: + return self + + async def __aexit__(self, *_exc: object) -> None: + return None + + async def read(self) -> bytes: + return remote_files[path] + + return FakeFile() async def remove(self, path: str) -> None: removed_paths.append(path)