5 Commits
Author SHA1 Message Date
kiskaadee 42bd4edf09 Merge pull request 'chore(deploy): harden systemd unit sandboxing and add automated verify test (#17)' (#18) from chore/issue-17-systemd-hardening into main
Core Architecture & Invariant CI / validate (push) Successful in 24s
2026-11-18 23:40:33 -05:00
kiskaadee 5a8ebffad2 fix(capture): read Dev Mode screenshots via asyncssh SFTP open()
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
- 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
2026-11-17 16:15:56 -05:00
kiskaadee 9195d91d7d docs(deploy): correct ProtectSystem=strict rejection rationale
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
- 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
2026-11-17 10:01:38 -05:00
kiskaadee 52ec28f278 test(deploy): harden test seams with section-aware parsing and fault-safe fixtures
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
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
2026-11-17 09:53:30 -05:00
kiskaadee 0bf2923edb chore(deploy): harden systemd unit sandboxing and add automated verify test
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
- 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)
2026-11-17 03:07:49 -05:00
7 changed files with 256 additions and 19 deletions

No files matched your search

+20 -1
View File
@@ -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=<proxy-or-vpn-hostname>` 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 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
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:
+18
View File
@@ -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
+6 -2
View File
@@ -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
+2 -1
View File
@@ -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()
+73 -14
View File
@@ -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:
+126
View File
@@ -0,0 +1,126 @@
"""Unit tests verifying deploy/lg-smtv-mcp.service template and sandboxing directives."""
import configparser
import re
import shutil
import subprocess
from pathlib import Path
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("<User>", "testuser")
.replace("<WorkingDirectory>", str(workdir))
.replace("<NixBinDir>", 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_declares_deployment_placeholders():
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
assert "<User>" in content
assert "<WorkingDirectory>" in content
assert "<NixBinDir>" in content
def test_service_template_bounds_restart_limit_in_unit_section():
content = SERVICE_TEMPLATE_PATH.read_text(encoding="utf-8")
parser = _parse_service_template(content)
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"
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_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}"
# 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 by systemd-analyze security"
score_line = lines[0]
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"
+11 -1
View File
@@ -487,9 +487,19 @@ async def test_server_create_mcp_server_wires_default_capture_client(
_ = path
return []
async def read(self, path: str) -> bytes:
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)
remote_files.pop(path, None)