feat(printer): badge print queue, Pi worker, captive-portal setup, admin printing view
- migration 20261018170000: pgmq badge_print/badge_print_dlq, print_stations, token-gated printer RPCs (claim/complete/fail/heartbeat), admin RPCs, welcome_checkin enqueue; badge_print_tests.sql (101 assertions) - apps/printer: Python worker (Playwright render -> brother_ql via pyusb), comitup captive-portal (Wi-Fi + HTTPS endpoint + anon key + token), arm64 image build + idempotent Pi setup/install scripts, 77 pytest - apps/admin: Printing view, station management/DLQ, global printer status pill, Print button on Registrations, standalone print renderer entry (print.html -> dist-print) with bundled fonts - docs: printing.md + architecture/schema/rpcs/tests/admin-app updates, apps/printer/AGENT.md operating manual - e2e: printing.spec.ts
This commit is contained in:
1 parent
04f3f55b78
commit
c980effddc
55 files changed
+7406
-29
No files matched your search
@@ -0,0 +1,263 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from http.server import ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from portal import portal
|
||||
|
||||
JWT = "eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiYW5vbiJ9.sig-__"
|
||||
TOKEN = "cvp_" + "a" * 64
|
||||
|
||||
|
||||
# ---- pure helpers ----------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_env_basic():
|
||||
parsed = portal.parse_env("# comment\n\nA=1\nB = two words \nBAD\n")
|
||||
assert parsed == {"A": "1", "B": "two words"}
|
||||
|
||||
|
||||
def test_update_env_replaces_in_place_preserves_others_appends_missing():
|
||||
old = (
|
||||
"# header\n"
|
||||
"CONVIVO_URL=https://old.example\n"
|
||||
"STATION_NAME=Desk\n"
|
||||
"PRINTER_IDENTIFIER=usb://0x04f9:0x20a8\n"
|
||||
)
|
||||
new = portal.update_env(old, {"CONVIVO_URL": "https://new.example", "CONVIVO_ANON_KEY": JWT})
|
||||
lines = new.splitlines()
|
||||
assert lines[0] == "# header"
|
||||
assert lines[1] == "CONVIVO_URL=https://new.example"
|
||||
assert "STATION_NAME=Desk" in lines
|
||||
assert "PRINTER_IDENTIFIER=usb://0x04f9:0x20a8" in lines
|
||||
assert lines[-1] == f"CONVIVO_ANON_KEY={JWT}"
|
||||
assert new.endswith("\n")
|
||||
|
||||
|
||||
def test_update_env_rejects_non_whitelisted_key():
|
||||
with pytest.raises(ValueError):
|
||||
portal.update_env("", {"PATH": "/evil"})
|
||||
|
||||
|
||||
def test_update_env_rejects_injection_in_values():
|
||||
with pytest.raises(ValueError):
|
||||
portal.update_env("", {"CONVIVO_URL": "https://x\nEVIL=1"})
|
||||
with pytest.raises(ValueError):
|
||||
portal.update_env("", {"CONVIVO_ANON_KEY": "a=b"})
|
||||
|
||||
|
||||
def test_write_env_atomic_and_mode(tmp_path):
|
||||
path = tmp_path / ".env"
|
||||
portal.write_env(str(path), "CONVIVO_URL=https://x\n")
|
||||
assert path.read_text() == "CONVIVO_URL=https://x\n"
|
||||
assert path.stat().st_mode & 0o777 == 0o600
|
||||
assert not (tmp_path / ".env.tmp").exists()
|
||||
|
||||
|
||||
def test_mask_token():
|
||||
assert portal.mask_token(TOKEN) == "cvp_…" + TOKEN[-4:]
|
||||
assert portal.mask_token("") == ""
|
||||
assert portal.mask_token("cvp_sh") == "cvp_…"
|
||||
assert "a" * 64 not in portal.mask_token(TOKEN)
|
||||
|
||||
|
||||
def test_validate_url():
|
||||
assert portal.validate_url("https://admin.appe.at")[0] is None
|
||||
assert portal.validate_url("https://x")[0] is None
|
||||
assert portal.validate_url("http://192.168.178.4:54321")[1] is not None
|
||||
assert portal.validate_url("http://192.168.178.4:54321")[0] is None
|
||||
assert portal.validate_url("http://localhost:54321")[0] is None
|
||||
assert portal.validate_url("http://127.0.0.1:8000")[0] is None
|
||||
assert portal.validate_url("http://printer.local")[0] is None
|
||||
assert portal.validate_url("http://10.0.0.5")[0] is None
|
||||
assert portal.validate_url("http://172.20.0.1")[0] is None
|
||||
assert portal.validate_url("http://evil.example")[0] is not None
|
||||
assert portal.validate_url("http://8.8.8.8")[0] is not None
|
||||
assert portal.validate_url("ftp://host")[0] is not None
|
||||
assert portal.validate_url("https://")[0] is not None
|
||||
assert portal.validate_url("not a url")[0] is not None
|
||||
|
||||
|
||||
def test_validate_anon_key():
|
||||
assert portal.validate_anon_key(JWT) is None
|
||||
assert portal.validate_anon_key("a.b") is not None
|
||||
assert portal.validate_anon_key("a.b.c.d") is not None
|
||||
assert portal.validate_anon_key("a.b.!bad") is not None
|
||||
assert portal.validate_anon_key("a..c") is not None
|
||||
|
||||
|
||||
def test_validate_token():
|
||||
assert portal.validate_token(TOKEN) is None
|
||||
assert portal.validate_token("x" * 68) is not None
|
||||
assert portal.validate_token("cvp_short") is not None
|
||||
assert portal.validate_token(TOKEN[:-1]) is not None
|
||||
|
||||
|
||||
def test_sort_aps_by_strength_desc_and_bad_values():
|
||||
aps = [
|
||||
{"ssid": "a", "strength": "20"},
|
||||
{"ssid": "b", "strength": "bad"},
|
||||
{"ssid": "c", "strength": "90"},
|
||||
]
|
||||
assert [ap["ssid"] for ap in portal.sort_aps(aps)] == ["c", "a", "b"]
|
||||
|
||||
|
||||
def test_parse_connect_ok_with_warning():
|
||||
form = {
|
||||
"ssid": "Office",
|
||||
"password": "secret",
|
||||
"convivo_url": "http://192.168.1.5:54321",
|
||||
"anon_key": JWT,
|
||||
"station_token": TOKEN,
|
||||
}
|
||||
ssid, password, updates, errors, warnings = portal.parse_connect(form)
|
||||
assert (ssid, password) == ("Office", "secret")
|
||||
assert updates == {
|
||||
"CONVIVO_URL": "http://192.168.1.5:54321",
|
||||
"CONVIVO_ANON_KEY": JWT,
|
||||
"PRINTER_STATION_TOKEN": TOKEN,
|
||||
}
|
||||
assert errors == []
|
||||
assert warnings
|
||||
|
||||
|
||||
def test_parse_connect_hidden_network():
|
||||
form = {"hidden": "1", "hidden_ssid": "SecretNet", "password": "pw"}
|
||||
ssid, password, updates, errors, warnings = portal.parse_connect(form)
|
||||
assert (ssid, password) == ("SecretNet", "pw")
|
||||
assert updates == {} and errors == [] and warnings == []
|
||||
|
||||
|
||||
def test_parse_connect_errors():
|
||||
_, _, updates, errors, _ = portal.parse_connect({})
|
||||
assert errors and not updates
|
||||
_, _, updates, errors, _ = portal.parse_connect(
|
||||
{"ssid": "x" * 40, "convivo_url": "http://evil.example", "station_token": "nope"}
|
||||
)
|
||||
assert len(errors) == 3 and not updates
|
||||
|
||||
|
||||
# ---- HTTP server (dry-run, fake env file) ----------------------------------
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def portal_server(tmp_path, monkeypatch):
|
||||
env = tmp_path / ".env"
|
||||
env.write_text(
|
||||
"CONVIVO_URL=https://old.example\n"
|
||||
"CONVIVO_ANON_KEY=old.anon.key\n"
|
||||
"PRINTER_STATION_TOKEN=cvp_" + "b" * 64 + "\n"
|
||||
"STATION_NAME=Desk\n"
|
||||
)
|
||||
monkeypatch.setattr(portal, "ENV_FILE", str(env))
|
||||
monkeypatch.setattr(portal, "DRY_RUN", True)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), portal.PortalHandler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
yield f"http://127.0.0.1:{server.server_address[1]}", env
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def _get(url: str):
|
||||
with urllib.request.urlopen(url, timeout=5) as resp:
|
||||
return resp.status, resp.read().decode()
|
||||
|
||||
|
||||
def test_get_root_lists_networks_and_masks_token(portal_server):
|
||||
base, env = portal_server
|
||||
status, page = _get(base + "/")
|
||||
assert status == 200
|
||||
assert "FakeOffice" in page and "FakeOpen" in page
|
||||
assert "https://old.example" in page # current URL is shown
|
||||
assert "cvp_" + "b" * 64 not in page # token only masked
|
||||
assert "bbbb" in page # last four shown
|
||||
|
||||
|
||||
def _get_with_cookie(url: str):
|
||||
req = urllib.request.Request(url)
|
||||
with urllib.request.urlopen(req, timeout=5) as resp:
|
||||
page = resp.read().decode()
|
||||
raw_cookie = resp.headers.get("Set-Cookie", "")
|
||||
csrf_cookie = raw_cookie.split(";")[0] # portal_csrf=...
|
||||
return page, csrf_cookie
|
||||
|
||||
|
||||
def test_catchall_redirects_to_portal(portal_server):
|
||||
base, _ = portal_server
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
opener = urllib.request.build_opener(NoRedirect)
|
||||
for probe in ("/generate_204", "/hotspot-detect.html", "/ncsi.txt", "/connecttest.txt"):
|
||||
try:
|
||||
opener.open(base + probe, timeout=5)
|
||||
pytest.fail(f"{probe} should not return 200")
|
||||
except urllib.error.HTTPError as exc:
|
||||
assert exc.code == 302, probe
|
||||
assert exc.headers.get("Location") == "http://10.41.0.1/", probe
|
||||
|
||||
|
||||
def test_networks_json_and_status(portal_server):
|
||||
base, _ = portal_server
|
||||
status, payload = _get(base + "/networks.json")
|
||||
assert status == 200
|
||||
networks = json.loads(payload)["networks"]
|
||||
assert [n["ssid"] for n in networks] == ["FakeOffice", "FakeOpen"]
|
||||
status, payload = _get(base + "/status")
|
||||
assert status == 200 and json.loads(payload)["state"] == "HOTSPOT"
|
||||
|
||||
|
||||
def test_post_connect_rewrites_env_without_echoing_secrets(portal_server):
|
||||
base, env = portal_server
|
||||
page, csrf_cookie = _get_with_cookie(base + "/")
|
||||
csrf = page.split('name=csrf value="')[1].split('"')[0]
|
||||
form = urllib.parse.urlencode(
|
||||
{
|
||||
"csrf": csrf,
|
||||
"ssid": "FakeOffice",
|
||||
"password": "hunter2",
|
||||
"convivo_url": "https://admin.appe.at",
|
||||
"anon_key": "",
|
||||
"station_token": TOKEN,
|
||||
}
|
||||
).encode()
|
||||
req = urllib.request.Request(base + "/connect", data=form,
|
||||
headers={"Cookie": csrf_cookie})
|
||||
with urllib.request.urlopen(req, timeout=5) as resp:
|
||||
status, page = resp.status, resp.read().decode()
|
||||
assert status == 200
|
||||
assert "FakeOffice" in page
|
||||
assert TOKEN not in page and JWT not in page
|
||||
written = env.read_text()
|
||||
assert "CONVIVO_URL=https://admin.appe.at" in written
|
||||
assert f"PRINTER_STATION_TOKEN={TOKEN}" in written
|
||||
assert "CONVIVO_ANON_KEY=old.anon.key" in written # blank field keeps current
|
||||
assert "STATION_NAME=Desk" in written # untouched keys preserved
|
||||
assert env.stat().st_mode & 0o777 == 0o600
|
||||
|
||||
|
||||
def test_post_connect_rejects_bad_csrf(portal_server):
|
||||
base, env = portal_server
|
||||
before = env.read_text()
|
||||
form = urllib.parse.urlencode({"csrf": "nope", "ssid": "FakeOffice"}).encode()
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
urllib.request.urlopen(urllib.request.Request(base + "/connect", data=form), timeout=5)
|
||||
assert exc.value.code == 400
|
||||
assert env.read_text() == before
|
||||
|
||||
|
||||
def test_post_connect_rejects_oversized_body(portal_server):
|
||||
base, _ = portal_server
|
||||
form = b"csrf=x&ssid=" + b"A" * (portal.MAX_BODY_BYTES + 1)
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
urllib.request.urlopen(urllib.request.Request(base + "/connect", data=form), timeout=5)
|
||||
assert exc.value.code == 431
|
||||
Reference in new issue
Block a user