Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42bd4edf09 | ||
|
|
5a8ebffad2 | ||
|
|
9195d91d7d | ||
|
|
52ec28f278 | ||
|
|
0bf2923edb | ||
|
|
b2738c0d48 | ||
|
|
ea0c1d9774 | ||
|
|
4af32b993d |
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).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -140,12 +140,14 @@ MAX_VOLUME=40
|
|||||||
|
|
||||||
## Running the MVP Server (`pair` & `serve`)
|
## Running the MVP Server (`pair` & `serve`)
|
||||||
|
|
||||||
|
> **Note:** Inside `nix develop`, run commands using `python -m lg_smtv_mcp <subcommand>` (or `nix run . -- <subcommand>`), as the devShell provisions the Python environment directly rather than installing package console scripts to `PATH`.
|
||||||
|
|
||||||
1. **Pair with the TV (one-time per TV):** Ensure the TV is powered on with *LG Connect Apps* enabled, then run:
|
1. **Pair with the TV (one-time per TV):** Ensure the TV is powered on with *LG Connect Apps* enabled, then run:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
lg-smtv-mcp pair
|
python -m lg_smtv_mcp pair
|
||||||
# Optional: override IP or also fetch Developer Mode SSH key
|
# Optional: override IP or also fetch Developer Mode SSH key
|
||||||
lg-smtv-mcp pair --ip <TV_IP>
|
python -m lg_smtv_mcp pair --ip <TV_IP>
|
||||||
```
|
```
|
||||||
|
|
||||||
Accept the pairing prompt on the TV screen. The client key is saved atomically with `0600` permissions to `CLIENT_KEY_PATH` (default `.client_key.json`).
|
Accept the pairing prompt on the TV screen. The client key is saved atomically with `0600` permissions to `CLIENT_KEY_PATH` (default `.client_key.json`).
|
||||||
@@ -155,10 +157,10 @@ MAX_VOLUME=40
|
|||||||
```bash
|
```bash
|
||||||
# Default: persistent Streamable HTTP daemon at http://<HOST>:<PORT>/mcp
|
# Default: persistent Streamable HTTP daemon at http://<HOST>:<PORT>/mcp
|
||||||
# Requires Authorization: Bearer <MCP_BEARER_TOKEN>
|
# Requires Authorization: Bearer <MCP_BEARER_TOKEN>
|
||||||
lg-smtv-mcp serve
|
python -m lg_smtv_mcp serve
|
||||||
|
|
||||||
# Local testing over stdio (no HTTP Bearer token required)
|
# Local testing over stdio (no HTTP Bearer token required)
|
||||||
lg-smtv-mcp serve --transport stdio
|
python -m lg_smtv_mcp serve --transport stdio
|
||||||
```
|
```
|
||||||
|
|
||||||
If you re-pair while `serve` is running, send `SIGHUP` to reload `.client_key.json` without restarting the daemon.
|
If you re-pair while `serve` is running, send `SIGHUP` to reload `.client_key.json` without restarting the daemon.
|
||||||
@@ -189,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 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
|
### 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:
|
||||||
@@ -203,9 +224,9 @@ On a trusted home LAN, SSH host-key checking is disabled by default because the
|
|||||||
|
|
||||||
## Operator Live-TV E2E Smoke Test Checklist
|
## Operator Live-TV E2E Smoke Test Checklist
|
||||||
|
|
||||||
Automated tests run strictly offline. After deploying or updating on a host on the same LAN as the TV, run this manual smoke checklist from an MCP client connected to `lg-smtv-mcp serve`:
|
Automated tests run strictly offline. After deploying or updating on a host on the same LAN as the TV, run this manual smoke checklist from an MCP client connected to `python -m lg_smtv_mcp serve`:
|
||||||
|
|
||||||
- [ ] **`pair`**: Run `lg-smtv-mcp pair`, accept the on-screen TV prompt, and confirm `CLIENT_KEY_PATH` (`.client_key.json`) exists with `0600` permissions and an entry for `<TV_IP>`.
|
- [ ] **`pair`**: Run `python -m lg_smtv_mcp pair`, accept the on-screen TV prompt, and confirm `CLIENT_KEY_PATH` (`.client_key.json`) exists with `0600` permissions and an entry for `<TV_IP>`.
|
||||||
- [ ] **`tv_wake`**: With the TV in standby, verify a mutating tool (`launch`) fails fast with `TV_OFFLINE_STANDBY` (no implicit WoL), then call `tv_wake` and confirm the TV powers on and returns `status: "connected"`.
|
- [ ] **`tv_wake`**: With the TV in standby, verify a mutating tool (`launch`) fails fast with `TV_OFFLINE_STANDBY` (no implicit WoL), then call `tv_wake` and confirm the TV powers on and returns `status: "connected"`.
|
||||||
- [ ] **`get_state`**: Call `get_state` and confirm `connected: true`, `stale: false`, and live `volume`, `muted`, `sound_output`, and `foreground_app` values.
|
- [ ] **`get_state`**: Call `get_state` and confirm `connected: true`, `stale: false`, and live `volume`, `muted`, `sound_output`, and `foreground_app` values.
|
||||||
- [ ] **`launch`**: Call `launch` (e.g., `app_id="youtube.leanback.v4"` with an optional `content_target`) and confirm the app opens on screen.
|
- [ ] **`launch`**: Call `launch` (e.g., `app_id="youtube.leanback.v4"` with an optional `content_target`) and confirm the app opens on screen.
|
||||||
|
|||||||
+5
-5
@@ -2,12 +2,11 @@
|
|||||||
|
|
||||||
## Current Direction
|
## Current Direction
|
||||||
|
|
||||||
`lg-smtv-mcp` has completed its M1 MVP control plane (persistent SSAP, pointer input, WoL recovery, FastMCP tools, Bearer auth, `pair`/`serve` CLI, and full-stack offline E2E verification) and the M2 capture and E2E-hardening slices. Remaining M2 work is deployment packaging and its `systemd` hardening follow-up.
|
`lg-smtv-mcp` has completed Milestone M2 (capture, E2E hardening, and systemd deployment packaging). Active work is the `systemd` unit sandboxing hardening follow-up ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17), Backlog) and the live-TV operator smoke verification.
|
||||||
|
|
||||||
## Near Term (Milestone M2)
|
## Near Term
|
||||||
|
|
||||||
- **Systemd Unit & Deployment Docs ([#13](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/13)):** Add `deploy/lg-smtv-mcp.service` template and document systemd + Developer Mode SSH setup in `README.md`.
|
- **Systemd Unit Sandboxing Hardening ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)):** Tighten the `deploy/lg-smtv-mcp.service` sandbox directives (`PrivateTmp`, `ProtectSystem`, capability drops, etc.) as a post-M2 hardening pass.
|
||||||
- **Systemd Unit Sandboxing Hardening ([#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17)):** Follow-up to `#13`, tightening the unit's sandboxing directives once the baseline deployment template lands.
|
|
||||||
|
|
||||||
## Medium Term
|
## Medium Term
|
||||||
|
|
||||||
@@ -15,9 +14,10 @@
|
|||||||
|
|
||||||
## Completed
|
## Completed
|
||||||
|
|
||||||
### M2: Capture & E2E Hardening (partial, 2026-11-16)
|
### M2: Capture, E2E Hardening & Systemd Deployment (Completed 2026-11-17)
|
||||||
- **#11 (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)):** E2E harness hardening in [`tests/test_e2e_mvp.py`](tests/test_e2e_mvp.py) — fast-fail ASGI lifespan startup, `elapsed_ms` contract check, and post-`turn_off()` `1008` -> `get_state` stale parity.
|
- **#11 (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)):** E2E harness hardening in [`tests/test_e2e_mvp.py`](tests/test_e2e_mvp.py) — fast-fail ASGI lifespan startup, `elapsed_ms` contract check, and post-`turn_off()` `1008` -> `get_state` stale parity.
|
||||||
- **#12 (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)):** `tv_core/capture.py` (`CaptureClient` + `AsyncSshCaptureTransport`), default `server.py` wiring, and offline capture contract tests; review remediation CR-01..CR-11 landed in `61d2315`.
|
- **#12 (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)):** `tv_core/capture.py` (`CaptureClient` + `AsyncSshCaptureTransport`), default `server.py` wiring, and offline capture contract tests; review remediation CR-01..CR-11 landed in `61d2315`.
|
||||||
|
- **#13 (PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16)):** `deploy/lg-smtv-mcp.service` systemd template, deployment + Developer Mode SSH setup docs in `README.md`, and DNS-rebinding / PATH env guidance.
|
||||||
|
|
||||||
### M1: MVP Core & End-to-End Verification (Completed 2026-11-16)
|
### M1: MVP Core & End-to-End Verification (Completed 2026-11-16)
|
||||||
- **#1 (PR [#6](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/6)):** Nix flake packaging, `pyproject.toml`, Pydantic v2 `TvConfig`, and `ConfigError` / `TvError` taxonomy.
|
- **#1 (PR [#6](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/6)):** Nix flake packaging, `pyproject.toml`, Pydantic v2 `TvConfig`, and `ConfigError` / `TvError` taxonomy.
|
||||||
|
|||||||
@@ -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
|
||||||
+10
-16
@@ -3,7 +3,7 @@
|
|||||||
* **Author:** kiskaadee
|
* **Author:** kiskaadee
|
||||||
* **Status:** Approved
|
* **Status:** Approved
|
||||||
* **Date:** 2026-11-15
|
* **Date:** 2026-11-15
|
||||||
* **Last reconciled:** 2026-11-16 (M2 `#12` / PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15) merged)
|
* **Last reconciled:** 2026-11-17 (M2 fully delivered: `#13` / PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16) merged; Milestone M2 closed)
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
@@ -267,7 +267,7 @@ All tools return structured JSON payloads (plus inline MCP `ImageContent` when `
|
|||||||
|
|
||||||
## Detailed Implementation Plan
|
## Detailed Implementation Plan
|
||||||
|
|
||||||
Milestone M1 foundations (`#1`–`#4`) and the M2 capture/E2E slices (`#11`, `#12`) are implemented, verified, and merged on `main`. The completed baselines are summarized for reference below; the active plan specifies the remaining Milestone M2 deployment slice (`#13`).
|
Milestone M1 foundations (`#1`–`#4`) and all Milestone M2 slices (`#11`, `#12`, `#13`) are implemented, verified, and merged on `main`. The completed baselines are summarized for reference below. Follow-up `systemd` unit sandboxing hardening is tracked separately in [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17).
|
||||||
|
|
||||||
### Completed Milestone M1 Baseline (`#1`–`#4`, Merged on `main`)
|
### Completed Milestone M1 Baseline (`#1`–`#4`, Merged on `main`)
|
||||||
|
|
||||||
@@ -278,7 +278,7 @@ Milestone M1 foundations (`#1`–`#4`) and the M2 capture/E2E slices (`#11`, `#1
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Completed Milestone M2 Slices (`#11`, `#12` — Merged on `main`)
|
### Completed Milestone M2 Slices (`#11`, `#12`, `#13` — Merged on `main`)
|
||||||
|
|
||||||
Delivered by `#12` (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)) and `#11` (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)). The contracts below match `main` as merged, including the PR `#15` review remediation (CR-01..CR-11).
|
Delivered by `#12` (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/15)) and `#11` (PR [#14](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/14)). The contracts below match `main` as merged, including the PR `#15` review remediation (CR-01..CR-11).
|
||||||
|
|
||||||
@@ -328,21 +328,15 @@ Delivered by `#12` (PR [#15](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/p
|
|||||||
* Asserted `isinstance(wake_payload["elapsed_ms"], int) and wake_payload["elapsed_ms"] >= 0` on `tv_wake`.
|
* Asserted `isinstance(wake_payload["elapsed_ms"], int) and wake_payload["elapsed_ms"] >= 0` on `tv_wake`.
|
||||||
* After `turn_off()`, simulated the TV closing the SSAP WebSocket with `1008` and re-queried `get_state` to verify `connected: false, stale: true` with cached state retained.
|
* After `turn_off()`, simulated the TV closing the SSAP WebSocket with `1008` and re-queried `get_state` to verify `connected: false, stale: true` with cached state retained.
|
||||||
|
|
||||||
* **M2 Delivery Checkpoint:** `nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"` and `nix flake check` passed for `#11` and `#12`.
|
#### 5. `deploy/lg-smtv-mcp.service` and `README.md` (Completed — Issue `#13`, PR [#16](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/pulls/16))
|
||||||
|
|
||||||
---
|
* **Type / Scope:** Systemd unit template and operator deployment documentation.
|
||||||
|
* **Delivered Changes:**
|
||||||
|
* Created `deploy/lg-smtv-mcp.service` template invoking `nix develop --command python -m lg_smtv_mcp serve` with `<User>`, `<WorkingDirectory>`, `EnvironmentFile`, `Restart=on-failure`, and `PATH` containing `<NixBinDir>`.
|
||||||
|
* Updated `README.md` with `systemd` setup instructions, Developer Mode pairing workflow (`python -m lg_smtv_mcp pair --fetch-ssh-key`), DNS-rebinding host configuration (`HOST` + `ALLOWED_HOSTS`), and live-TV operator smoke checklist items.
|
||||||
|
* Follow-up unit sandboxing hardening is tracked separately in issue [#17](https://gitea.roadtotech.me/kiskaadee/lg-smtv-mcp/issues/17).
|
||||||
|
|
||||||
### Active Milestone M2 Plan: Systemd Deployment (`#13`)
|
* **M2 Delivery Checkpoint:** All checks (`ruff`, `pyright`, `pytest`, `nix flake check`) passed; PR #16 merged on `main`.
|
||||||
|
|
||||||
#### 1. `deploy/lg-smtv-mcp.service` and `README.md` (Create / Modify — Issue `#13`)
|
|
||||||
|
|
||||||
* **Type / Scope:** Systemd unit template and operator documentation.
|
|
||||||
* **Proposed Changes:**
|
|
||||||
* Create `deploy/lg-smtv-mcp.service` with `<User>`, `<WorkingDirectory>`, `EnvironmentFile`, `After=network-online.target`, `Wants=network-online.target`, and `Restart=on-failure`, invoking `nix develop --command python -m lg_smtv_mcp serve`.
|
|
||||||
* Update `README.md` with `systemd` deployment steps (including ensuring `nix` is on `systemd`'s `PATH`), Developer Mode SSH setup (`pair --fetch-ssh-key`, `:9922` session timer behavior, `SSH_KNOWN_HOSTS_PATH`), and a live-TV `screenshot` / `keys(..., capture=True)` smoke checklist item.
|
|
||||||
* A follow-up issue (`#17`) tracks tightening the unit's sandboxing directives after this baseline template lands.
|
|
||||||
|
|
||||||
* **M2 Completion Checkpoint:** `nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"` and `nix flake check`.
|
|
||||||
|
|
||||||
### Verification Plan
|
### Verification Plan
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -102,7 +102,8 @@ class AsyncSshCaptureTransport:
|
|||||||
try:
|
try:
|
||||||
async with asyncio.timeout(timeout):
|
async with asyncio.timeout(timeout):
|
||||||
sftp = await self._ensure_sftp(exclude=remote_path)
|
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)
|
return bytes(data)
|
||||||
except asyncssh.Error, OSError:
|
except asyncssh.Error, OSError:
|
||||||
await self._close_handles()
|
await self._close_handles()
|
||||||
|
|||||||
+73
-14
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import inspect
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
import asyncssh
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from lg_smtv_mcp.config import TvConfig
|
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
|
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:
|
class FakeSftpClient:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -19,25 +50,34 @@ class FakeSftpClient:
|
|||||||
files: dict[str, bytes] | None = None,
|
files: dict[str, bytes] | None = None,
|
||||||
extra_names: list[str] | None = None,
|
extra_names: list[str] | None = None,
|
||||||
read_error: Exception | None = None,
|
read_error: Exception | None = None,
|
||||||
|
read_delay: float = 0.0,
|
||||||
remove_delay: float = 0.0,
|
remove_delay: float = 0.0,
|
||||||
remove_error: Exception | None = None,
|
remove_error: Exception | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.files = dict(files or {})
|
self.files = dict(files or {})
|
||||||
self.extra_names = list(extra_names or [])
|
self.extra_names = list(extra_names or [])
|
||||||
self.read_error = read_error
|
self.read_error = read_error
|
||||||
|
self.read_delay = read_delay
|
||||||
self.remove_delay = remove_delay
|
self.remove_delay = remove_delay
|
||||||
self.remove_error = remove_error
|
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.remove_calls: list[str] = []
|
||||||
self.closed = False
|
self.closed = False
|
||||||
|
|
||||||
async def read(self, path: str) -> bytes:
|
def open(self, path: str, mode: str = "r") -> FakeSftpFile:
|
||||||
self.read_calls.append(path)
|
"""Mirror asyncssh.SFTPClient.open: regular function returning an async file."""
|
||||||
if self.read_error is not None:
|
self.open_calls.append((path, mode))
|
||||||
raise self.read_error
|
error = self.read_error
|
||||||
if path not in self.files:
|
if error is None and path not in self.files:
|
||||||
raise FileNotFoundError(path)
|
error = FileNotFoundError(path)
|
||||||
return self.files[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:
|
async def remove(self, path: str) -> None:
|
||||||
if self.remove_delay > 0:
|
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"
|
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(
|
async def test_async_ssh_capture_transport_sweeps_on_initial_connect_and_reconnect(
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> 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(
|
async def test_async_ssh_capture_transport_enforces_read_timeout(
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
class HangingSftp(FakeSftpClient):
|
sftp = FakeSftpClient(files={"/tmp/lg_smtv_cap_1.jpg": b"bytes"}, read_delay=10.0)
|
||||||
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"})
|
|
||||||
conn = FakeSshConnection(sftp)
|
conn = FakeSshConnection(sftp)
|
||||||
|
|
||||||
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
async def fake_connect(**kwargs: Any) -> FakeSshConnection:
|
||||||
|
|||||||
@@ -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
@@ -487,9 +487,19 @@ async def test_server_create_mcp_server_wires_default_capture_client(
|
|||||||
_ = path
|
_ = path
|
||||||
return []
|
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 remote_files[path]
|
||||||
|
|
||||||
|
return FakeFile()
|
||||||
|
|
||||||
async def remove(self, path: str) -> None:
|
async def remove(self, path: str) -> None:
|
||||||
removed_paths.append(path)
|
removed_paths.append(path)
|
||||||
remote_files.pop(path, None)
|
remote_files.pop(path, None)
|
||||||
|
|||||||
Reference in new issue
Block a user