mirror of
https://github.com/deunix-educ/mediadeck.git
synced 2026-11-25 04:39:42 +01:00
Offer secure (HTTPS) and unsecured (HTTP) access side by side, add a QR codes page
Optional plain HTTP port next to HTTPS (server.http_port, off by default): - open_sites()/serve() replace web.run_app: one AppRunner, two TCPSites, so the tablet picks https://<ip>:8765 or http://<ip>:8766 without a restart - http_port requires TLS and must differ from port (validated in config.py) - make http-on / http-off (--http-port N) write or remove the line, restoring the file if the result is invalid; make firewall accepts HTTP_PORT - make url prints both addresses and QR codes QR codes page (make qr, --qr): - self-contained HTML written with mode 600 in $XDG_RUNTIME_DIR and opened as file://, never served: the codes contain the access token - qrencode SVG with crispEdges (no seams between modules), fr/en from LANG - cards for HTTPS, HTTP and the CA certificate, depending on the config Tests: 107 (dual listeners with the local CA, set_http_port, QR page content and file mode). Docs: README fr/en and CLAUDE.md updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -64,6 +64,26 @@ class ParseConfigTest(unittest.TestCase):
|
||||
with self.subTest(server=server), self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN, **server}})
|
||||
|
||||
def test_http_port_is_off_by_default(self) -> None:
|
||||
self.assertEqual(parse_config({"server": {"token": TOKEN}}).http_port, 0)
|
||||
|
||||
def test_http_port_next_to_tls(self) -> None:
|
||||
server = {"token": TOKEN, "tls_cert": "/c.pem", "tls_key": "/k.key", "http_port": 8766}
|
||||
self.assertEqual(parse_config({"server": server}).http_port, 8766)
|
||||
|
||||
def test_http_port_is_validated(self) -> None:
|
||||
tls = {"tls_cert": "/c.pem", "tls_key": "/k.key"}
|
||||
for server in (
|
||||
{"http_port": 8766}, # sans TLS, `port` sert déjà du HTTP en clair
|
||||
{**tls, "http_port": 8765}, # même port que le HTTPS
|
||||
{**tls, "http_port": 70000},
|
||||
{**tls, "http_port": -1},
|
||||
{**tls, "http_port": "8766"},
|
||||
{**tls, "http_port": True},
|
||||
):
|
||||
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}})
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Tests de la page des QR codes : contenu, absence du jeton en clair, droits du fichier, choix des codes."""
|
||||
|
||||
import base64
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from mediadeck.__main__ import access_cards
|
||||
from mediadeck.config import parse_config
|
||||
from mediadeck.qrpage import QrCard, build_page, qr_svg, write_page
|
||||
|
||||
TOKEN = "secret-token-" + "x" * 20
|
||||
LAN_IP = "192.168.1.104"
|
||||
TLS = {"tls_cert": "/c.pem", "tls_key": "/k.key", "tls_ca": "/ca.crt"}
|
||||
|
||||
|
||||
def cards_for(**server: object) -> list[QrCard]:
|
||||
return access_cards(parse_config({"server": {"token": TOKEN, "advertise_host": LAN_IP, **server}}))
|
||||
|
||||
|
||||
class AccessCardsTest(unittest.TestCase):
|
||||
def test_plain_http_only_by_default(self) -> None:
|
||||
cards = cards_for()
|
||||
self.assertEqual([card.kind for card in cards], ["http"])
|
||||
self.assertEqual(cards[0].url, f"http://{LAN_IP}:8765/?token={TOKEN}")
|
||||
|
||||
def test_https_only_with_tls(self) -> None:
|
||||
cards = cards_for(**TLS)
|
||||
self.assertEqual([card.kind for card in cards], ["https", "ca"])
|
||||
self.assertEqual(cards[0].url, f"https://{LAN_IP}:8765/?token={TOKEN}")
|
||||
self.assertEqual(cards[1].url, f"https://{LAN_IP}:8765/ca.crt")
|
||||
|
||||
def test_both_modes_fetch_the_ca_over_http(self) -> None:
|
||||
cards = cards_for(**TLS, http_port=8766)
|
||||
self.assertEqual([card.kind for card in cards], ["https", "http", "ca"])
|
||||
self.assertEqual(cards[1].url, f"http://{LAN_IP}:8766/?token={TOKEN}")
|
||||
self.assertEqual(cards[2].url, f"http://{LAN_IP}:8766/ca.crt")
|
||||
|
||||
def test_displayed_address_never_holds_the_token(self) -> None:
|
||||
for card in cards_for(**TLS, http_port=8766):
|
||||
self.assertNotIn(TOKEN, card.address)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("qrencode"), "qrencode is required")
|
||||
class QrPageTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.cards = cards_for(**TLS, http_port=8766)
|
||||
|
||||
def test_page_is_self_contained_and_keeps_the_token_out_of_the_text(self) -> None:
|
||||
page = build_page(self.cards, "en")
|
||||
self.assertEqual(page.count('class="card"'), 3)
|
||||
self.assertNotIn(TOKEN, page)
|
||||
# Aucune ressource externe : seules les images en data: URI
|
||||
self.assertNotRegex(page, r"(src|href)=\"(?!data:)")
|
||||
self.assertIn("Unsecured (HTTP)", page)
|
||||
self.assertIn(f"http://{LAN_IP}:8766", page)
|
||||
|
||||
def test_each_qr_code_encodes_its_url(self) -> None:
|
||||
page = build_page(self.cards, "en")
|
||||
images = re.findall(r"base64,([A-Za-z0-9+/=]+)\"", page)
|
||||
self.assertEqual([base64.b64decode(image) for image in images], [qr_svg(card.url) for card in self.cards])
|
||||
|
||||
def test_qr_svg_has_no_anti_aliasing_seams(self) -> None:
|
||||
self.assertIn(b'shape-rendering="crispEdges"', qr_svg("http://x"))
|
||||
|
||||
def test_language_and_escaping(self) -> None:
|
||||
card = QrCard("http", "http://<script>", "http://x")
|
||||
french = build_page([card], "fr")
|
||||
self.assertIn("Non sécurisé (HTTP)", french)
|
||||
self.assertIn('lang="fr"', french)
|
||||
self.assertNotIn("<script>", french)
|
||||
self.assertIn("<script>", french)
|
||||
|
||||
def test_written_file_is_private(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as runtime, mock.patch.dict("os.environ", {"XDG_RUNTIME_DIR": runtime}):
|
||||
path = write_page(self.cards, "en")
|
||||
path.chmod(0o644) # un fichier précédent aux droits trop larges est resserré à la réécriture
|
||||
path = write_page(self.cards, "en")
|
||||
self.assertEqual(path.parent, Path(runtime) / "mediadeck")
|
||||
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
|
||||
self.assertEqual(path.parent.stat().st_mode & 0o077, 0)
|
||||
self.assertIn("MediaDeck", path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Tests des écoutes : HTTPS seul, ou HTTPS + HTTP en clair (server.http_port), avec une vraie CA locale."""
|
||||
|
||||
import dataclasses
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
|
||||
from mediadeck.config import Config, parse_config
|
||||
from mediadeck.server import open_sites
|
||||
from mediadeck.tls import build_ssl_context, generate_certificates
|
||||
|
||||
TOKEN = "x" * 32
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
async def hello(_request: web.Request) -> web.Response:
|
||||
return web.Response(text="ok")
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("openssl"), "openssl is required")
|
||||
class OpenSitesTest(unittest.IsolatedAsyncioTestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls._tmp = tempfile.TemporaryDirectory()
|
||||
cls.ca, cls.cert, cls.key = generate_certificates(Path(cls._tmp.name) / "tls", ["localhost", "127.0.0.1"])
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls._tmp.cleanup()
|
||||
|
||||
def _config(self, plain: bool) -> Config:
|
||||
server = {
|
||||
"token": TOKEN,
|
||||
"host": "127.0.0.1",
|
||||
"port": free_port(),
|
||||
"tls_cert": str(self.cert),
|
||||
"tls_key": str(self.key),
|
||||
"tls_ca": str(self.ca),
|
||||
}
|
||||
config = parse_config({"server": server})
|
||||
return dataclasses.replace(config, http_port=free_port()) if plain else config
|
||||
|
||||
async def _serve(self, config: Config) -> None:
|
||||
app = web.Application()
|
||||
app.router.add_get("/", hello)
|
||||
runner = await open_sites(app, config, build_ssl_context(config))
|
||||
self.addAsyncCleanup(runner.cleanup)
|
||||
|
||||
async def _get(self, url: str) -> str:
|
||||
context = ssl.create_default_context(cafile=str(self.ca))
|
||||
async with aiohttp.ClientSession() as session, session.get(url, ssl=context) as response:
|
||||
self.assertEqual(response.status, 200)
|
||||
return await response.text()
|
||||
|
||||
async def test_https_only_by_default(self) -> None:
|
||||
config = self._config(plain=False)
|
||||
await self._serve(config)
|
||||
self.assertEqual(await self._get(f"https://127.0.0.1:{config.port}/"), "ok")
|
||||
with self.assertRaises(aiohttp.ClientError):
|
||||
await self._get(f"http://127.0.0.1:{config.port}/")
|
||||
|
||||
async def test_secure_and_unsecured_side_by_side(self) -> None:
|
||||
config = self._config(plain=True)
|
||||
await self._serve(config)
|
||||
self.assertEqual(await self._get(f"https://127.0.0.1:{config.port}/"), "ok")
|
||||
self.assertEqual(await self._get(f"http://127.0.0.1:{config.http_port}/"), "ok")
|
||||
|
||||
async def test_each_port_keeps_its_protocol(self) -> None:
|
||||
config = self._config(plain=True)
|
||||
await self._serve(config)
|
||||
with self.assertRaises(aiohttp.ClientError):
|
||||
await self._get(f"http://127.0.0.1:{config.port}/")
|
||||
with self.assertRaises(aiohttp.ClientError):
|
||||
await self._get(f"https://127.0.0.1:{config.http_port}/")
|
||||
|
||||
async def test_busy_http_port_releases_the_main_port(self) -> None:
|
||||
config = self._config(plain=True)
|
||||
with socket.socket() as busy:
|
||||
busy.bind(("127.0.0.1", config.http_port))
|
||||
busy.listen()
|
||||
with self.assertRaises(OSError):
|
||||
await open_sites(web.Application(), config, build_ssl_context(config))
|
||||
# Le port principal doit être libéré par l'échec : on peut le rouvrir aussitôt
|
||||
await self._serve(dataclasses.replace(config, http_port=0))
|
||||
+49
-1
@@ -10,7 +10,7 @@ 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
|
||||
from mediadeck.tls import build_ssl_context, enable_tls, generate_certificates, is_permitted, set_http_port
|
||||
|
||||
TOKEN = "x" * 32
|
||||
LAN_IP = "192.168.1.104"
|
||||
@@ -35,6 +35,12 @@ class ClientUrlTest(unittest.TestCase):
|
||||
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="))
|
||||
|
||||
def test_plain_url_uses_http_port(self) -> None:
|
||||
server = {"token": TOKEN, "advertise_host": LAN_IP, "tls_cert": "/c.pem", "tls_key": "/k.key", "http_port": 8766}
|
||||
config = parse_config({"server": server})
|
||||
self.assertTrue(client_url(config, plain=True).startswith(f"http://{LAN_IP}:8766/?token="))
|
||||
self.assertTrue(client_url(config).startswith(f"https://{LAN_IP}:8765/?token="))
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("openssl"), "openssl is required")
|
||||
class CertificateTest(unittest.TestCase):
|
||||
@@ -141,3 +147,45 @@ class EnableTlsTest(unittest.TestCase):
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class SetHttpPortTest(unittest.TestCase):
|
||||
TLS = 'tls_cert = "/c.pem"\ntls_key = "/k.key"\n'
|
||||
|
||||
def _write(self, directory: str, body: str) -> Path:
|
||||
path = Path(directory) / "config.toml"
|
||||
path.write_text(f'[server]\nport = 8765\n{body}token = "{TOKEN}"\n')
|
||||
path.chmod(0o600)
|
||||
return path
|
||||
|
||||
def test_adds_replaces_and_removes_the_line(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = self._write(tmp, self.TLS)
|
||||
set_http_port(path, 8766)
|
||||
self.assertEqual(load_config(path).http_port, 8766)
|
||||
set_http_port(path, 9000)
|
||||
self.assertEqual(load_config(path).http_port, 9000)
|
||||
self.assertEqual(path.read_text().count("http_port"), 1)
|
||||
set_http_port(path, 0)
|
||||
self.assertEqual(load_config(path).http_port, 0)
|
||||
self.assertNotIn("http_port", path.read_text())
|
||||
self.assertEqual(path.stat().st_mode & 0o077, 0)
|
||||
|
||||
def test_commented_example_is_not_a_setting(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = self._write(tmp, self.TLS + "# http_port = 1234\n")
|
||||
set_http_port(path, 8766)
|
||||
self.assertEqual(load_config(path).http_port, 8766)
|
||||
self.assertIn("# http_port = 1234", path.read_text())
|
||||
|
||||
def test_invalid_result_restores_the_file(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = self._write(tmp, "") # sans TLS : http_port est refusé
|
||||
before = path.read_text()
|
||||
with self.assertRaises(ConfigError):
|
||||
set_http_port(path, 8766)
|
||||
self.assertEqual(path.read_text(), before)
|
||||
path = self._write(tmp, self.TLS)
|
||||
with self.assertRaises(ConfigError): # même port que le HTTPS
|
||||
set_http_port(path, 8765)
|
||||
self.assertNotIn("http_port", path.read_text())
|
||||
|
||||
Reference in New Issue
Block a user