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}"