chore(deploy): harden systemd unit sandboxing and add automated verify test
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
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)
This commit is contained in:
1 parent
b2738c0d48
commit
0bf2923edb
4 files changed
+124
-3
No files matched your search
@@ -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.
|
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.**
|
> **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.
|
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 `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
|
### 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:
|
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:
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
Description=LG webOS Smart TV MCP server
|
Description=LG webOS Smart TV MCP server
|
||||||
Wants=network-online.target
|
Wants=network-online.target
|
||||||
After=network-online.target
|
After=network-online.target
|
||||||
|
StartLimitIntervalSec=60s
|
||||||
|
StartLimitBurst=5
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
@@ -13,5 +15,21 @@ ExecStart=/usr/bin/env nix develop --command python -m lg_smtv_mcp serve
|
|||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=5s
|
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]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
@@ -25,6 +25,10 @@
|
|||||||
ps.pytest-asyncio
|
ps.pytest-asyncio
|
||||||
];
|
];
|
||||||
|
|
||||||
|
testTools = [
|
||||||
|
pkgs.systemd
|
||||||
|
];
|
||||||
|
|
||||||
pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps);
|
pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps);
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
@@ -39,7 +43,7 @@
|
|||||||
ps.pytestCheckHook
|
ps.pytestCheckHook
|
||||||
pkgs.ruff
|
pkgs.ruff
|
||||||
pkgs.pyright
|
pkgs.pyright
|
||||||
] ++ testDeps;
|
] ++ testDeps ++ testTools;
|
||||||
preCheck = ''
|
preCheck = ''
|
||||||
ruff check .
|
ruff check .
|
||||||
ruff format --check .
|
ruff format --check .
|
||||||
@@ -52,7 +56,7 @@
|
|||||||
pythonEnv
|
pythonEnv
|
||||||
pkgs.pyright
|
pkgs.pyright
|
||||||
pkgs.ruff
|
pkgs.ruff
|
||||||
];
|
] ++ testTools;
|
||||||
shellHook = ''
|
shellHook = ''
|
||||||
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
|
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
|
||||||
if [ -d .git ] && [ -d .githooks ]; then
|
if [ -d .git ] && [ -d .githooks ]; then
|
||||||
|
|||||||
@@ -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 "<User>" in content
|
||||||
|
assert "<WorkingDirectory>" in content
|
||||||
|
assert "<NixBinDir>" 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("<User>", "kiskaadee")
|
||||||
|
.replace("<WorkingDirectory>", "/home/kiskaadee/Projects/active/lg-smtv-mcp")
|
||||||
|
.replace("<NixBinDir>", "/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("<User>", "kiskaadee")
|
||||||
|
.replace("<WorkingDirectory>", "/home/kiskaadee/Projects/active/lg-smtv-mcp")
|
||||||
|
.replace("<NixBinDir>", "/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}"
|
||||||
Reference in new issue
Block a user