mirror of
https://github.com/deunix-educ/mediadeck.git
synced 2026-11-25 04:39:42 +01:00
Initial commit: MediaDeck web remote for a Linux media PC
Python bridge (aiohttp, single asyncio loop) between a tablet browser and a Linux media PC: MPRIS players, PipeWire audio (pactl), virtual keyboard and touchpad (uinput), power and session control (logind). - Tablet UI with player, audio, touchpad, launchers and system tabs (fr/en) - Launchers stored in SQLite and managed from /admin; raw commands are opt-in (admin.allow_custom_command) - Optional text entry, translated to key presses from the PC's real keyboard layout with libxkbcommon and never through the clipboard (features.text_input, off by default) - Local HTTPS with a private CA restricted by name constraints (make cert) - Token-protected WebSocket and REST API, strict CSP, no JS dependencies Checked: pyright 0 errors, 87 unit tests, browser tests in headless Chromium. Not yet exercised on the real tablet, nor with real uinput key presses. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,167 @@
|
||||
"""Tests de l'API REST d'administration des lanceurs (sans D-Bus : seules les routes /api sont montées)."""
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
from mediadeck.admin import AdminApi
|
||||
from mediadeck.config import parse_config
|
||||
from mediadeck.launchers import LauncherStore
|
||||
|
||||
TOKEN = "t" * 32
|
||||
AUTH = {"Authorization": f"Bearer {TOKEN}"}
|
||||
WEB = {"label": "Arte", "icon": "tv", "kind": "web", "spec": {"url": "https://www.arte.tv/fr/", "browser": "chromium"}}
|
||||
COMMAND = {"label": "Off", "icon": "screen-off", "kind": "command", "spec": {"argv": ["kscreen-doctor", "--dpms", "off"]}}
|
||||
|
||||
|
||||
class AdminApiCase(unittest.IsolatedAsyncioTestCase):
|
||||
"""Serveur de test sans commande brute autorisée ; les sous-classes ajoutent les tests."""
|
||||
|
||||
allow_command = False
|
||||
|
||||
async def asyncSetUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.store = LauncherStore(Path(self._tmp.name) / "launchers.db")
|
||||
self.changes = 0
|
||||
config = parse_config(
|
||||
{"server": {"token": TOKEN}, "admin": {"allow_custom_command": self.allow_command}}
|
||||
)
|
||||
app = web.Application()
|
||||
AdminApi(config, self.store, self._on_change).add_routes(app)
|
||||
self.client = TestClient(TestServer(app))
|
||||
await self.client.start_server()
|
||||
|
||||
async def asyncTearDown(self) -> None:
|
||||
await self.client.close()
|
||||
self.store.close()
|
||||
self._tmp.cleanup()
|
||||
|
||||
def _on_change(self) -> None:
|
||||
self.changes += 1
|
||||
|
||||
|
||||
class AdminApiTest(AdminApiCase):
|
||||
async def test_token_required_on_every_route(self) -> None:
|
||||
calls = [
|
||||
("GET", "/api/launchers"), ("POST", "/api/launchers"), ("PUT", "/api/launchers/x"),
|
||||
("DELETE", "/api/launchers/x"), ("POST", "/api/launchers/reorder"), ("GET", "/api/apps"),
|
||||
]
|
||||
wrong = {"Authorization": "Bearer nope"}
|
||||
for method, path in calls:
|
||||
for headers in ({}, wrong, {"Authorization": TOKEN}, {"Authorization": f"Basic {TOKEN}"}):
|
||||
with self.subTest(method=method, path=path, headers=headers):
|
||||
response = await self.client.request(method, path, headers=headers, json=WEB)
|
||||
self.assertEqual(response.status, 401)
|
||||
# Le jeton en paramètre d'URL n'est pas accepté : il finirait dans les journaux et l'historique
|
||||
response = await self.client.get(f"/api/launchers?token={TOKEN}")
|
||||
self.assertEqual(response.status, 401)
|
||||
|
||||
async def test_list_exposes_options(self) -> None:
|
||||
response = await self.client.get("/api/launchers", headers=AUTH)
|
||||
data = await response.json()
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(data["launchers"], [])
|
||||
self.assertIn("tv", data["icons"])
|
||||
self.assertFalse(data["allow_command"])
|
||||
self.assertEqual({browser["id"] for browser in data["browsers"]}, {"chromium", "chrome", "brave", "firefox"})
|
||||
|
||||
async def test_crud_cycle(self) -> None:
|
||||
created = await self.client.post("/api/launchers", headers=AUTH, json=WEB)
|
||||
self.assertEqual(created.status, 201)
|
||||
entry = await created.json()
|
||||
self.assertEqual(entry["id"], "arte")
|
||||
self.assertEqual(entry["spec"]["fullscreen"], False)
|
||||
|
||||
updated = await self.client.put("/api/launchers/arte", headers=AUTH, json={**WEB, "label": "Arte TV"})
|
||||
self.assertEqual(updated.status, 200)
|
||||
self.assertEqual((await updated.json())["label"], "Arte TV")
|
||||
|
||||
second = await self.client.post("/api/launchers", headers=AUTH, json={**WEB, "label": "Autre"})
|
||||
self.assertEqual(second.status, 201)
|
||||
reorder = await self.client.post("/api/launchers/reorder", headers=AUTH, json={"ids": ["autre", "arte"]})
|
||||
self.assertEqual(reorder.status, 204)
|
||||
listing = await (await self.client.get("/api/launchers", headers=AUTH)).json()
|
||||
self.assertEqual([item["id"] for item in listing["launchers"]], ["autre", "arte"])
|
||||
|
||||
deleted = await self.client.delete("/api/launchers/arte", headers=AUTH)
|
||||
self.assertEqual(deleted.status, 204)
|
||||
self.assertEqual((await self.client.delete("/api/launchers/arte", headers=AUTH)).status, 404)
|
||||
self.assertEqual((await self.client.put("/api/launchers/arte", headers=AUTH, json=WEB)).status, 404)
|
||||
# create + update + create + reorder + delete : chaque modification notifie les tablettes
|
||||
self.assertEqual(self.changes, 5)
|
||||
|
||||
async def test_validation_errors_do_not_change_anything(self) -> None:
|
||||
bad = {**WEB, "spec": {**WEB["spec"], "url": "javascript:alert(1)"}}
|
||||
response = await self.client.post("/api/launchers", headers=AUTH, json=bad)
|
||||
self.assertEqual(response.status, 400)
|
||||
self.assertIn("error", await response.json())
|
||||
invalid_json = await self.client.post("/api/launchers", headers=AUTH, data=b"{nope")
|
||||
self.assertEqual(invalid_json.status, 400)
|
||||
too_large = await self.client.post("/api/launchers", headers=AUTH, data=b" " * 20000)
|
||||
self.assertEqual(too_large.status, 400)
|
||||
bad_order = await self.client.post("/api/launchers/reorder", headers=AUTH, json={"ids": ["x"]})
|
||||
self.assertEqual(bad_order.status, 400)
|
||||
self.assertEqual(self.store.list(), [])
|
||||
self.assertEqual(self.changes, 0)
|
||||
|
||||
async def test_raw_commands_are_forbidden_by_default(self) -> None:
|
||||
response = await self.client.post("/api/launchers", headers=AUTH, json=COMMAND)
|
||||
self.assertEqual(response.status, 403)
|
||||
self.assertEqual(self.store.list(), [])
|
||||
|
||||
async def test_imported_command_can_be_renamed_but_not_rewritten(self) -> None:
|
||||
entry = self.store.create("Off", "screen-off", "command", COMMAND["spec"])
|
||||
renamed = await self.client.put(f"/api/launchers/{entry.id}", headers=AUTH, json={**COMMAND, "label": "Écran off"})
|
||||
self.assertEqual(renamed.status, 200)
|
||||
rewritten = await self.client.put(
|
||||
f"/api/launchers/{entry.id}", headers=AUTH, json={**COMMAND, "spec": {"argv": ["reboot"]}}
|
||||
)
|
||||
self.assertEqual(rewritten.status, 403)
|
||||
stored = self.store.get(entry.id)
|
||||
assert stored is not None
|
||||
self.assertEqual(stored.spec, COMMAND["spec"])
|
||||
|
||||
async def test_apps_listing_and_app_launcher(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
(Path(tmp) / "vlc.desktop").write_text("[Desktop Entry]\nType=Application\nName=VLC\nExec=vlc\n")
|
||||
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp)]):
|
||||
apps = await (await self.client.get("/api/apps", headers=AUTH)).json()
|
||||
self.assertEqual(apps, [{"id": "vlc.desktop", "name": "VLC"}])
|
||||
ok = await self.client.post(
|
||||
"/api/launchers", headers=AUTH,
|
||||
json={"label": "VLC", "icon": "film", "kind": "app", "spec": {"desktop_id": "vlc.desktop"}},
|
||||
)
|
||||
self.assertEqual(ok.status, 201)
|
||||
unknown = await self.client.post(
|
||||
"/api/launchers", headers=AUTH,
|
||||
json={"label": "X", "icon": "app", "kind": "app", "spec": {"desktop_id": "../../x.desktop"}},
|
||||
)
|
||||
self.assertEqual(unknown.status, 400)
|
||||
|
||||
|
||||
class AdminApiCommandAllowedTest(AdminApiCase):
|
||||
allow_command = True
|
||||
|
||||
async def test_list_announces_raw_commands(self) -> None:
|
||||
data = await (await self.client.get("/api/launchers", headers=AUTH)).json()
|
||||
self.assertTrue(data["allow_command"])
|
||||
|
||||
async def test_raw_commands_are_accepted(self) -> None:
|
||||
response = await self.client.post("/api/launchers", headers=AUTH, json=COMMAND)
|
||||
self.assertEqual(response.status, 201)
|
||||
self.assertEqual((await response.json())["spec"], COMMAND["spec"])
|
||||
|
||||
async def test_command_can_be_rewritten(self) -> None:
|
||||
entry = self.store.create("Off", "screen-off", "command", COMMAND["spec"])
|
||||
rewritten = await self.client.put(
|
||||
f"/api/launchers/{entry.id}", headers=AUTH, json={**COMMAND, "spec": {"argv": ["reboot"]}}
|
||||
)
|
||||
self.assertEqual(rewritten.status, 200)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Tests de validation de la configuration."""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from mediadeck.config import ConfigError, load_config, parse_config
|
||||
|
||||
TOKEN = "x" * 32
|
||||
|
||||
|
||||
class ParseConfigTest(unittest.TestCase):
|
||||
def test_defaults(self) -> None:
|
||||
config = parse_config({"server": {"token": TOKEN}})
|
||||
self.assertEqual(config.port, 8765)
|
||||
self.assertEqual(config.max_volume, 1.0)
|
||||
self.assertTrue(config.enable_input)
|
||||
self.assertEqual(config.launchers, ())
|
||||
|
||||
def test_short_token_rejected(self) -> None:
|
||||
with self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": "short"}})
|
||||
|
||||
def test_launcher_command_must_be_argv(self) -> None:
|
||||
# Une chaîne seule serait tentante à passer à un shell : refusée
|
||||
with self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN}, "launchers": [{"id": "a", "label": "A", "command": "vlc"}]})
|
||||
|
||||
def test_duplicate_launcher_id(self) -> None:
|
||||
launcher = {"id": "vlc", "label": "VLC", "command": ["vlc"]}
|
||||
with self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN}, "launchers": [launcher, launcher]})
|
||||
|
||||
def test_advertise_host(self) -> None:
|
||||
self.assertEqual(parse_config({"server": {"token": TOKEN}}).advertise_host, "")
|
||||
config = parse_config({"server": {"token": TOKEN, "advertise_host": "192.168.1.104"}})
|
||||
self.assertEqual(config.advertise_host, "192.168.1.104")
|
||||
self.assertEqual(
|
||||
parse_config({"server": {"token": TOKEN, "advertise_host": "mediapc.local"}}).advertise_host,
|
||||
"mediapc.local",
|
||||
)
|
||||
|
||||
def test_advertise_host_rejects_url_syntax(self) -> None:
|
||||
# La valeur est insérée telle quelle dans l'URL : pas de schéma, port, chemin ni espace
|
||||
for value in ("http://192.168.1.104", "192.168.1.104:8765", "host/path", "a b", "x@y", 42):
|
||||
with self.subTest(value=value), self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN, "advertise_host": value}})
|
||||
|
||||
def test_tls_paths(self) -> None:
|
||||
config = parse_config({"server": {"token": TOKEN, "tls_cert": "~/c.pem", "tls_key": "/k.key"}})
|
||||
self.assertTrue(config.tls_enabled)
|
||||
self.assertEqual(config.tls_cert, Path.home() / "c.pem")
|
||||
self.assertIsNone(config.tls_ca)
|
||||
self.assertFalse(parse_config({"server": {"token": TOKEN}}).tls_enabled)
|
||||
|
||||
def test_tls_options_are_consistent(self) -> None:
|
||||
for server in (
|
||||
{"tls_cert": "/c.pem"}, # clé manquante
|
||||
{"tls_key": "/k.key"}, # certificat manquant
|
||||
{"tls_ca": "/ca.crt"}, # CA sans certificat
|
||||
{"tls_cert": 1, "tls_key": "/k.key"},
|
||||
):
|
||||
with self.subTest(server=server), self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN, **server}})
|
||||
|
||||
def test_max_volume_bounds(self) -> None:
|
||||
with self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN}, "audio": {"max_volume": 3}})
|
||||
|
||||
|
||||
class LoadConfigTest(unittest.TestCase):
|
||||
def test_world_readable_file_rejected(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "config.toml"
|
||||
path.write_text(f'[server]\ntoken = "{TOKEN}"\n')
|
||||
os.chmod(path, 0o644)
|
||||
with self.assertRaises(ConfigError):
|
||||
load_config(path)
|
||||
os.chmod(path, 0o600)
|
||||
self.assertEqual(load_config(path).token, TOKEN)
|
||||
|
||||
def test_example_config_is_valid(self) -> None:
|
||||
example = Path(__file__).resolve().parent.parent / "config.example.toml"
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "config.toml"
|
||||
path.write_text(example.read_text().replace("CHANGE_ME", TOKEN))
|
||||
os.chmod(path, 0o600)
|
||||
config = load_config(path)
|
||||
self.assertGreater(len(config.launchers), 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Tests des lanceurs : stockage SQLite, validation, construction de la commande, applications .desktop."""
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from mediadeck import launchers
|
||||
from mediadeck.config import Launcher as ConfigLauncher
|
||||
from mediadeck.launchers import (
|
||||
CommandNotAllowed,
|
||||
LauncherEntry,
|
||||
LauncherError,
|
||||
LauncherNotFound,
|
||||
LauncherStore,
|
||||
build_argv,
|
||||
validate,
|
||||
)
|
||||
|
||||
WEB = {"label": "Arte", "icon": "tv", "kind": "web", "spec": {"url": "https://www.arte.tv/fr/", "browser": "chromium"}}
|
||||
COMMAND = {"label": "Off", "icon": "screen-off", "kind": "command", "spec": {"argv": ["kscreen-doctor", "--dpms", "off"]}}
|
||||
|
||||
DESKTOP = """[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Lecteur {name}
|
||||
Exec={name} %U
|
||||
{extra}
|
||||
"""
|
||||
|
||||
|
||||
def write_desktop(directory: Path, filename: str, name: str, extra: str = "") -> None:
|
||||
(directory / filename).write_text(DESKTOP.format(name=name, extra=extra))
|
||||
|
||||
|
||||
class StoreTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.path = Path(self._tmp.name) / "data" / "launchers.db"
|
||||
self.store = LauncherStore(self.path)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.store.close()
|
||||
self._tmp.cleanup()
|
||||
|
||||
def test_private_permissions(self) -> None:
|
||||
self.assertEqual(self.path.stat().st_mode & 0o077, 0)
|
||||
self.assertEqual(self.path.parent.stat().st_mode & 0o077, 0)
|
||||
|
||||
def test_create_generates_unique_slugs_and_keeps_order(self) -> None:
|
||||
first = self.store.create("Écran off", "app", "command", {"argv": ["a"]})
|
||||
second = self.store.create("Écran off", "app", "command", {"argv": ["b"]})
|
||||
self.assertEqual((first.id, second.id), ("ecran-off", "ecran-off-2"))
|
||||
self.assertEqual([entry.id for entry in self.store.list()], ["ecran-off", "ecran-off-2"])
|
||||
|
||||
def test_update_and_delete(self) -> None:
|
||||
entry = self.store.create("Arte", "tv", "web", WEB["spec"])
|
||||
self.store.update(entry.id, "Arte TV", "film", "web", WEB["spec"])
|
||||
updated = self.store.get(entry.id)
|
||||
assert updated is not None
|
||||
self.assertEqual((updated.label, updated.icon), ("Arte TV", "film"))
|
||||
self.store.delete(entry.id)
|
||||
self.assertIsNone(self.store.get(entry.id))
|
||||
with self.assertRaises(LauncherNotFound):
|
||||
self.store.delete(entry.id)
|
||||
with self.assertRaises(LauncherNotFound):
|
||||
self.store.update("absent", "x", "app", "command", {"argv": ["x"]})
|
||||
|
||||
def test_reorder_requires_every_id(self) -> None:
|
||||
ids = [self.store.create(name, "app", "command", {"argv": [name]}).id for name in ("a", "b", "c")]
|
||||
self.store.reorder(["c", "a", "b"])
|
||||
self.assertEqual([entry.id for entry in self.store.list()], ["c", "a", "b"])
|
||||
for bad in (ids[:2], [*ids, "d"], ["a", "a", "b"]):
|
||||
with self.subTest(ids=bad), self.assertRaises(LauncherError):
|
||||
self.store.reorder(bad)
|
||||
|
||||
def test_data_survives_reopening(self) -> None:
|
||||
self.store.create("Arte", "tv", "web", WEB["spec"])
|
||||
self.store.close()
|
||||
self.store = LauncherStore(self.path)
|
||||
self.assertEqual([entry.label for entry in self.store.list()], ["Arte"])
|
||||
|
||||
def test_seed_imports_config_launchers_once(self) -> None:
|
||||
config_launchers = [
|
||||
ConfigLauncher("vlc", "VLC", ("vlc",), "film"),
|
||||
ConfigLauncher("odd", "Odd", ("odd", "--x"), "inconnue"),
|
||||
]
|
||||
self.assertEqual(self.store.seed(config_launchers), 2)
|
||||
self.assertEqual(self.store.seed(config_launchers), 0)
|
||||
entries = self.store.list()
|
||||
self.assertEqual([entry.id for entry in entries], ["vlc", "odd"])
|
||||
self.assertEqual(entries[0].kind, "command")
|
||||
self.assertEqual(entries[1].spec, {"argv": ["odd", "--x"]})
|
||||
self.assertEqual(entries[1].icon, "app")
|
||||
# Une fois importés, les lanceurs supprimés ne reviennent pas au redémarrage
|
||||
self.store.delete("vlc")
|
||||
self.store.close()
|
||||
self.store = LauncherStore(self.path)
|
||||
self.assertEqual(self.store.seed(config_launchers), 0)
|
||||
self.assertEqual([entry.id for entry in self.store.list()], ["odd"])
|
||||
|
||||
def test_limit(self) -> None:
|
||||
for index in range(launchers.MAX_LAUNCHERS):
|
||||
self.store.create(f"l{index}", "app", "command", {"argv": ["x"]})
|
||||
with self.assertRaises(LauncherError):
|
||||
self.store.create("one more", "app", "command", {"argv": ["x"]})
|
||||
|
||||
|
||||
class ValidateTest(unittest.TestCase):
|
||||
def test_valid_web(self) -> None:
|
||||
label, icon, kind, spec = validate(WEB, allow_command=False)
|
||||
self.assertEqual((label, icon, kind), ("Arte", "tv", "web"))
|
||||
self.assertEqual(spec, {"url": "https://www.arte.tv/fr/", "browser": "chromium", "fullscreen": False})
|
||||
|
||||
def test_fullscreen_dropped_for_firefox(self) -> None:
|
||||
data = {**WEB, "spec": {**WEB["spec"], "browser": "firefox", "fullscreen": True}}
|
||||
self.assertFalse(validate(data, allow_command=False)[3]["fullscreen"])
|
||||
|
||||
def test_rejected_urls(self) -> None:
|
||||
for url in ("javascript:alert(1)", "file:///etc/passwd", "http://", "https://a b.example", "--kiosk", "", " ",
|
||||
"https://x/\n--evil", 5):
|
||||
with self.subTest(url=url), self.assertRaises(LauncherError):
|
||||
validate({**WEB, "spec": {**WEB["spec"], "url": url}}, allow_command=False)
|
||||
|
||||
def test_rejected_fields(self) -> None:
|
||||
for patch in (
|
||||
{"label": ""}, {"label": "x" * 41}, {"label": 3}, {"icon": "nope"}, {"kind": "shell"}, {"kind": None},
|
||||
{"spec": "x"}, {"spec": {**WEB["spec"], "browser": "netscape"}}, {"spec": {**WEB["spec"], "fullscreen": "yes"}},
|
||||
):
|
||||
with self.subTest(patch=patch), self.assertRaises(LauncherError):
|
||||
validate({**WEB, **patch}, allow_command=False)
|
||||
with self.assertRaises(LauncherError):
|
||||
validate([], allow_command=False)
|
||||
|
||||
def test_command_forbidden_by_default(self) -> None:
|
||||
with self.assertRaises(CommandNotAllowed):
|
||||
validate(COMMAND, allow_command=False)
|
||||
self.assertEqual(validate(COMMAND, allow_command=True)[3], {"argv": ["kscreen-doctor", "--dpms", "off"]})
|
||||
|
||||
def test_command_argv_rules(self) -> None:
|
||||
for argv in ([], "vlc", [""], ["a", 3], ["a\0b"], ["x"] * 33):
|
||||
with self.subTest(argv=argv), self.assertRaises(LauncherError):
|
||||
validate({**COMMAND, "spec": {"argv": argv}}, allow_command=True)
|
||||
|
||||
def test_existing_command_can_be_renamed_but_not_changed(self) -> None:
|
||||
current = LauncherEntry("off", "Off", "app", "command", COMMAND["spec"])
|
||||
renamed = validate({**COMMAND, "label": "Écran éteint"}, allow_command=False, current=current)
|
||||
self.assertEqual(renamed[0], "Écran éteint")
|
||||
with self.assertRaises(CommandNotAllowed):
|
||||
validate({**COMMAND, "spec": {"argv": ["rm", "-rf", "~"]}}, allow_command=False, current=current)
|
||||
# Convertir un lanceur web en commande brute reste une création de commande
|
||||
web = LauncherEntry("w", "W", "tv", "web", WEB["spec"])
|
||||
with self.assertRaises(CommandNotAllowed):
|
||||
validate(COMMAND, allow_command=False, current=web)
|
||||
|
||||
|
||||
class BuildArgvTest(unittest.TestCase):
|
||||
def test_web_argv(self) -> None:
|
||||
spec = {"url": "https://www.arte.tv/fr/", "browser": "chromium", "fullscreen": True}
|
||||
entry = LauncherEntry("arte", "Arte", "tv", "web", spec)
|
||||
with mock.patch("mediadeck.launchers.shutil.which", return_value="/usr/bin/chromium"):
|
||||
self.assertEqual(build_argv(entry), ["chromium", "--start-fullscreen", "https://www.arte.tv/fr/"])
|
||||
windowed = LauncherEntry("arte", "Arte", "tv", "web", {**spec, "fullscreen": False})
|
||||
self.assertEqual(build_argv(windowed), ["chromium", "https://www.arte.tv/fr/"])
|
||||
firefox = LauncherEntry("arte", "Arte", "tv", "web", {**spec, "browser": "firefox"})
|
||||
self.assertEqual(build_argv(firefox), ["firefox", "--new-window", "https://www.arte.tv/fr/"])
|
||||
|
||||
def test_web_browser_not_installed(self) -> None:
|
||||
entry = LauncherEntry("arte", "Arte", "tv", "web", WEB["spec"])
|
||||
with mock.patch("mediadeck.launchers.shutil.which", return_value=None), self.assertRaises(LauncherError):
|
||||
build_argv(entry)
|
||||
|
||||
def test_command_argv(self) -> None:
|
||||
entry = LauncherEntry("off", "Off", "app", "command", COMMAND["spec"])
|
||||
self.assertEqual(build_argv(entry), ["kscreen-doctor", "--dpms", "off"])
|
||||
|
||||
def test_app_argv_uses_gio_and_the_resolved_path(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
write_desktop(Path(tmp), "vlc.desktop", "vlc")
|
||||
entry = LauncherEntry("vlc", "VLC", "film", "app", {"desktop_id": "vlc.desktop"})
|
||||
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp)]), \
|
||||
mock.patch("mediadeck.launchers.shutil.which", return_value="/usr/bin/gio"):
|
||||
self.assertEqual(build_argv(entry), ["gio", "launch", str(Path(tmp) / "vlc.desktop")])
|
||||
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp)]), \
|
||||
mock.patch("mediadeck.launchers.shutil.which", return_value=None), self.assertRaises(LauncherError):
|
||||
build_argv(entry)
|
||||
|
||||
|
||||
class DesktopAppsTest(unittest.TestCase):
|
||||
def test_listing_filters_and_precedence(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
|
||||
user, system = Path(first), Path(second)
|
||||
write_desktop(user, "mpv.desktop", "mpv-utilisateur")
|
||||
write_desktop(system, "mpv.desktop", "mpv-systeme")
|
||||
write_desktop(system, "zeal.desktop", "zeal")
|
||||
write_desktop(system, "hidden.desktop", "hidden", "NoDisplay=true")
|
||||
write_desktop(system, "shell.desktop", "shell", "Terminal=true")
|
||||
(system / "broken.desktop").write_text("pas un fichier desktop")
|
||||
(system / "notes.txt").write_text("[Desktop Entry]")
|
||||
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[user, system, system / "absent"]):
|
||||
apps = launchers.list_desktop_apps()
|
||||
self.assertEqual([(app.id, app.name) for app in apps],
|
||||
[("mpv.desktop", "Lecteur mpv-utilisateur"), ("zeal.desktop", "Lecteur zeal")])
|
||||
self.assertIsNone(launchers.find_desktop_entry("hidden.desktop"))
|
||||
|
||||
def test_find_desktop_entry_rejects_path_tricks(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
write_desktop(Path(tmp), "vlc.desktop", "vlc")
|
||||
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp) / "sub"]):
|
||||
for desktop_id in ("../vlc.desktop", "/etc/passwd", "vlc", "a/b.desktop", ""):
|
||||
with self.subTest(desktop_id=desktop_id):
|
||||
self.assertIsNone(launchers.find_desktop_entry(desktop_id))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Tests des conversions MPRIS et pactl, sans D-Bus ni serveur audio."""
|
||||
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from dbus_next.signature import Variant
|
||||
|
||||
from mediadeck.audio import parse_sinks
|
||||
from mediadeck.mpris import normalize_metadata, unwrap
|
||||
|
||||
|
||||
class MprisTest(unittest.TestCase):
|
||||
def test_unwrap_nested_variants(self) -> None:
|
||||
value = {"a": Variant("as", ["x", "y"]), "b": Variant("v", Variant("i", 3))}
|
||||
self.assertEqual(unwrap(value), {"a": ["x", "y"], "b": 3})
|
||||
|
||||
def test_normalize_metadata(self) -> None:
|
||||
raw = {
|
||||
"mpris:trackid": Variant("o", "/org/mpris/MediaPlayer2/Track/1"),
|
||||
"mpris:length": Variant("x", 215_000_000),
|
||||
"xesam:title": Variant("s", "Song"),
|
||||
"xesam:artist": Variant("as", ["A", "B"]),
|
||||
"xesam:comment": Variant("as", ["ignored"]),
|
||||
}
|
||||
meta = normalize_metadata(raw)
|
||||
self.assertEqual(meta["artist"], "A, B")
|
||||
self.assertEqual(meta["length"], 215_000_000)
|
||||
self.assertEqual(meta["trackid"], "/org/mpris/MediaPlayer2/Track/1")
|
||||
self.assertNotIn("comment", meta)
|
||||
|
||||
def test_missing_length_defaults_to_zero(self) -> None:
|
||||
self.assertEqual(normalize_metadata({})["length"], 0)
|
||||
|
||||
|
||||
class PactlTest(unittest.TestCase):
|
||||
def test_parse_sinks_average_volume(self) -> None:
|
||||
raw = json.dumps(
|
||||
[
|
||||
{
|
||||
"name": "alsa_output.hdmi",
|
||||
"description": "HDMI TV",
|
||||
"mute": False,
|
||||
"volume": {
|
||||
"front-left": {"value": 26214, "value_percent": "40%", "db": "-23.88 dB"},
|
||||
"front-right": {"value": 32768, "value_percent": "50%", "db": "-18.06 dB"},
|
||||
},
|
||||
},
|
||||
{"name": "bt", "description": "", "mute": True, "volume": {}},
|
||||
]
|
||||
)
|
||||
sinks = parse_sinks(raw)
|
||||
self.assertEqual(sinks[0]["volume"], 0.45)
|
||||
self.assertFalse(sinks[0]["muted"])
|
||||
# Description vide : repli sur le nom
|
||||
self.assertEqual(sinks[1]["description"], "bt")
|
||||
self.assertTrue(sinks[1]["muted"])
|
||||
self.assertEqual(sinks[1]["volume"], 0.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Tests de la saisie de texte : disposition du clavier, traduction caractère -> touches, envoi des frappes."""
|
||||
|
||||
import asyncio
|
||||
import unittest
|
||||
from typing import Any
|
||||
|
||||
from mediadeck.input import TYPING_KEYS, VirtualInput
|
||||
from mediadeck.keymap import (
|
||||
KEY_ENTER,
|
||||
KEY_SPACE,
|
||||
Keymap,
|
||||
KeymapError,
|
||||
LayoutSpec,
|
||||
Stroke,
|
||||
parse_kxkbrc,
|
||||
parse_setxkbmap,
|
||||
)
|
||||
from mediadeck.text import MAX_TEXT_LENGTH, TextTyper
|
||||
|
||||
from xkbsim import Simulator, SimulatorUnavailable
|
||||
|
||||
US = LayoutSpec(layout="us")
|
||||
FR = LayoutSpec(layout="fr")
|
||||
FR_LATIN9 = LayoutSpec(model="pc104", layout="fr", variant="latin9")
|
||||
DE = LayoutSpec(layout="de")
|
||||
|
||||
KEY_A, KEY_Q, KEY_2, KEY_0 = 30, 16, 3, 11
|
||||
KEY_LEFTSHIFT, KEY_RIGHTALT = 42, 100
|
||||
|
||||
ASCII = "Hello, World! 0123456789 @#$%^&*()_+-=[]{};:'\",.<>/?\\|`~ end"
|
||||
FRENCH = "Élève à l'école, ça coûte 5 €, garçon naïf, forêt, Noël, Ça va ? Œuvre : « oui »."
|
||||
|
||||
|
||||
def build(spec: LayoutSpec) -> Keymap:
|
||||
try:
|
||||
return Keymap(spec)
|
||||
except KeymapError as exc:
|
||||
raise unittest.SkipTest(f"xkb unavailable for {spec}: {exc}") from exc
|
||||
|
||||
|
||||
class ParseTest(unittest.TestCase):
|
||||
def test_kxkbrc(self) -> None:
|
||||
text = "[Layout]\nDisplayNames=,\nLayoutList=fr,us\nModel=pc104\nOptions=compose:ralt\nUse=true\nVariantList=latin9,\n"
|
||||
self.assertEqual(
|
||||
parse_kxkbrc(text),
|
||||
[
|
||||
LayoutSpec("pc104", "fr", "latin9", "compose:ralt"),
|
||||
LayoutSpec("pc104", "us", "", "compose:ralt"),
|
||||
],
|
||||
)
|
||||
|
||||
def test_kxkbrc_not_applicable(self) -> None:
|
||||
self.assertIsNone(parse_kxkbrc("[Layout]\nLayoutList=fr\nUse=false\n"))
|
||||
self.assertIsNone(parse_kxkbrc("[Other]\nUse=true\n"))
|
||||
self.assertIsNone(parse_kxkbrc("[Layout]\nUse=true\nLayoutList=\n"))
|
||||
self.assertIsNone(parse_kxkbrc("pas un fichier ini"))
|
||||
|
||||
def test_kxkbrc_defaults_model(self) -> None:
|
||||
specs = parse_kxkbrc("[Layout]\nUse=true\nLayoutList=de\n")
|
||||
assert specs is not None
|
||||
self.assertEqual(specs[0], LayoutSpec("pc105", "de", "", ""))
|
||||
|
||||
def test_setxkbmap(self) -> None:
|
||||
output = "rules: evdev\nmodel: pc104\nlayout: fr,us\nvariant: latin9,\noptions: grp:alt_shift_toggle\n"
|
||||
self.assertEqual(
|
||||
parse_setxkbmap(output),
|
||||
[
|
||||
LayoutSpec("pc104", "fr", "latin9", "grp:alt_shift_toggle"),
|
||||
LayoutSpec("pc104", "us", "", "grp:alt_shift_toggle"),
|
||||
],
|
||||
)
|
||||
self.assertIsNone(parse_setxkbmap(""))
|
||||
|
||||
|
||||
class KeymapTest(unittest.TestCase):
|
||||
def test_us_basic(self) -> None:
|
||||
keymap = build(US)
|
||||
self.assertEqual(keymap.plan("a")[0], [Stroke(KEY_A)])
|
||||
self.assertEqual(keymap.plan("A")[0], [Stroke(KEY_A, shift=True)])
|
||||
self.assertEqual(keymap.plan("@")[0], [Stroke(KEY_2, shift=True)])
|
||||
self.assertEqual(keymap.plan(" ")[0], [Stroke(KEY_SPACE)])
|
||||
self.assertEqual(keymap.plan("\n")[0], [Stroke(KEY_ENTER)])
|
||||
self.assertEqual((keymap.shift_code, keymap.altgr_code), (KEY_LEFTSHIFT, None))
|
||||
|
||||
def test_azerty_differs_from_qwerty(self) -> None:
|
||||
# Le piège d'origine : la même lettre ne se tape pas avec la même touche
|
||||
keymap = build(FR)
|
||||
self.assertEqual(keymap.plan("a")[0], [Stroke(KEY_Q)])
|
||||
self.assertEqual(keymap.plan("1")[0], [Stroke(2, shift=True)])
|
||||
self.assertEqual(keymap.plan("é")[0], [Stroke(KEY_2)])
|
||||
self.assertEqual(keymap.plan("@")[0], [Stroke(KEY_0, altgr=True)])
|
||||
self.assertEqual(keymap.altgr_code, KEY_RIGHTALT)
|
||||
|
||||
def test_unavailable_characters_are_reported_once(self) -> None:
|
||||
strokes, skipped = build(US).plan("a→b→😀")
|
||||
self.assertEqual(len(strokes), 2)
|
||||
self.assertEqual(skipped, ["→", "😀"])
|
||||
|
||||
def test_typographic_fallback(self) -> None:
|
||||
keymap = build(US)
|
||||
apostrophe = keymap.plan("'")[0]
|
||||
self.assertEqual(keymap.plan("’")[0], apostrophe)
|
||||
self.assertEqual(keymap.plan("…")[0], keymap.plan("...")[0])
|
||||
|
||||
def test_only_allowed_keys_are_used(self) -> None:
|
||||
keymap = build(FR_LATIN9)
|
||||
strokes, _ = keymap.plan(ASCII + FRENCH)
|
||||
self.assertTrue(all(stroke.code in TYPING_KEYS for stroke in strokes))
|
||||
|
||||
def test_invalid_layout(self) -> None:
|
||||
with self.assertRaises(KeymapError):
|
||||
Keymap(LayoutSpec(layout="zz-not-a-layout"))
|
||||
|
||||
|
||||
class RoundTripTest(unittest.TestCase):
|
||||
"""Les frappes calculées, rejouées par un état xkb, redonnent exactement le texte demandé."""
|
||||
|
||||
def simulate(self, spec: LayoutSpec, text: str) -> tuple[str, list[str]]:
|
||||
keymap = build(spec)
|
||||
try:
|
||||
simulator = Simulator(keymap)
|
||||
except SimulatorUnavailable as exc:
|
||||
raise unittest.SkipTest(f"no compose table for {exc}") from exc
|
||||
strokes, skipped = keymap.plan(text)
|
||||
return simulator.type(strokes), skipped
|
||||
|
||||
def test_ascii_on_us(self) -> None:
|
||||
typed, skipped = self.simulate(US, ASCII)
|
||||
self.assertEqual((typed, skipped), (ASCII, []))
|
||||
|
||||
def test_ascii_on_azerty_latin9(self) -> None:
|
||||
typed, skipped = self.simulate(FR_LATIN9, ASCII)
|
||||
self.assertEqual((typed, skipped), (ASCII, []))
|
||||
|
||||
def test_ascii_on_german(self) -> None:
|
||||
typed, skipped = self.simulate(DE, ASCII)
|
||||
self.assertEqual((typed, skipped), (ASCII, []))
|
||||
|
||||
def test_french_text_on_azerty(self) -> None:
|
||||
typed, skipped = self.simulate(FR_LATIN9, FRENCH)
|
||||
self.assertEqual(skipped, [])
|
||||
self.assertEqual(typed, FRENCH)
|
||||
|
||||
def test_accents_with_dead_keys(self) -> None:
|
||||
# ê, ï, ñ, ü, â : absents de la rangée de touches ou obtenus par touche morte
|
||||
text = "ê ï ñ ü â Ê Ö ã û"
|
||||
typed, skipped = self.simulate(FR_LATIN9, text)
|
||||
self.assertEqual((typed, skipped), (text, []))
|
||||
|
||||
def test_partial_text_only_loses_the_unavailable_characters(self) -> None:
|
||||
typed, skipped = self.simulate(US, "abc → def")
|
||||
self.assertEqual(skipped, ["→"])
|
||||
self.assertEqual(typed, "abc def")
|
||||
|
||||
def test_newline_and_tab(self) -> None:
|
||||
typed, _ = self.simulate(US, "a\tb\nc")
|
||||
# Entrée produit « \r » dans xkb ; les applications le lisent comme la touche Entrée
|
||||
self.assertEqual(typed, "a\tb\rc")
|
||||
|
||||
|
||||
class FakeKeyboard:
|
||||
"""Remplace VirtualInput : enregistre les événements et suit les touches enfoncées."""
|
||||
|
||||
available = True
|
||||
reason = ""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.events: list[tuple[int, bool]] = []
|
||||
self.down: set[int] = set()
|
||||
|
||||
def write_keys(self, events: list[tuple[int, bool]]) -> None:
|
||||
for code, pressed in events:
|
||||
assert code in TYPING_KEYS
|
||||
self.events.append((code, pressed))
|
||||
(self.down.add if pressed else self.down.discard)(code)
|
||||
|
||||
|
||||
def typer(keyboard: Any = None, enabled: bool = True, spec: LayoutSpec = US, delay: float = 0) -> TextTyper:
|
||||
async def layout() -> LayoutSpec:
|
||||
return spec
|
||||
|
||||
return TextTyper(keyboard or FakeKeyboard(), enabled, layout, delay)
|
||||
|
||||
|
||||
class TextTyperTest(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_event_order_with_modifiers(self) -> None:
|
||||
keyboard = FakeKeyboard()
|
||||
await typer(keyboard).type("aA")
|
||||
self.assertEqual(
|
||||
keyboard.events,
|
||||
[
|
||||
(KEY_A, True), (KEY_A, False),
|
||||
(KEY_LEFTSHIFT, True), (KEY_A, True), (KEY_A, False), (KEY_LEFTSHIFT, False),
|
||||
],
|
||||
)
|
||||
self.assertEqual(keyboard.down, set())
|
||||
|
||||
async def test_layout_is_read_on_each_call(self) -> None:
|
||||
keyboard = FakeKeyboard()
|
||||
spec = [US]
|
||||
|
||||
async def layout() -> LayoutSpec:
|
||||
return spec[0]
|
||||
|
||||
text_typer = TextTyper(keyboard, True, layout, 0)
|
||||
await text_typer.type("a")
|
||||
spec[0] = FR
|
||||
await text_typer.type("a")
|
||||
self.assertEqual([code for code, pressed in keyboard.events if pressed], [KEY_A, KEY_Q])
|
||||
|
||||
async def test_unavailable_characters_are_typed_around_then_reported(self) -> None:
|
||||
keyboard = FakeKeyboard()
|
||||
with self.assertRaisesRegex(ValueError, "→"):
|
||||
await typer(keyboard).type("a→b")
|
||||
self.assertEqual([code for code, pressed in keyboard.events if pressed], [KEY_A, 48])
|
||||
|
||||
async def test_validation(self) -> None:
|
||||
for bad in ("", None, 5, ["a"], "x" * (MAX_TEXT_LENGTH + 1)):
|
||||
with self.subTest(bad=bad), self.assertRaises(ValueError):
|
||||
await typer().type(bad)
|
||||
|
||||
async def test_disabled_by_config(self) -> None:
|
||||
disabled = typer(enabled=False)
|
||||
self.assertFalse(disabled.available)
|
||||
self.assertIn("features.text_input", disabled.snapshot()["reason"])
|
||||
with self.assertRaises(RuntimeError):
|
||||
await disabled.type("a")
|
||||
|
||||
async def test_keyboard_unavailable(self) -> None:
|
||||
keyboard = FakeKeyboard()
|
||||
keyboard.available = False
|
||||
keyboard.reason = "cannot open /dev/uinput"
|
||||
text_typer = typer(keyboard)
|
||||
self.assertEqual(text_typer.snapshot(), {"available": False, "reason": "cannot open /dev/uinput"})
|
||||
|
||||
async def test_concurrent_texts_do_not_interleave(self) -> None:
|
||||
keyboard = FakeKeyboard()
|
||||
text_typer = typer(keyboard, delay=0.001)
|
||||
await asyncio.gather(text_typer.type("aaaa"), text_typer.type("bbbb"))
|
||||
pressed = [code for code, is_down in keyboard.events if is_down]
|
||||
self.assertEqual(pressed, [KEY_A] * 4 + [48] * 4)
|
||||
|
||||
async def test_cancellation_never_leaves_a_key_down(self) -> None:
|
||||
keyboard = FakeKeyboard()
|
||||
text_typer = typer(keyboard, delay=0.05)
|
||||
task = asyncio.create_task(text_typer.type("AAAA"))
|
||||
await asyncio.sleep(0.02) # Maj + A sont enfoncées, la pause est en cours
|
||||
self.assertTrue(keyboard.down)
|
||||
task.cancel()
|
||||
with self.assertRaises(asyncio.CancelledError):
|
||||
await task
|
||||
self.assertEqual(keyboard.down, set())
|
||||
|
||||
|
||||
class VirtualInputKeysTest(unittest.TestCase):
|
||||
class Device:
|
||||
def __init__(self) -> None:
|
||||
self.written: list[tuple[int, int, int]] = []
|
||||
self.synced = 0
|
||||
|
||||
def write(self, event_type: int, code: int, value: int) -> None:
|
||||
self.written.append((event_type, code, value))
|
||||
|
||||
def syn(self) -> None:
|
||||
self.synced += 1
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
def make(self) -> tuple[VirtualInput, "VirtualInputKeysTest.Device"]:
|
||||
keyboard_input = VirtualInput(False)
|
||||
device = self.Device()
|
||||
keyboard_input._keyboard = device
|
||||
keyboard_input._pointer = self.Device()
|
||||
return keyboard_input, device
|
||||
|
||||
def test_write_keys_syncs_once(self) -> None:
|
||||
keyboard_input, device = self.make()
|
||||
keyboard_input.write_keys([(KEY_LEFTSHIFT, True), (KEY_A, True)])
|
||||
self.assertEqual([(code, value) for _type, code, value in device.written], [(KEY_LEFTSHIFT, 1), (KEY_A, 1)])
|
||||
self.assertEqual(device.synced, 1)
|
||||
|
||||
def test_keys_outside_the_typing_block_are_refused(self) -> None:
|
||||
keyboard_input, device = self.make()
|
||||
for code in (116, 142, 205, 0, 300): # POWER, SLEEP, SUSPEND, hors plage
|
||||
with self.subTest(code=code), self.assertRaises(ValueError):
|
||||
keyboard_input.write_keys([(code, True)])
|
||||
self.assertEqual(device.written, [])
|
||||
|
||||
def test_unavailable_input(self) -> None:
|
||||
with self.assertRaises(RuntimeError):
|
||||
VirtualInput(False).write_keys([(KEY_A, True)])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Tests du HTTPS local : génération des certificats, validation et poignée de main TLS."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import ssl
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from mediadeck.__main__ import client_url
|
||||
from mediadeck.config import Config, ConfigError, load_config, parse_config
|
||||
from mediadeck.tls import build_ssl_context, enable_tls, generate_certificates, is_permitted
|
||||
|
||||
TOKEN = "x" * 32
|
||||
LAN_IP = "192.168.1.104"
|
||||
|
||||
|
||||
class PermittedNamesTest(unittest.TestCase):
|
||||
def test_private_addresses_and_local_names(self) -> None:
|
||||
for host in (LAN_IP, "10.2.0.2", "172.20.0.1", "127.0.0.1", "localhost", "pc.local", "pc.lan", "pc"):
|
||||
with self.subTest(host=host):
|
||||
self.assertTrue(is_permitted(host, "pc"))
|
||||
|
||||
def test_public_names_refused(self) -> None:
|
||||
for host in ("8.8.8.8", "172.32.0.1", "example.com", "evil.local.example.com", "::1"):
|
||||
with self.subTest(host=host):
|
||||
self.assertFalse(is_permitted(host, "pc"))
|
||||
|
||||
|
||||
class ClientUrlTest(unittest.TestCase):
|
||||
def test_scheme_follows_tls(self) -> None:
|
||||
server = {"token": TOKEN, "advertise_host": LAN_IP}
|
||||
self.assertTrue(client_url(parse_config({"server": server})).startswith(f"http://{LAN_IP}:8765/?token="))
|
||||
tls = {**server, "tls_cert": "/c.pem", "tls_key": "/k.key"}
|
||||
self.assertTrue(client_url(parse_config({"server": tls})).startswith(f"https://{LAN_IP}:8765/?token="))
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("openssl"), "openssl is required")
|
||||
class CertificateTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls._tmp = tempfile.TemporaryDirectory()
|
||||
cls.directory = Path(cls._tmp.name) / "tls"
|
||||
cls.ca, cls.cert, cls.key = generate_certificates(cls.directory, [LAN_IP, "localhost", "127.0.0.1"])
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls._tmp.cleanup()
|
||||
|
||||
def _config(self) -> Config:
|
||||
server = {"token": TOKEN, "tls_cert": str(self.cert), "tls_key": str(self.key), "tls_ca": str(self.ca)}
|
||||
return parse_config({"server": server})
|
||||
|
||||
def test_private_keys_are_personal(self) -> None:
|
||||
self.assertEqual((self.directory / "ca.key").stat().st_mode & 0o077, 0)
|
||||
self.assertEqual(self.key.stat().st_mode & 0o077, 0)
|
||||
self.assertEqual(self.directory.stat().st_mode & 0o077, 0)
|
||||
|
||||
def test_public_name_refused(self) -> None:
|
||||
with self.assertRaises(ConfigError):
|
||||
generate_certificates(self.directory, ["example.com"])
|
||||
|
||||
def test_reissue_keeps_the_ca(self) -> None:
|
||||
before = self.ca.read_bytes()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
# Copie du dossier : le certificat serveur est réémis, la CA (donc la confiance de la tablette) reste
|
||||
copy = Path(tmp) / "tls"
|
||||
shutil.copytree(self.directory, copy)
|
||||
generate_certificates(copy, [LAN_IP])
|
||||
self.assertEqual((copy / "mediadeck-ca.crt").read_bytes(), before)
|
||||
|
||||
def test_world_readable_key_rejected(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
key = Path(tmp) / "server.key"
|
||||
shutil.copy(self.key, key)
|
||||
os.chmod(key, 0o644)
|
||||
server = {"token": TOKEN, "tls_cert": str(self.cert), "tls_key": str(key)}
|
||||
with self.assertRaises(ConfigError):
|
||||
build_ssl_context(parse_config({"server": server}))
|
||||
|
||||
def test_missing_file_rejected(self) -> None:
|
||||
server = {"token": TOKEN, "tls_cert": "/nonexistent.pem", "tls_key": str(self.key)}
|
||||
with self.assertRaises(ConfigError):
|
||||
build_ssl_context(parse_config({"server": server}))
|
||||
|
||||
def test_no_tls_without_certificate(self) -> None:
|
||||
self.assertIsNone(build_ssl_context(parse_config({"server": {"token": TOKEN}})))
|
||||
|
||||
def test_handshake_verifies_with_the_ca(self) -> None:
|
||||
# Le client se connecte en local mais vérifie le nom annoncé à la tablette
|
||||
for name in (LAN_IP, "localhost", "127.0.0.1"):
|
||||
with self.subTest(name=name):
|
||||
asyncio.run(self._handshake(name, cafile=self.ca))
|
||||
|
||||
def test_handshake_refused_for_other_address(self) -> None:
|
||||
with self.assertRaises(ssl.SSLCertVerificationError):
|
||||
asyncio.run(self._handshake("192.168.1.105", cafile=self.ca))
|
||||
|
||||
def test_handshake_refused_without_the_ca(self) -> None:
|
||||
with self.assertRaises(ssl.SSLCertVerificationError):
|
||||
asyncio.run(self._handshake(LAN_IP, cafile=None))
|
||||
|
||||
async def _handshake(self, server_hostname: str, cafile: Path | None) -> None:
|
||||
context = build_ssl_context(self._config())
|
||||
server = await asyncio.start_server(lambda _reader, writer: writer.close(), "127.0.0.1", 0, ssl=context)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
client = ssl.create_default_context(cafile=str(cafile) if cafile else None)
|
||||
try:
|
||||
_reader, writer = await asyncio.open_connection(
|
||||
"127.0.0.1", port, ssl=client, server_hostname=server_hostname
|
||||
)
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
finally:
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
|
||||
|
||||
class EnableTlsTest(unittest.TestCase):
|
||||
def test_inserts_paths_once(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "config.toml"
|
||||
path.write_text(f'[server]\nhost = "0.0.0.0"\nport = 8765\ntoken = "{TOKEN}"\n\n[audio]\nmax_volume = 1.0\n')
|
||||
os.chmod(path, 0o600)
|
||||
cert, key, ca = Path("/t/server.pem"), Path("/t/server.key"), Path("/t/ca.crt")
|
||||
self.assertTrue(enable_tls(path, cert, key, ca))
|
||||
self.assertFalse(enable_tls(path, cert, key, ca))
|
||||
config = load_config(path)
|
||||
self.assertEqual((config.tls_cert, config.tls_key, config.tls_ca), (cert, key, ca))
|
||||
self.assertEqual(config.max_volume, 1.0)
|
||||
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
|
||||
|
||||
def test_missing_port_line(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "config.toml"
|
||||
path.write_text(f'[server]\ntoken = "{TOKEN}"\n')
|
||||
with self.assertRaises(ConfigError):
|
||||
enable_tls(path, Path("/c"), Path("/k"), Path("/a"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Simulateur de clavier pour les tests : rejoue des frappes dans un état xkb avec composition des touches mortes.
|
||||
|
||||
Reproduit ce que fait le serveur graphique (X11 ou Wayland) avec les touches reçues d'un périphérique uinput.
|
||||
"""
|
||||
|
||||
import ctypes
|
||||
|
||||
from mediadeck.keymap import Keymap, Stroke
|
||||
|
||||
_COMPOSING, _COMPOSED, _CANCELLED = 1, 2, 3
|
||||
_KEY_UP, _KEY_DOWN = 0, 1
|
||||
|
||||
|
||||
class SimulatorUnavailable(Exception):
|
||||
"""Table de composition introuvable pour la locale demandée."""
|
||||
|
||||
|
||||
class Simulator:
|
||||
def __init__(self, keymap: Keymap, locale: str = "en_US.UTF-8") -> None:
|
||||
self.keymap = keymap
|
||||
lib = keymap.lib
|
||||
vp, u32, cp, sz = ctypes.c_void_p, ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t
|
||||
for name, restype, argtypes in (
|
||||
("xkb_state_new", vp, [vp]),
|
||||
("xkb_state_unref", None, [vp]),
|
||||
("xkb_state_update_key", ctypes.c_int, [vp, u32, ctypes.c_int]),
|
||||
("xkb_state_key_get_one_sym", u32, [vp, u32]),
|
||||
("xkb_state_key_get_utf8", ctypes.c_int, [vp, u32, ctypes.c_char_p, sz]),
|
||||
("xkb_compose_table_new_from_locale", vp, [vp, cp, ctypes.c_int]),
|
||||
("xkb_compose_state_new", vp, [vp, ctypes.c_int]),
|
||||
("xkb_compose_state_feed", ctypes.c_int, [vp, u32]),
|
||||
("xkb_compose_state_get_status", ctypes.c_int, [vp]),
|
||||
("xkb_compose_state_get_utf8", ctypes.c_int, [vp, ctypes.c_char_p, sz]),
|
||||
("xkb_compose_state_reset", None, [vp]),
|
||||
):
|
||||
function = getattr(lib, name)
|
||||
function.restype, function.argtypes = restype, argtypes
|
||||
self.lib = lib
|
||||
self.state = lib.xkb_state_new(keymap.handle)
|
||||
table = lib.xkb_compose_table_new_from_locale(keymap._context, locale.encode(), 0)
|
||||
if not table:
|
||||
raise SimulatorUnavailable(locale)
|
||||
self.compose = lib.xkb_compose_state_new(table, 0)
|
||||
|
||||
def _utf8(self, function, *args) -> str:
|
||||
buffer = ctypes.create_string_buffer(64)
|
||||
function(*args, buffer, 64)
|
||||
return buffer.value.decode()
|
||||
|
||||
def type(self, strokes: list[Stroke]) -> str:
|
||||
"""Texte obtenu après ces frappes (les touches mortes en attente ne produisent rien)."""
|
||||
lib, output = self.lib, []
|
||||
for stroke in strokes:
|
||||
modifiers = [
|
||||
code
|
||||
for code, wanted in ((self.keymap.shift_code, stroke.shift), (self.keymap.altgr_code, stroke.altgr))
|
||||
if wanted and code is not None
|
||||
]
|
||||
for code in modifiers:
|
||||
lib.xkb_state_update_key(self.state, code + 8, _KEY_DOWN)
|
||||
key = stroke.code + 8
|
||||
keysym = lib.xkb_state_key_get_one_sym(self.state, key)
|
||||
text = self._utf8(lib.xkb_state_key_get_utf8, self.state, key)
|
||||
lib.xkb_state_update_key(self.state, key, _KEY_DOWN)
|
||||
lib.xkb_state_update_key(self.state, key, _KEY_UP)
|
||||
for code in reversed(modifiers):
|
||||
lib.xkb_state_update_key(self.state, code + 8, _KEY_UP)
|
||||
lib.xkb_compose_state_feed(self.compose, keysym)
|
||||
status = lib.xkb_compose_state_get_status(self.compose)
|
||||
if status == _COMPOSING:
|
||||
continue
|
||||
if status == _COMPOSED:
|
||||
output.append(self._utf8(lib.xkb_compose_state_get_utf8, self.compose))
|
||||
elif status != _CANCELLED:
|
||||
output.append(text)
|
||||
lib.xkb_compose_state_reset(self.compose)
|
||||
return "".join(output)
|
||||
Reference in New Issue
Block a user