diff --git a/src/lg_smtv_mcp/auth.py b/src/lg_smtv_mcp/auth.py new file mode 100644 index 0000000..ad3b5c0 --- /dev/null +++ b/src/lg_smtv_mcp/auth.py @@ -0,0 +1,122 @@ +"""HTTP Bearer authentication ASGI middleware and MCP transport security settings.""" + +import hmac +import json +from collections.abc import Awaitable, Callable, Iterable, MutableMapping +from typing import Any + +from mcp.server.transport_security import TransportSecuritySettings + +from lg_smtv_mcp.config import TvConfig +from lg_smtv_mcp.errors import ConfigError + +type Scope = MutableMapping[str, Any] +type Receive = Callable[[], Awaitable[MutableMapping[str, Any]]] +type Send = Callable[[MutableMapping[str, Any]], Awaitable[None]] +type ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]] + +_UNAUTHORIZED_BODY = json.dumps({"error": "unauthorized"}).encode("utf-8") + + +def _dedupe(items: Iterable[str]) -> list[str]: + return list(dict.fromkeys(items)) + + +def _add_host_variants(hosts: list[str], origins: list[str], raw_host: str, port: int) -> None: + entry = raw_host.strip() + if not entry: + return + if entry.startswith(("http://", "https://")): + origins.append(entry) + return + hosts.append(entry) + if ":" not in entry: + hosts.append(f"{entry}:{port}") + for scheme in ("http", "https"): + origins.append(f"{scheme}://{entry}") + origins.append(f"{scheme}://{entry}:{port}") + else: + for scheme in ("http", "https"): + origins.append(f"{scheme}://{entry}") + + +def build_transport_security_settings(config: TvConfig) -> TransportSecuritySettings: + """Derive DNS-rebinding TransportSecuritySettings from TvConfig.""" + hosts: list[str] = [] + origins: list[str] = [] + + for local_host in ("127.0.0.1", "localhost"): + hosts.extend([f"{local_host}:{config.port}", f"{local_host}:*", local_host]) + for scheme in ("http", "https"): + origins.extend([f"{scheme}://{local_host}:{config.port}", f"{scheme}://{local_host}:*"]) + + if config.host and config.host not in {"0.0.0.0", "::"}: + _add_host_variants(hosts, origins, config.host, config.port) + + for extra_host in config.allowed_hosts: + _add_host_variants(hosts, origins, extra_host, config.port) + + return TransportSecuritySettings( + enable_dns_rebinding_protection=True, + allowed_hosts=_dedupe(hosts), + allowed_origins=_dedupe(origins), + ) + + +class BearerAuthMiddleware: + """ASGI middleware enforcing constant-time Authorization: Bearer .""" + + def __init__(self, app: ASGIApp, token: str) -> None: + cleaned = token.strip() + if not cleaned: + raise ConfigError("MCP_BEARER_TOKEN must be a non-empty string") + self._app = app + self._token_bytes = cleaned.encode("utf-8") + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope.get("type") != "http": + await self._app(scope, receive, send) + return + + if not self._is_authorized(scope): + await send( + { + "type": "http.response.start", + "status": 401, + "headers": [ + (b"content-type", b"application/json"), + (b"www-authenticate", b"Bearer"), + ], + } + ) + await send( + { + "type": "http.response.body", + "body": _UNAUTHORIZED_BODY, + "more_body": False, + } + ) + return + + await self._app(scope, receive, send) + + def _is_authorized(self, scope: Scope) -> bool: + headers: Iterable[tuple[bytes, bytes]] = scope.get("headers", ()) + auth_value: str | None = None + for name, value in headers: + if name.lower() == b"authorization": + auth_value = value.decode("latin-1") + break + if auth_value is None: + return False + + parts = auth_value.split(" ", 1) + if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1]: + return False + + return hmac.compare_digest(parts[1].encode("utf-8"), self._token_bytes) + + +def wrap_bearer_auth(app: ASGIApp, token: str) -> ASGIApp: + """Wrap an ASGI application with BearerAuthMiddleware.""" + return BearerAuthMiddleware(app, token) diff --git a/src/lg_smtv_mcp/cli.py b/src/lg_smtv_mcp/cli.py index fd29e47..24de904 100644 --- a/src/lg_smtv_mcp/cli.py +++ b/src/lg_smtv_mcp/cli.py @@ -1,9 +1,202 @@ -"""CLI entrypoint stub for lg-smtv-mcp (expanded in Issue #3).""" +"""CLI entrypoint for lg-smtv-mcp (serve and pair subcommands).""" -from collections.abc import Sequence +import argparse +import asyncio +import ipaddress +import json +import os +import sys +import tempfile +from collections.abc import Callable, Sequence +from contextlib import suppress +from pathlib import Path +from typing import Any, cast + +from mcp.server.mcpserver import MCPServer + +from lg_smtv_mcp.auth import ASGIApp +from lg_smtv_mcp.config import TvConfig, load_config +from lg_smtv_mcp.errors import ConfigError, ErrorCode, TvError +from lg_smtv_mcp.server import create_http_app, create_mcp_server +from lg_smtv_mcp.tv_core.protocols import WebSocketConnectFn +from lg_smtv_mcp.tv_core.ssap import build_register_payload, websockets_connect -def main(argv: Sequence[str] | None = None) -> int: - """CLI entrypoint stub.""" - _ = argv +def _default_uvicorn_run(app: ASGIApp, host: str, port: int) -> None: + import uvicorn + + uvicorn.run(app, host=host, port=port) + + +def _default_stdio_run(server: MCPServer[Any]) -> None: + server.run(transport="stdio") + + +def _default_fetch_url(url: str) -> bytes: + from urllib.request import urlopen + + with urlopen(url, timeout=10.0) as resp: # noqa: S310 + return bytes(resp.read()) + + +def _atomic_write_0600(path: Path, data: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent)) + tmp_path = Path(tmp_name) + try: + os.chmod(fd, 0o600) + with os.fdopen(fd, "wb") as handle: + handle.write(data) + os.chmod(tmp_path, 0o600) + os.replace(tmp_path, path) + except BaseException: + with suppress(OSError): + tmp_path.unlink() + raise + + +def _load_existing_keys(key_path: Path) -> dict[str, str]: + if not key_path.is_file(): + return {} + try: + raw = json.loads(key_path.read_text(encoding="utf-8")) + except OSError, json.JSONDecodeError: + return {} + if not isinstance(raw, dict): + return {} + raw_dict = cast(dict[Any, Any], raw) + return {str(k): str(v) for k, v in raw_dict.items() if isinstance(v, str) and v} + + +async def _pair_tv( + ip: str, + existing_key: str | None, + connect_fn: WebSocketConnectFn, +) -> str: + ws = await connect_fn(f"ws://{ip}:3000") + try: + reg_payload = build_register_payload(existing_key) + await ws.send(json.dumps(reg_payload)) + while True: + raw = await ws.recv() + frame: dict[str, Any] = json.loads(raw) + msg_type = frame.get("type") + if msg_type == "registered": + payload = frame.get("payload") + if isinstance(payload, dict): + payload_dict = cast(dict[str, Any], payload) + client_key = payload_dict.get("client-key") + if isinstance(client_key, str) and client_key: + return client_key + raise TvError(ErrorCode.PAIRING_REQUIRED, "TV registration returned no client-key") + if msg_type == "error": + raise TvError( + ErrorCode.PAIRING_REQUIRED, + f"TV pairing rejected: {frame.get('error', 'unknown error')}", + ) + finally: + await ws.close() + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="lg-smtv-mcp") + subparsers = parser.add_subparsers(dest="command", required=True) + + serve_parser = subparsers.add_parser("serve", help="Run the MCP server.") + serve_parser.add_argument( + "--transport", + choices=["streamable-http", "stdio"], + default="streamable-http", + help="MCP transport to serve.", + ) + + pair_parser = subparsers.add_parser("pair", help="Pair with an LG webOS TV.") + pair_parser.add_argument("--ip", default=None, help="TV IPv4 address (defaults to TV_IP).") + pair_parser.add_argument( + "--fetch-ssh-key", + action="store_true", + help="Also fetch Developer Mode SSH private key from http://:9991/webos_rsa.", + ) + pair_parser.add_argument( + "--ssh-key-path", + type=Path, + default=None, + help="Destination path for fetched Developer Mode SSH key.", + ) + return parser + + +def _handle_serve( + args: argparse.Namespace, + config: TvConfig, + *, + uvicorn_run: Callable[[ASGIApp, str, int], None], + stdio_run: Callable[[MCPServer[Any]], None], +) -> int: + if args.transport == "stdio": + server = create_mcp_server(config) + stdio_run(server) + return 0 + + app = create_http_app(config) + uvicorn_run(app, config.host, config.port) return 0 + + +def _handle_pair( + args: argparse.Namespace, + config: TvConfig, + *, + connect_fn: WebSocketConnectFn, + fetch_url: Callable[[str], bytes], +) -> int: + raw_ip: str = args.ip if args.ip is not None else config.tv_ip + try: + tv_ip = str(ipaddress.IPv4Address(raw_ip.strip())) + except ValueError as exc: + raise ConfigError(f"Invalid TV IPv4 address: {raw_ip!r}") from exc + + existing_keys = _load_existing_keys(config.client_key_path) + client_key = asyncio.run(_pair_tv(tv_ip, existing_keys.get(tv_ip), connect_fn)) + existing_keys[tv_ip] = client_key + _atomic_write_0600( + config.client_key_path, + (json.dumps(existing_keys, indent=2) + "\n").encode("utf-8"), + ) + + if args.fetch_ssh_key: + ssh_dest: Path = args.ssh_key_path or config.ssh_key_path or Path(".webos_rsa") + key_bytes = fetch_url(f"http://{tv_ip}:9991/webos_rsa") + if not key_bytes.strip(): + raise TvError( + ErrorCode.SCREENSHOT_UNAVAILABLE, + "Fetched Developer Mode SSH key was empty", + ) + _atomic_write_0600(ssh_dest, key_bytes) + + return 0 + + +def main( + argv: Sequence[str] | None = None, + *, + config_loader: Callable[[], TvConfig] = load_config, + uvicorn_run: Callable[[ASGIApp, str, int], None] = _default_uvicorn_run, + stdio_run: Callable[[MCPServer[Any]], None] = _default_stdio_run, + connect_fn: WebSocketConnectFn = websockets_connect, + fetch_url: Callable[[str], bytes] = _default_fetch_url, + env_path: Path | None = None, +) -> int: + """CLI entrypoint for `lg-smtv-mcp serve` and `lg-smtv-mcp pair`.""" + _ = env_path + parser = _build_parser() + args = parser.parse_args(list(argv) if argv is not None else None) + + try: + config = config_loader() + if args.command == "serve": + return _handle_serve(args, config, uvicorn_run=uvicorn_run, stdio_run=stdio_run) + return _handle_pair(args, config, connect_fn=connect_fn, fetch_url=fetch_url) + except (ConfigError, TvError, OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 diff --git a/src/lg_smtv_mcp/server.py b/src/lg_smtv_mcp/server.py new file mode 100644 index 0000000..b80de19 --- /dev/null +++ b/src/lg_smtv_mcp/server.py @@ -0,0 +1,192 @@ +"""MCP server, ASGI lifespan management, and LG webOS TV tool definitions.""" + +import asyncio +import base64 +import json +import signal +from collections.abc import AsyncGenerator, Awaitable, Callable +from contextlib import asynccontextmanager, suppress +from dataclasses import asdict +from typing import Any + +from mcp.server.mcpserver import MCPServer +from mcp.server.mcpserver.exceptions import ToolError +from mcp.types import ImageContent, TextContent + +from lg_smtv_mcp.auth import ASGIApp, build_transport_security_settings, wrap_bearer_auth +from lg_smtv_mcp.config import TvConfig, require_bearer_token +from lg_smtv_mcp.errors import ConfigError, TvError +from lg_smtv_mcp.tv_core import TvManager + + +async def _run_tv_call[T](fn: Callable[[], Awaitable[T]]) -> T: + try: + return await fn() + except TvError as exc: + raise ToolError(f"{exc.code.value}: {exc.message}") from exc + except ConfigError as exc: + raise ToolError(exc.message) from exc + + +def _build_capture_content( + metadata: dict[str, Any], + image_bytes: bytes | None, +) -> list[TextContent | ImageContent]: + items: list[TextContent | ImageContent] = [ + TextContent(type="text", text=json.dumps(metadata)), + ] + if image_bytes is not None: + encoded = base64.b64encode(image_bytes).decode("ascii") + items.append(ImageContent(type="image", data=encoded, mime_type="image/jpeg")) + return items + + +def _register_tools(server: MCPServer, tv_manager: TvManager, config: TvConfig) -> None: + @server.tool(description="Wake the TV via Wake-on-LAN and wait until SSAP is connected.") + async def tv_wake() -> dict[str, Any]: + status = await _run_tv_call(tv_manager.wake) + return asdict(status) + + @server.tool(description="Return cached TV state without blocking on standby or UI locks.") + async def get_state() -> dict[str, Any]: + return asdict(tv_manager.get_state()) + + @server.tool(description="Send a batch of remote control button keys with optional screenshot.") + async def keys( + keys: list[str], + delay_ms: int = 250, + settle_ms: int = 800, + capture: bool = False, + ) -> list[TextContent | ImageContent]: + res = await _run_tv_call( + lambda: tv_manager.send_keys( + keys, delay_ms=delay_ms, settle_ms=settle_ms, capture=capture + ) + ) + metadata: dict[str, Any] = {"keys_sent": res.keys_sent, "count": res.count} + if res.frame_sha256 is not None: + metadata["frame_sha256"] = res.frame_sha256 + if res.changed_since_last is not None: + metadata["changed_since_last"] = res.changed_since_last + if res.size_bytes is not None: + metadata["size_bytes"] = res.size_bytes + if res.capture_error is not None: + metadata["capture_error"] = res.capture_error + return _build_capture_content(metadata, res.image_bytes) + + @server.tool( + description=( + "Insert text via webOS IME (requires the TV's native on-screen keyboard to be open), " + "optionally pressing Enter and capturing a screenshot." + ) + ) + async def type_text( + text: str, + send_enter: bool = True, + capture: bool = False, + ) -> list[TextContent | ImageContent]: + res = await _run_tv_call( + lambda: tv_manager.type_text(text, send_enter=send_enter, capture=capture) + ) + metadata: dict[str, Any] = { + "text_sent": res.text_sent, + "enter_sent": res.enter_sent, + } + if res.frame_sha256 is not None: + metadata["frame_sha256"] = res.frame_sha256 + if res.changed_since_last is not None: + metadata["changed_since_last"] = res.changed_since_last + if res.size_bytes is not None: + metadata["size_bytes"] = res.size_bytes + if res.capture_error is not None: + metadata["capture_error"] = res.capture_error + return _build_capture_content(metadata, res.image_bytes) + + @server.tool(description="Capture a TV screenshot and return JPEG image content plus metadata.") + async def screenshot() -> list[TextContent | ImageContent]: + res = await _run_tv_call(tv_manager.screenshot) + metadata: dict[str, Any] = { + "frame_sha256": res.frame_sha256, + "changed_since_last": res.changed_since_last, + "size_bytes": res.size_bytes, + } + return _build_capture_content(metadata, res.image_bytes) + + @server.tool(description="Launch a webOS app by ID with optional contentTarget and params.") + async def launch( + app_id: str, + content_target: str | None = None, + params: dict[str, Any] | None = None, + ) -> dict[str, Any]: + return await _run_tv_call( + lambda: tv_manager.launch_app(app_id, content_target=content_target, params=params) + ) + + @server.tool(description="List installed TV apps as [{id, title}].") + async def list_apps() -> list[dict[str, str]]: + return await _run_tv_call(tv_manager.list_apps) + + @server.tool(description="Set TV volume within [0, MAX_VOLUME].") + async def set_volume(level: int) -> dict[str, Any]: + return await _run_tv_call(lambda: tv_manager.set_volume(level)) + + @server.tool(description="Set TV audio mute state.") + async def set_mute(muted: bool) -> dict[str, Any]: + return await _run_tv_call(lambda: tv_manager.set_mute(muted)) + + @server.tool(description="List external TV inputs as [{id, label, connected}].") + async def list_inputs() -> list[dict[str, Any]]: + return await _run_tv_call(tv_manager.list_inputs) + + @server.tool(description="Switch active external TV input by input_id.") + async def switch_input(input_id: str) -> dict[str, Any]: + return await _run_tv_call(lambda: tv_manager.switch_input(input_id)) + + @server.tool(description="Power off the TV into standby.") + async def turn_off() -> dict[str, Any]: + return await _run_tv_call(tv_manager.turn_off) + + if config.enable_raw_ssap: + + @server.tool( + description="Send a raw SSAP request (enabled only when ENABLE_RAW_SSAP=true)." + ) + async def raw_ssap(uri: str, payload: dict[str, Any] | None = None) -> dict[str, Any]: + return await _run_tv_call(lambda: tv_manager.raw_ssap(uri, payload)) + + +def create_mcp_server(config: TvConfig, manager: TvManager | None = None) -> MCPServer: + """Create and configure the MCPServer instance with TV tools and lifespan.""" + tv_manager = manager if manager is not None else TvManager(config) + + @asynccontextmanager + async def _lifespan(_server: MCPServer[None]) -> AsyncGenerator[None]: + loop = asyncio.get_running_loop() + await tv_manager.start() + sighup_registered = False + if hasattr(signal, "SIGHUP"): + with suppress(NotImplementedError, AttributeError, ValueError): + loop.add_signal_handler(signal.SIGHUP, tv_manager.reload_client_key) + sighup_registered = True + try: + yield + finally: + if sighup_registered and hasattr(signal, "SIGHUP"): + with suppress(NotImplementedError, AttributeError, ValueError): + loop.remove_signal_handler(signal.SIGHUP) + await tv_manager.close() + + server = MCPServer(name="lg-smtv-mcp", lifespan=_lifespan) + _register_tools(server, tv_manager, config) + return server + + +def create_http_app(config: TvConfig, manager: TvManager | None = None) -> ASGIApp: + """Create the Bearer-authenticated Streamable HTTP ASGI application.""" + token = require_bearer_token(config) + server = create_mcp_server(config, manager=manager) + app = server.streamable_http_app( + transport_security=build_transport_security_settings(config), + host=config.host, + ) + return wrap_bearer_auth(app, token) diff --git a/src/lg_smtv_mcp/tv_core/manager.py b/src/lg_smtv_mcp/tv_core/manager.py index 6397d45..9be4179 100644 --- a/src/lg_smtv_mcp/tv_core/manager.py +++ b/src/lg_smtv_mcp/tv_core/manager.py @@ -473,6 +473,7 @@ class TvManager: changed_since_last=cap.changed_since_last if cap is not None else None, size_bytes=cap.size_bytes if cap is not None else None, capture_error=cap_err, + image_bytes=cap.image_bytes if cap is not None else None, ) async def type_text( @@ -505,6 +506,7 @@ class TvManager: changed_since_last=cap.changed_since_last if cap is not None else None, size_bytes=cap.size_bytes if cap is not None else None, capture_error=cap_err, + image_bytes=cap.image_bytes if cap is not None else None, ) async def screenshot(self) -> CaptureResult: diff --git a/src/lg_smtv_mcp/tv_core/protocols.py b/src/lg_smtv_mcp/tv_core/protocols.py index a288d0f..9f1793f 100644 --- a/src/lg_smtv_mcp/tv_core/protocols.py +++ b/src/lg_smtv_mcp/tv_core/protocols.py @@ -95,6 +95,7 @@ class KeysResult: changed_since_last: bool | None = None size_bytes: int | None = None capture_error: str | None = None + image_bytes: bytes | None = None @dataclass(frozen=True, slots=True) @@ -107,3 +108,4 @@ class TextResult: changed_since_last: bool | None = None size_bytes: int | None = None capture_error: str | None = None + image_bytes: bytes | None = None diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..2a3283b --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,119 @@ +"""Offline contract tests for BearerAuthMiddleware and TransportSecuritySettings.""" + +from collections.abc import MutableMapping +from typing import Any + +import httpx +import pytest + +from lg_smtv_mcp.auth import ( + Receive, + Scope, + Send, + build_transport_security_settings, + wrap_bearer_auth, +) +from lg_smtv_mcp.config import TvConfig +from lg_smtv_mcp.errors import ConfigError + + +async def _ok_app(scope: Scope, receive: Receive, send: Send) -> None: + _ = (scope, receive) + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [(b"content-type", b"application/json")], + } + ) + await send({"type": "http.response.body", "body": b'{"ok":true}', "more_body": False}) + + +async def test_bearer_auth_allows_valid_token_and_forwards_to_app() -> None: + app = wrap_bearer_auth(_ok_app, "secret-token-123") + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client: + resp = await client.get("/mcp", headers={"Authorization": "Bearer secret-token-123"}) + + assert resp.status_code == 200 + assert resp.json() == {"ok": True} + + +@pytest.mark.parametrize( + "headers", + [ + {}, + {"Authorization": ""}, + {"Authorization": "Basic dXNlcjpwYXNz"}, + {"Authorization": "Bearer"}, + {"Authorization": "Bearer "}, + {"Authorization": "Bearer wrong-token"}, + {"Authorization": "Bearer secret-token-1234"}, + ], +) +async def test_bearer_auth_rejects_missing_malformed_or_invalid_token_with_401( + headers: dict[str, str], +) -> None: + app = wrap_bearer_auth(_ok_app, "secret-token-123") + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client: + resp = await client.get("/mcp", headers=headers) + + assert resp.status_code == 401 + assert resp.headers.get("www-authenticate") == "Bearer" + assert resp.json() == {"error": "unauthorized"} + + +async def test_bearer_auth_passes_through_non_http_lifespan_scope() -> None: + seen_scopes: list[str] = [] + + async def lifespan_app(scope: Scope, receive: Receive, send: Send) -> None: + _ = (receive, send) + seen_scopes.append(str(scope["type"])) + + app = wrap_bearer_auth(lifespan_app, "secret-token-123") + + async def dummy_receive() -> MutableMapping[str, Any]: + return {"type": "lifespan.startup"} + + async def dummy_send(message: MutableMapping[str, Any]) -> None: + _ = message + + await app({"type": "lifespan"}, dummy_receive, dummy_send) + assert seen_scopes == ["lifespan"] + + +@pytest.mark.parametrize("bad_token", ["", " "]) +def test_bearer_auth_rejects_blank_server_token_with_config_error(bad_token: str) -> None: + with pytest.raises(ConfigError): + wrap_bearer_auth(_ok_app, bad_token) + + +def test_transport_security_settings_includes_local_bound_host_and_allowed_hosts() -> None: + config = TvConfig( + tv_ip="192.0.2.10", + host="192.0.2.50", + port=9000, + allowed_hosts=("tv-mcp.local", "198.51.100.5:9000"), + ) + settings = build_transport_security_settings(config) + + assert settings.enable_dns_rebinding_protection is True + assert "127.0.0.1:9000" in settings.allowed_hosts + assert "localhost:9000" in settings.allowed_hosts + assert "192.0.2.50:9000" in settings.allowed_hosts + assert "tv-mcp.local" in settings.allowed_hosts + assert "tv-mcp.local:9000" in settings.allowed_hosts + assert "198.51.100.5:9000" in settings.allowed_hosts + assert "http://192.0.2.50:9000" in settings.allowed_origins + assert "http://tv-mcp.local:9000" in settings.allowed_origins + + +def test_transport_security_settings_excludes_wildcard_bind_host_from_allowed_hosts() -> None: + config = TvConfig(tv_ip="192.0.2.10", host="0.0.0.0", port=8765) + settings = build_transport_security_settings(config) + + assert "0.0.0.0" not in settings.allowed_hosts + assert "0.0.0.0:8765" not in settings.allowed_hosts + assert "127.0.0.1:8765" in settings.allowed_hosts + assert "localhost:8765" in settings.allowed_hosts diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..301770b --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,198 @@ +"""Offline contract tests for lg-smtv-mcp CLI (serve and pair).""" + +import json +import stat +from pathlib import Path +from typing import Any + +import httpx +import pytest +from mcp.server.mcpserver import MCPServer + +from lg_smtv_mcp.auth import ASGIApp +from lg_smtv_mcp.cli import main +from lg_smtv_mcp.config import TvConfig +from tests.conftest import FakeWebSocketTransport + + +def _make_config( + tmp_path: Path, + *, + token: str | None = "test-token", + ssh_key_path: Path | None = None, +) -> TvConfig: + return TvConfig( + tv_ip="192.0.2.10", + tv_mac="AA:BB:CC:DD:EE:FF", + client_key_path=tmp_path / ".client_key.json", + ssh_key_path=ssh_key_path, + mcp_bearer_token=token, + ) + + +@pytest.mark.parametrize("bad_token", [None, "", " "]) +def test_cli_serve_http_fails_closed_when_bearer_token_missing_or_blank( + tmp_path: Path, + bad_token: str | None, +) -> None: + called = False + + def fake_uvicorn(app: ASGIApp, host: str, port: int) -> None: + nonlocal called + _ = (app, host, port) + called = True + + rc = main( + ["serve", "--transport", "streamable-http"], + config_loader=lambda: _make_config(tmp_path, token=bad_token), + uvicorn_run=fake_uvicorn, + ) + + assert rc == 1 + assert called is False + + +async def test_cli_serve_http_runs_uvicorn_with_configured_host_and_port(tmp_path: Path) -> None: + captured: list[tuple[ASGIApp, str, int]] = [] + + def fake_uvicorn(app: ASGIApp, host: str, port: int) -> None: + captured.append((app, host, port)) + + rc = main( + ["serve", "--transport", "streamable-http"], + config_loader=lambda: _make_config(tmp_path, token="valid-secret"), + uvicorn_run=fake_uvicorn, + ) + + assert rc == 0 + assert len(captured) == 1 + app, host, port = captured[0] + assert host == "127.0.0.1" + assert port == 8765 + + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1:8765") as client: + unauth = await client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "initialize"}) + assert unauth.status_code == 401 + + +def test_cli_serve_stdio_delegates_to_stdio_runner_without_bearer_token(tmp_path: Path) -> None: + ran: list[MCPServer[Any]] = [] + + def fake_stdio(server: MCPServer[Any]) -> None: + ran.append(server) + + rc = main( + ["serve", "--transport", "stdio"], + config_loader=lambda: _make_config(tmp_path, token=None), + stdio_run=fake_stdio, + ) + + assert rc == 0 + assert len(ran) == 1 + assert isinstance(ran[0], MCPServer) + + +def test_cli_pair_merges_existing_client_keys_and_writes_0600(tmp_path: Path) -> None: + key_file = tmp_path / ".client_key.json" + key_file.write_text(json.dumps({"192.0.2.10": "old-key"}), encoding="utf-8") + + def on_send(raw: str, ws: FakeWebSocketTransport) -> None: + msg: dict[str, Any] = json.loads(raw) + if msg.get("type") == "register": + ws.push_json( + { + "type": "registered", + "id": msg["id"], + "payload": {"client-key": "new-key-20"}, + } + ) + + ws = FakeWebSocketTransport(on_send=on_send) + connected_urls: list[str] = [] + + async def fake_connect(url: str) -> FakeWebSocketTransport: + connected_urls.append(url) + return ws + + rc = main( + ["pair", "--ip", "192.0.2.20"], + config_loader=lambda: _make_config(tmp_path), + connect_fn=fake_connect, + ) + + assert rc == 0 + assert connected_urls == ["ws://192.0.2.20:3000"] + saved = json.loads(key_file.read_text(encoding="utf-8")) + assert saved == {"192.0.2.10": "old-key", "192.0.2.20": "new-key-20"} + assert stat.S_IMODE(key_file.stat().st_mode) == 0o600 + + +def test_cli_pair_fetch_ssh_key_saves_key_with_0600_permissions(tmp_path: Path) -> None: + ssh_dest = tmp_path / "webos_rsa" + fetched_urls: list[str] = [] + + def on_send(raw: str, ws: FakeWebSocketTransport) -> None: + msg: dict[str, Any] = json.loads(raw) + if msg.get("type") == "register": + ws.push_json( + { + "type": "registered", + "id": msg["id"], + "payload": {"client-key": "tv-key-10"}, + } + ) + + async def fake_connect(_url: str) -> FakeWebSocketTransport: + return FakeWebSocketTransport(on_send=on_send) + + def fake_fetch(url: str) -> bytes: + fetched_urls.append(url) + return b"-----BEGIN RSA PRIVATE KEY-----\nTEST\n-----END RSA PRIVATE KEY-----\n" + + rc = main( + ["pair", "--fetch-ssh-key", "--ssh-key-path", str(ssh_dest)], + config_loader=lambda: _make_config(tmp_path), + connect_fn=fake_connect, + fetch_url=fake_fetch, + ) + + assert rc == 0 + assert fetched_urls == ["http://192.0.2.10:9991/webos_rsa"] + assert ssh_dest.read_bytes().startswith(b"-----BEGIN RSA PRIVATE KEY-----") + assert stat.S_IMODE(ssh_dest.stat().st_mode) == 0o600 + + +def test_cli_pair_fetch_ssh_key_failure_preserves_client_key_and_exits_nonzero( + tmp_path: Path, +) -> None: + key_file = tmp_path / ".client_key.json" + ssh_dest = tmp_path / "webos_rsa" + + def on_send(raw: str, ws: FakeWebSocketTransport) -> None: + msg: dict[str, Any] = json.loads(raw) + if msg.get("type") == "register": + ws.push_json( + { + "type": "registered", + "id": msg["id"], + "payload": {"client-key": "tv-key-10"}, + } + ) + + async def fake_connect(_url: str) -> FakeWebSocketTransport: + return FakeWebSocketTransport(on_send=on_send) + + def failing_fetch(_url: str) -> bytes: + raise OSError("connection refused") + + rc = main( + ["pair", "--fetch-ssh-key", "--ssh-key-path", str(ssh_dest)], + config_loader=lambda: _make_config(tmp_path), + connect_fn=fake_connect, + fetch_url=failing_fetch, + ) + + assert rc == 1 + assert json.loads(key_file.read_text(encoding="utf-8")) == {"192.0.2.10": "tv-key-10"} + assert not ssh_dest.exists() diff --git a/tests/test_server.py b/tests/test_server.py new file mode 100644 index 0000000..6da11a0 --- /dev/null +++ b/tests/test_server.py @@ -0,0 +1,459 @@ +"""Offline contract tests for MCPServer tools, error mapping, and ASGI lifespan.""" + +import asyncio +import base64 +import hashlib +import json +import signal +from collections.abc import AsyncGenerator, Awaitable, Callable, MutableMapping +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any + +import httpx +import pytest +from mcp.server.mcpserver.exceptions import ToolError +from mcp.types import CallToolResult, ImageContent, TextContent + +from lg_smtv_mcp.config import TvConfig +from lg_smtv_mcp.errors import ErrorCode, TvError +from lg_smtv_mcp.server import create_http_app, create_mcp_server +from lg_smtv_mcp.tv_core import CaptureResult, ConnectionState, TvManager +from tests.conftest import FakeWebSocketTransport + +_TEST_JPEG = b"\xff\xd8\xff\xe0test-jpeg" +_TEST_SHA256 = hashlib.sha256(_TEST_JPEG).hexdigest() + + +class _FakeCapturer: + def __init__(self, *, error: TvError | None = None) -> None: + self._error = error + self.closed = False + + async def capture_frame( + self, + ssap_request_fn: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]], + ) -> CaptureResult: + _ = ssap_request_fn + if self._error is not None: + raise self._error + return CaptureResult( + image_bytes=_TEST_JPEG, + frame_sha256=_TEST_SHA256, + changed_since_last=True, + size_bytes=len(_TEST_JPEG), + ) + + async def close(self) -> None: + self.closed = True + + +def _make_config( + tmp_path: Path, + *, + enable_raw_ssap: bool = False, + max_volume: int = 30, +) -> TvConfig: + key_file = tmp_path / ".client_key.json" + key_file.write_text(json.dumps({"192.0.2.10": "saved-key"}), encoding="utf-8") + return TvConfig( + tv_ip="192.0.2.10", + tv_mac="AA:BB:CC:DD:EE:FF", + client_key_path=key_file, + mcp_bearer_token="test-bearer-token", + enable_raw_ssap=enable_raw_ssap, + max_volume=max_volume, + ) + + +def _online_transport( + sent_requests: list[tuple[str, dict[str, Any]]], + replies: dict[str, dict[str, Any]] | None = None, +) -> FakeWebSocketTransport: + replies = replies or {} + + def on_send(raw: str, ws: FakeWebSocketTransport) -> None: + msg: dict[str, Any] = json.loads(raw) + msg_type = msg.get("type") + msg_id = msg.get("id") + if msg_type == "register": + ws.push_json( + {"type": "registered", "id": msg_id, "payload": {"client-key": "saved-key"}} + ) + return + if msg_type == "subscribe": + ws.push_json({"type": "response", "id": msg_id, "payload": {"subscribed": True}}) + return + if msg_type == "request": + uri = str(msg.get("uri", "")) + if uri == "ssap://com.webos.service.networkinput/getPointerInputSocket": + ws.push_json( + { + "type": "response", + "id": msg_id, + "payload": { + "returnValue": True, + "socketPath": "ws://192.0.2.10:3000/pointer", + }, + } + ) + return + payload_in = dict(msg.get("payload") or {}) + sent_requests.append((uri, payload_in)) + reply_payload = {"returnValue": True, **replies.get(uri, {})} + ws.push_json({"type": "response", "id": msg_id, "payload": reply_payload}) + + return FakeWebSocketTransport(on_send=on_send) + + +async def _wait_connected(mgr: TvManager) -> None: + async def _poll() -> None: + while mgr.state != ConnectionState.CONNECTED: + await asyncio.sleep(0) + + await asyncio.wait_for(_poll(), timeout=2.0) + + +@asynccontextmanager +async def _started_manager( + tmp_path: Path, + *, + enable_raw_ssap: bool = False, + max_volume: int = 30, + capturer: _FakeCapturer | None = None, + replies: dict[str, dict[str, Any]] | None = None, +) -> AsyncGenerator[tuple[TvConfig, TvManager, list[tuple[str, dict[str, Any]]]]]: + sent_requests: list[tuple[str, dict[str, Any]]] = [] + pointer_ws = FakeWebSocketTransport() + + async def connect_fn(url: str) -> FakeWebSocketTransport: + if url.endswith("/pointer"): + return pointer_ws + return _online_transport(sent_requests, replies) + + config = _make_config( + tmp_path, + enable_raw_ssap=enable_raw_ssap, + max_volume=max_volume, + ) + mgr = TvManager( + config, + connect_fn=connect_fn, + capture_client=capturer, + backoff_steps=(10.0,), + ) + await mgr.start() + try: + await _wait_connected(mgr) + yield config, mgr, sent_requests + finally: + await mgr.close() + + +async def test_server_registers_12_default_tools_and_gates_raw_ssap(tmp_path: Path) -> None: + expected_default = { + "tv_wake", + "get_state", + "keys", + "type_text", + "screenshot", + "launch", + "list_apps", + "set_volume", + "set_mute", + "list_inputs", + "switch_input", + "turn_off", + } + + server_off = create_mcp_server(_make_config(tmp_path, enable_raw_ssap=False)) + names_off = {tool.name for tool in await server_off.list_tools()} + assert names_off == expected_default + assert "raw_ssap" not in names_off + + server_on = create_mcp_server(_make_config(tmp_path, enable_raw_ssap=True)) + names_on = {tool.name for tool in await server_on.list_tools()} + assert names_on == expected_default | {"raw_ssap"} + + +async def test_server_maps_tv_error_to_tool_error_code_and_message(tmp_path: Path) -> None: + async def standby_connect(_url: str) -> FakeWebSocketTransport: + raise TvError(ErrorCode.TV_OFFLINE_STANDBY, "TV is in standby") + + config = _make_config(tmp_path) + mgr = TvManager(config, connect_fn=standby_connect, backoff_steps=(10.0,)) + await mgr.start() + try: + server = create_mcp_server(config, manager=mgr) + with pytest.raises(ToolError, match=r"TV_OFFLINE_STANDBY: "): + await server.call_tool("turn_off", {}) + finally: + await mgr.close() + + +async def test_server_launch_merges_content_target_and_omits_empty_params( + tmp_path: Path, +) -> None: + async with _started_manager(tmp_path) as (config, mgr, sent_requests): + server = create_mcp_server(config, manager=mgr) + await server.call_tool("launch", {"app_id": "youtube.leanback.v4"}) + await server.call_tool( + "launch", + { + "app_id": "youtube.leanback.v4", + "content_target": "v=abc123", + "params": {"contentTarget": "old", "extra": 1}, + }, + ) + + launch_calls = [ + payload for uri, payload in sent_requests if uri == "ssap://system.launcher/launch" + ] + assert launch_calls == [ + {"id": "youtube.leanback.v4"}, + {"id": "youtube.leanback.v4", "params": {"contentTarget": "v=abc123", "extra": 1}}, + ] + + +@pytest.mark.parametrize( + ("level", "should_succeed"), + [(-1, False), (0, True), (30, True), (31, False)], +) +async def test_server_set_volume_enforces_max_volume_bounds( + tmp_path: Path, + level: int, + should_succeed: bool, +) -> None: + async with _started_manager(tmp_path, max_volume=30) as (config, mgr, sent_requests): + server = create_mcp_server(config, manager=mgr) + if should_succeed: + await server.call_tool("set_volume", {"level": level}) + assert ("ssap://audio/setVolume", {"volume": level}) in sent_requests + else: + with pytest.raises(ToolError, match=r"INVALID_ARGUMENT: "): + await server.call_tool("set_volume", {"level": level}) + assert not any(uri == "ssap://audio/setVolume" for uri, _ in sent_requests) + + +@pytest.mark.parametrize( + ("text", "should_succeed"), + [("", False), ("a", True), ("x" * 500, True), ("x" * 501, False)], +) +async def test_server_type_text_validates_length_bounds( + tmp_path: Path, + text: str, + should_succeed: bool, +) -> None: + async with _started_manager(tmp_path) as (config, mgr, sent_requests): + server = create_mcp_server(config, manager=mgr) + if should_succeed: + await server.call_tool("type_text", {"text": text, "send_enter": False}) + assert ( + "ssap://com.webos.service.ime/insertText", + {"text": text, "replace": 0}, + ) in sent_requests + else: + with pytest.raises(ToolError, match=r"INVALID_ARGUMENT: "): + await server.call_tool("type_text", {"text": text, "send_enter": False}) + + +async def test_server_screenshot_returns_text_and_image_content(tmp_path: Path) -> None: + capturer = _FakeCapturer() + async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _): + server = create_mcp_server(config, manager=mgr) + shot_res = await server.call_tool("screenshot", {}) + + assert isinstance(shot_res, CallToolResult) + assert len(shot_res.content) == 2 + text_block, image_block = shot_res.content[0], shot_res.content[1] + assert isinstance(text_block, TextContent) + assert isinstance(image_block, ImageContent) + shot_meta = json.loads(text_block.text) + assert shot_meta["frame_sha256"] == _TEST_SHA256 + assert shot_meta["size_bytes"] == len(_TEST_JPEG) + assert image_block.mime_type == "image/jpeg" + assert base64.b64decode(image_block.data) == _TEST_JPEG + + +async def test_server_keys_capture_returns_text_and_image_content(tmp_path: Path) -> None: + capturer = _FakeCapturer() + async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _): + server = create_mcp_server(config, manager=mgr) + keys_res = await server.call_tool( + "keys", + {"keys": ["UP"], "delay_ms": 0, "settle_ms": 0, "capture": True}, + ) + + assert isinstance(keys_res, CallToolResult) + assert len(keys_res.content) == 2 + text_block, image_block = keys_res.content[0], keys_res.content[1] + assert isinstance(text_block, TextContent) + assert isinstance(image_block, ImageContent) + keys_meta = json.loads(text_block.text) + assert keys_meta["keys_sent"] is True + assert keys_meta["count"] == 1 + assert base64.b64decode(image_block.data) == _TEST_JPEG + + +async def test_server_type_text_capture_returns_text_and_image_content(tmp_path: Path) -> None: + capturer = _FakeCapturer() + async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _): + server = create_mcp_server(config, manager=mgr) + text_res = await server.call_tool( + "type_text", + {"text": "hi", "send_enter": False, "capture": True}, + ) + + assert isinstance(text_res, CallToolResult) + assert len(text_res.content) == 2 + text_block, image_block = text_res.content[0], text_res.content[1] + assert isinstance(text_block, TextContent) + assert isinstance(image_block, ImageContent) + assert base64.b64decode(image_block.data) == _TEST_JPEG + + +async def test_server_keys_capture_returns_text_only_on_capture_error(tmp_path: Path) -> None: + capturer = _FakeCapturer(error=TvError(ErrorCode.SCREENSHOT_UNAVAILABLE, "Dev Mode expired")) + async with _started_manager(tmp_path, capturer=capturer) as (config, mgr, _): + server = create_mcp_server(config, manager=mgr) + res = await server.call_tool( + "keys", + {"keys": ["ENTER"], "delay_ms": 0, "settle_ms": 0, "capture": True}, + ) + + assert isinstance(res, CallToolResult) + assert len(res.content) == 1 + text_block = res.content[0] + assert isinstance(text_block, TextContent) + meta = json.loads(text_block.text) + assert meta["keys_sent"] is True + assert meta["capture_error"] == "SCREENSHOT_UNAVAILABLE: Dev Mode expired" + + +async def test_server_http_app_rejects_unauthenticated_mcp_request_with_401(tmp_path: Path) -> None: + config = _make_config(tmp_path) + mgr = TvManager(config, backoff_steps=(10.0,)) + app = create_http_app(config, manager=mgr) + + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1:8765") as client: + unauth = await client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "initialize"}) + + assert unauth.status_code == 401 + + +async def test_server_http_app_lifespan_starts_and_closes_manager_with_sighup( + tmp_path: Path, +) -> None: + sent_requests: list[tuple[str, dict[str, Any]]] = [] + pointer_ws = FakeWebSocketTransport() + ssap_ws = _online_transport(sent_requests) + + async def connect_fn(url: str) -> FakeWebSocketTransport: + if url.endswith("/pointer"): + return pointer_ws + return ssap_ws + + config = _make_config(tmp_path) + mgr = TvManager(config, connect_fn=connect_fn, backoff_steps=(10.0,)) + app = create_http_app(config, manager=mgr) + + incoming: list[MutableMapping[str, Any]] = [ + {"type": "lifespan.startup"}, + {"type": "lifespan.shutdown"}, + ] + outgoing: list[MutableMapping[str, Any]] = [] + startup_done = asyncio.Event() + allow_shutdown = asyncio.Event() + + async def receive() -> MutableMapping[str, Any]: + if incoming[0]["type"] == "lifespan.shutdown": + await allow_shutdown.wait() + return incoming.pop(0) + + async def send(msg: MutableMapping[str, Any]) -> None: + outgoing.append(msg) + if msg["type"] == "lifespan.startup.complete": + startup_done.set() + + async def _run_lifespan() -> None: + await app({"type": "lifespan"}, receive, send) + + lifespan_task: asyncio.Task[None] = asyncio.create_task(_run_lifespan()) + try: + await asyncio.wait_for(startup_done.wait(), timeout=2.0) + await _wait_connected(mgr) + loop = asyncio.get_running_loop() + assert loop.remove_signal_handler(signal.SIGHUP) is True + finally: + allow_shutdown.set() + await asyncio.wait_for(lifespan_task, timeout=2.0) + + assert [m["type"] for m in outgoing] == [ + "lifespan.startup.complete", + "lifespan.shutdown.complete", + ] + assert ssap_ws.closed is True + + +async def test_server_http_app_allows_authenticated_mcp_initialize_request( + tmp_path: Path, +) -> None: + sent_requests: list[tuple[str, dict[str, Any]]] = [] + ssap_ws = _online_transport(sent_requests) + + async def connect_fn(_url: str) -> FakeWebSocketTransport: + return ssap_ws + + config = _make_config(tmp_path) + mgr = TvManager(config, connect_fn=connect_fn, backoff_steps=(10.0,)) + app = create_http_app(config, manager=mgr) + + incoming: list[MutableMapping[str, Any]] = [ + {"type": "lifespan.startup"}, + {"type": "lifespan.shutdown"}, + ] + startup_done = asyncio.Event() + allow_shutdown = asyncio.Event() + + async def receive() -> MutableMapping[str, Any]: + if incoming[0]["type"] == "lifespan.shutdown": + await allow_shutdown.wait() + return incoming.pop(0) + + async def send(msg: MutableMapping[str, Any]) -> None: + if msg["type"] == "lifespan.startup.complete": + startup_done.set() + + async def _run_lifespan() -> None: + await app({"type": "lifespan"}, receive, send) + + lifespan_task: asyncio.Task[None] = asyncio.create_task(_run_lifespan()) + try: + await asyncio.wait_for(startup_done.wait(), timeout=2.0) + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient( + transport=transport, base_url="http://127.0.0.1:8765" + ) as client: + resp = await client.post( + "/mcp", + headers={ + "Authorization": "Bearer test-bearer-token", + "Accept": "application/json, text/event-stream", + }, + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-03-26", + "capabilities": {}, + "clientInfo": {"name": "test-client", "version": "0.1.0"}, + }, + }, + ) + assert resp.status_code == 200 + assert "lg-smtv-mcp" in resp.text + finally: + allow_shutdown.set() + await asyncio.wait_for(lifespan_task, timeout=2.0) diff --git a/tests/test_ssap.py b/tests/test_ssap.py index 357999f..02f4774 100644 --- a/tests/test_ssap.py +++ b/tests/test_ssap.py @@ -6,7 +6,7 @@ import pytest from lg_smtv_mcp.errors import ErrorCode, TvError from lg_smtv_mcp.tv_core.protocols import WebSocketClosedError -from lg_smtv_mcp.tv_core.ssap import PERMISSIONS, SsapClient +from lg_smtv_mcp.tv_core.ssap import SsapClient from tests.conftest import FakeWebSocketTransport @@ -35,8 +35,25 @@ async def test_ssap_register_sends_all_permissions_even_with_saved_client_key() reg_msg = json.loads(transport.sent[0]) assert reg_msg["type"] == "register" assert reg_msg["payload"]["client-key"] == "saved-key-123" - assert len(PERMISSIONS) == 16 - assert reg_msg["payload"]["manifest"]["permissions"] == list(PERMISSIONS) + expected_permissions = [ + "LAUNCH", + "CONTROL_AUDIO", + "CONTROL_DISPLAY", + "CONTROL_POWER", + "CONTROL_INPUT_TEXT", + "CONTROL_INPUT_MEDIA_PLAYBACK", + "CONTROL_INPUT_JOYSTICK", + "CONTROL_INPUT_TV", + "CONTROL_TV_MEDIA", + "CONTROL_MOUSE_AND_KEYBOARD", + "READ_INSTALLED_APPS", + "READ_RUNNING_APPS", + "READ_INPUT_DEVICE_LIST", + "READ_TV_CHANNEL_LIST", + "READ_POWER_STATE", + "WRITE_NOTIFICATION_TOAST", + ] + assert reg_msg["payload"]["manifest"]["permissions"] == expected_permissions async def test_ssap_request_demuxes_interleaved_subscribe_push_frame() -> None: