#!/usr/bin/env python3 """Host integration test for the Quagr client/daemon & cover screen integration. Compiles quagr_plugin.cpp + neoui.cpp and bananarchy-cover-idle.c on the host to verify: 1. Quagr crypto interoperability (passphrase SHA-256 & raw 64-hex keys, XOR, 2-byte checksum, 30-byte padding, wrong-key rejection). 2. Strict autostart gating in both quagr_plugin_init() and --preload (starts ONLY when autostart_rx=1 and a valid Rx passphrase/hex key exist). 3. End-to-end streaming HTTP chunked receive, atomic $SXMO_NOTIFDIR creation, rx.log persistence, and immediate BANANARCHY_COVER_SOCKET QUAGR delivery. 4. Closed-flip bananarchy-cover-idle instant wake, full wrapped message display, persistence past wake_blank_timeout and NOTIFY races, and dismissal via any side button (VOLUP, VOLDOWN, POWER) or LID OPEN while preserving call priority. """ import hashlib import os import pathlib import queue import socket import subprocess import sys import tempfile import textwrap import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer BASE = pathlib.Path(__file__).resolve().parent.parent QUAGR_CPP = BASE / "src/dwm-plugins/quagr_plugin.cpp" NEOUI_CPP = BASE / "src/neoui/neoui.cpp" COVER_C = BASE / "src/bananarchy-daemons/bananarchy-cover-idle.c" FB_W, FB_H, FB_BPP = 240, 240, 32 FB_SIZE = FB_W * FB_H * (FB_BPP // 8) def derive_quagr_pass_key(passphrase: str) -> bytes: return hashlib.sha256(("QUAGR:" + passphrase).encode("utf-8")).digest() def qgr_encrypt_py(message: str, key: bytes, nonce: bytes = None) -> str: raw = message.encode("utf-8")[:30] padded = raw + b"\xff" * (30 - len(raw)) chk = hashlib.sha256(padded).digest()[:2] if nonce is None: nonce = os.urandom(4) mask = hashlib.sha256(nonce + key).digest() mc = padded + chk cipher = bytes(a ^ b for a, b in zip(mc, mask)) return (nonce + cipher).hex() def wait_for(predicate, timeout=4.0, step=0.05): end = time.time() + timeout while time.time() < end: if predicate(): return True time.sleep(step) return False def write_quagr_conf(home_dir: pathlib.Path, *, autostart=0, relay="https://ntfy.sh", topic="quagr-public", rx_mode="pass", rx_secret="", tx_mode="pass", tx_secret=""): cfg_dir = home_dir / ".config/sxmo" cfg_dir.mkdir(parents=True, exist_ok=True) conf = cfg_dir / "quagr.conf" conf.write_text( f"autostart_rx={1 if autostart else 0}\n" f"relay_url={relay}\n" f"topic_id={topic}\n" f"rx_mode={rx_mode}\n" f"rx_secret={rx_secret}\n" f"tx_mode={tx_mode}\n" f"tx_secret={tx_secret}\n", encoding="utf-8", ) def pkg_flags(*pkgs): out = subprocess.check_output(["pkg-config", *pkgs], text=True) return out.strip().split() class CoverHarness: def __init__(self, root: pathlib.Path, exe: pathlib.Path): self.root = root self.sock_path = root / "cover.sock" self.fb = root / "fb1" self.backlight = root / "backlight" self.config = root / "cover.conf" self.main_blank = root / "idle_blank_timeout" self.lid_file = root / "lid-state" self.event_log = root / "cover-events.log" self.event_sh = root / "cover-event.sh" self.event_sh.write_text( "#!/bin/sh\n" "printf '%s %s\\n' \"$1\" \"$2\" >> \"$TEST_COVER_EVENT_LOG\"\n", encoding="utf-8", ) os.chmod(self.event_sh, 0o755) self.fb.write_bytes(b"\x00" * FB_SIZE) self.backlight.write_text("0", encoding="utf-8") self.main_blank.write_text("5\n", encoding="utf-8") self.lid_file.write_text("open\n", encoding="utf-8") self.config.write_text( f"enabled = true\n" f"backend = fb\n" f"socket_path = {self.sock_path}\n" f"fb_device = {self.fb}\n" f"backlight_path = {self.backlight}\n" f"backlight_level = 160\n" f"blank_timeout = auto\n" f"wake_blank_timeout = 1\n", encoding="utf-8", ) env = dict(os.environ) env.update({ "BANANARCHY_COVER_LOCK": str(root / "cover.lock"), "BANANARCHY_COVER_FB_GEOM": f"{FB_W},{FB_H},{FB_BPP}", "BANANARCHY_COVER_MAIN_BLANK_CFG": str(self.main_blank), "BANANARCHY_COVER_NOIDLE_PATH": str(root / "sxmo.noidle"), "BANANARCHY_COVER_LID_STATE": str(self.lid_file), "BANANARCHY_COVER_EVENT_CMD": str(self.event_sh), "TEST_COVER_EVENT_LOG": str(self.event_log), }) self.proc = subprocess.Popen( [str(exe), "--config", str(self.config)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) self.client_path = root / "cover-client.sock" self.client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) self.client.bind(str(self.client_path)) self.client.settimeout(2.0) if not wait_for(self.sock_path.exists, timeout=3.0): raise RuntimeError("cover socket never appeared") def send(self, cmd: str) -> str: self.client.sendto(cmd.encode("utf-8"), str(self.sock_path)) try: return self.client.recv(512).decode("utf-8").strip() except socket.timeout: return "" def status(self) -> dict: raw = self.send("STATUS") fields = {} for tok in raw.split(): if "=" in tok: k, v = tok.split("=", 1) fields[k] = v return fields def set_lid(self, state: str): self.lid_file.write_text(state + "\n", encoding="utf-8") self.send("LID " + state.upper()) def frame_nonzero_rows(self) -> list: data = self.fb.read_bytes() rows = [] stride = FB_W * 4 for y in range(FB_H): row = data[y * stride:(y + 1) * stride] if any(row): rows.append(y) return rows def backlight_value(self) -> str: return self.backlight.read_text(encoding="utf-8").strip() def events(self) -> str: if not self.event_log.exists(): return "" return self.event_log.read_text(encoding="utf-8") def close(self): try: self.send("QUIT") except OSError: pass self.client.close() try: self.proc.wait(timeout=3) except subprocess.TimeoutExpired: self.proc.kill() self.proc.wait() def build_host_binaries(root: pathlib.Path): cflags = pkg_flags("--cflags", "pangoxft", "x11", "xfixes", "xft", "fontconfig", "freetype2", "alsa", "openssl", "libjpeg", "libpng") libs = pkg_flags("--libs", "pangoxft", "x11", "xfixes", "xft", "fontconfig", "freetype2", "alsa", "openssl", "libjpeg", "libpng") so_path = root / "quagr.so" cmd_so = [ "g++", "-shared", "-fPIC", "-std=c++20", "-O2", "-Wall", "-Wextra", *cflags, f"-I{BASE / 'src/neoui'}", f"-I{BASE / 'src/dwm-plugins'}", str(QUAGR_CPP), str(NEOUI_CPP), *libs, "-o", str(so_path), ] res_so = subprocess.run(cmd_so, capture_output=True, text=True) if res_so.returncode != 0: raise RuntimeError("quagr.so host compile failed:\n" + res_so.stderr) harness_c = root / "quagr_host_runner.c" harness_c.write_text(textwrap.dedent(""" #define _DEFAULT_SOURCE #include #include #include #include #include "dwm_plugin.h" static int g_spawn_calls = 0; static char g_spawn_name[64] = ""; static char g_spawn_arg[64] = ""; static void mock_spawn_plugin(const char* name, const char* arg) { g_spawn_calls++; snprintf(g_spawn_name, sizeof(g_spawn_name), "%s", name ? name : ""); snprintf(g_spawn_arg, sizeof(g_spawn_arg), "%s", arg ? arg : ""); } int main(int argc, char** argv) { const char* so_path = getenv("TEST_QUAGR_SO"); if (!so_path || !*so_path) return 90; void* h = dlopen(so_path, RTLD_NOW | RTLD_LOCAL); if (!h) { fprintf(stderr, "dlopen: %s\\n", dlerror()); return 91; } const DwmPlugin* plug = (const DwmPlugin*)dlsym(h, DWM_PLUGIN_ENTRY_SYMBOL); if (!plug || plug->api_version != DWM_PLUGIN_API_VERSION || !plug->name) { fprintf(stderr, "invalid plugin entry\\n"); return 92; } if (argc >= 2 && strcmp(argv[1], "--probe-init") == 0) { DwmHostApi api; memset(&api, 0, sizeof(api)); api.api_version = DWM_PLUGIN_API_VERSION; api.spawn_plugin = mock_spawn_plugin; if (plug->init) plug->init(&api); printf("spawn=%d name=%s arg=%s\\n", g_spawn_calls, g_spawn_name, g_spawn_arg); dlclose(h); return 0; } if (!plug->run_main) return 93; int rc = plug->run_main(argc, argv); dlclose(h); return rc; } """), encoding="utf-8") runner_path = root / "quagr_host_runner" cmd_run = [ "gcc", "-std=c99", "-O2", "-Wall", "-Wextra", f"-I{BASE / 'src/sxmo-dwm'}", str(harness_c), "-ldl", "-o", str(runner_path), ] res_run = subprocess.run(cmd_run, capture_output=True, text=True) if res_run.returncode != 0: raise RuntimeError("runner compile failed:\n" + res_run.stderr) cover_exe = root / "cover-idle" res_cov = subprocess.run( ["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", f"-I{COVER_C.parent}", str(COVER_C), "-o", str(cover_exe)], capture_output=True, text=True, ) if res_cov.returncode != 0: raise RuntimeError("cover-idle host compile failed:\n" + res_cov.stderr) return so_path, runner_path, cover_exe def run_runner(runner: pathlib.Path, so_path: pathlib.Path, home: pathlib.Path, args, extra_env=None, timeout=5.0): env = dict(os.environ) env["HOME"] = str(home) env["TEST_QUAGR_SO"] = str(so_path) if extra_env: env.update(extra_env) return subprocess.run( [str(runner), *args], env=env, capture_output=True, text=True, timeout=timeout, ) def test_init_and_autostart_gating(so_path: pathlib.Path, runner: pathlib.Path, root: pathlib.Path): # 1. Protocol & crypto internal self-test h0 = root / "home-selftest" h0.mkdir() r = run_runner(runner, so_path, h0, ["--self-test"]) assert r.returncode == 0, f"--self-test failed: {r.stderr}" # 2. Config absent -> no autostart in both init() and --preload h_none = root / "home-none" h_none.mkdir() r_init = run_runner(runner, so_path, h_none, ["--probe-init"]) assert r_init.stdout.strip() == "spawn=0 name= arg=", r_init.stdout r_pre = run_runner(runner, so_path, h_none, ["--preload"], timeout=2.0) assert r_pre.returncode == 0 # 3. autostart_rx=0 with valid Rx passphrase -> no autostart h_off = root / "home-off" write_quagr_conf(h_off, autostart=0, rx_mode="pass", rx_secret="valid-pass") r_init = run_runner(runner, so_path, h_off, ["--probe-init"]) assert r_init.stdout.strip() == "spawn=0 name= arg=", r_init.stdout r_pre = run_runner(runner, so_path, h_off, ["--preload"], timeout=2.0) assert r_pre.returncode == 0 # 4. autostart_rx=1 with empty Rx secret (even if Tx secret set!) -> no autostart h_empty = root / "home-empty-rx" write_quagr_conf(h_empty, autostart=1, rx_mode="pass", rx_secret="", tx_mode="pass", tx_secret="only-tx-set") r_init = run_runner(runner, so_path, h_empty, ["--probe-init"]) assert r_init.stdout.strip() == "spawn=0 name= arg=", r_init.stdout r_pre = run_runner(runner, so_path, h_empty, ["--preload"], timeout=2.0) assert r_pre.returncode == 0 # 5. autostart_rx=1 with invalid 63-char hex Rx key -> no autostart h_badhex = root / "home-badhex" write_quagr_conf(h_badhex, autostart=1, rx_mode="hex", rx_secret="a" * 63) r_init = run_runner(runner, so_path, h_badhex, ["--probe-init"]) assert r_init.stdout.strip() == "spawn=0 name= arg=", r_init.stdout r_pre = run_runner(runner, so_path, h_badhex, ["--preload"], timeout=2.0) assert r_pre.returncode == 0 # 6. autostart_rx=1 with valid passphrase -> init() spawns --preload h_pass = root / "home-pass-ok" write_quagr_conf(h_pass, autostart=1, rx_mode="pass", rx_secret="foo bar baz") r_init = run_runner(runner, so_path, h_pass, ["--probe-init"]) assert r_init.stdout.strip() == "spawn=1 name=quagr arg=--preload", r_init.stdout # 7. autostart_rx=1 with valid 64-hex key -> init() spawns --preload h_hex = root / "home-hex-ok" write_quagr_conf(h_hex, autostart=1, rx_mode="hex", rx_secret="0123456789abcdef" * 4) r_init = run_runner(runner, so_path, h_hex, ["--probe-init"]) assert r_init.stdout.strip() == "spawn=1 name=quagr arg=--preload", r_init.stdout print("[ok] Quagr crypto self-test and strict init/--preload autostart gating") class MockNtfyState: def __init__(self): self.stream_ready = threading.Event() self.stop_stream = threading.Event() self.chunks = queue.Queue() self.posted = [] self.get_count = 0 def start_mock_ntfy(state: MockNtfyState): class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, fmt, *args): return def do_GET(self): if not self.path.endswith("/raw"): self.send_response(404) self.send_header("Content-Length", "0") self.end_headers() return state.get_count += 1 self.send_response(200) self.send_header("Content-Type", "text/plain") self.send_header("Transfer-Encoding", "chunked") self.end_headers() # Send an initial ntfy keepalive blank chunk before signaling ready self.wfile.write(b"1\r\n\n\r\n") self.wfile.flush() state.stream_ready.set() while not state.stop_stream.is_set(): try: chunk = state.chunks.get(timeout=0.1) except queue.Empty: continue if chunk is None: break data = chunk.encode("utf-8") frame = f"{len(data):x}\r\n".encode("ascii") + data + b"\r\n" self.wfile.write(frame) self.wfile.flush() try: self.wfile.write(b"0\r\n\r\n") self.wfile.flush() except OSError: pass def do_POST(self): clen = int(self.headers.get("Content-Length", "0")) body = self.rfile.read(clen).decode("utf-8", errors="replace") state.posted.append((self.path, body)) self.send_response(200) self.send_header("Content-Length", "2") self.end_headers() self.wfile.write(b"ok") srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler) srv.daemon_threads = True t = threading.Thread(target=srv.serve_forever, daemon=True) t.start() return srv def run_preload_stream_case(so_path: pathlib.Path, runner: pathlib.Path, case_dir: pathlib.Path, *, rx_mode: str, rx_secret: str, decrypt_key: bytes, message: str): state = MockNtfyState() srv = start_mock_ntfy(state) port = srv.server_address[1] home = case_dir / "home" notif_dir = case_dir / "notifs" notif_dir.mkdir(parents=True, exist_ok=True) cover_sock_path = case_dir / "mock_cover.sock" cover_rx = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) cover_rx.bind(str(cover_sock_path)) cover_rx.settimeout(0.2) different_tx_hex = "fe" * 32 write_quagr_conf( home, autostart=1, relay=f"http://127.0.0.1:{port}", topic="testroom", rx_mode=rx_mode, rx_secret=rx_secret, tx_mode="hex", tx_secret=different_tx_hex, ) # Clean any stale plugin lock/fifo in /tmp just in case for p in ("/tmp/dwm_plugin_quagr.lock", "/tmp/dwm_plugin_quagr.fifo", "/tmp/dwm_plugin_quagr.daemon.pid"): if os.path.exists(p): os.unlink(p) env = dict(os.environ) env.update({ "HOME": str(home), "TEST_QUAGR_SO": str(so_path), "SXMO_NOTIFDIR": str(notif_dir), "BANANARCHY_COVER_SOCKET": str(cover_sock_path), }) proc = subprocess.Popen( [str(runner), "--preload"], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) try: assert state.stream_ready.wait(timeout=3.0), "preload daemon did not subscribe" # Push noise encrypted under a different key -> must be silently ignored wrong_key = derive_quagr_pass_key("definitely-wrong-key") state.chunks.put(qgr_encrypt_py("Noise ignore me", wrong_key) + "\n") # Push real packet split across two chunks to test chunked stream assembly good_pkt = qgr_encrypt_py(message, decrypt_key) + "\n" state.chunks.put(good_pkt[:33]) time.sleep(0.05) state.chunks.put(good_pkt[33:]) received_dgrams = [] def check_notif_and_cover(): try: data = cover_rx.recv(512).decode("utf-8", errors="replace") received_dgrams.append(data) except OSError: pass files = [f for f in notif_dir.iterdir() if not f.name.startswith(".")] return len(files) > 0 and len(received_dgrams) > 0 assert wait_for(check_notif_and_cover, timeout=4.0), ( f"missing notif/cover delivery: notifs={list(notif_dir.iterdir())}, " f"dgrams={received_dgrams}" ) assert received_dgrams == [f"QUAGR {message}\n"], f"unexpected cover dgram: {received_dgrams}" nfiles = [f for f in notif_dir.iterdir() if not f.name.startswith(".")] assert len(nfiles) == 1, f"expected 1 notif file (noise ignored), got {nfiles}" lines = nfiles[0].read_text(encoding="utf-8").splitlines() assert lines[:3] == ["quagr", "xquagr", f"[Quagr] {message}"], lines rx_log = (home / ".local/share/sxmo/quagr/rx.log").read_text(encoding="utf-8") assert message in rx_log, rx_log assert "Noise ignore me" not in rx_log, rx_log finally: state.stop_stream.set() state.chunks.put(None) proc.terminate() try: proc.wait(timeout=3) except subprocess.TimeoutExpired: proc.kill() proc.wait() cover_rx.close() srv.shutdown() srv.server_close() for p in ("/tmp/dwm_plugin_quagr.lock", "/tmp/dwm_plugin_quagr.fifo", "/tmp/dwm_plugin_quagr.daemon.pid"): if os.path.exists(p): os.unlink(p) def test_cover_quagr_integration(cover_exe: pathlib.Path, root: pathlib.Path): cov_dir = root / "cover-test" cov_dir.mkdir() cov = CoverHarness(cov_dir, cover_exe) try: # Start closed and dark cov.set_lid("closed") assert wait_for(lambda: cov.status().get("visible") == "0") assert cov.backlight_value() == "0" # Full 30-byte ASCII message with punctuation msg = "Meet @ gate #4 = 19:30! [OK!!]" assert len(msg.encode("utf-8")) == 30 cov.send("QUAGR " + msg) assert wait_for(lambda: cov.status().get("visible") == "1") st = cov.status() assert st.get("quagr") == "1", st assert cov.backlight_value() == "160" rows = cov.frame_nonzero_rows() # Header (~y 0..30), timestamp (~y 38..45), wrapped message (~y 60..170), footer (~y 222) msg_rows = [y for y in rows if 58 <= y <= 185] assert len(msg_rows) >= 24, f"expected multi-line message rows on cover, got {msg_rows}" # Concurrent NOTIFY Notification from sxmo_hook_notification.sh + waiting # past wake_blank_timeout=1 must NOT cancel or auto-blank the Quagr alert cov.send("NOTIFY Notification") time.sleep(1.35) st = cov.status() assert st.get("visible") == "1" and st.get("quagr") == "1", st assert cov.backlight_value() == "160" # Dismiss with BUTTON VOLUP + trailing WAKE race -> must blank & clear cov.send("BUTTON VOLUP") time.sleep(0.03) cov.send("WAKE") assert wait_for(lambda: cov.status().get("visible") == "0" and cov.status().get("quagr") == "0") assert cov.backlight_value() == "0" time.sleep(0.2) assert cov.status().get("visible") == "0", "trailing WAKE should stay dismissed" # Dismiss with BUTTON VOLDOWN cov.send("QUAGR Second page & test $42!") assert wait_for(lambda: cov.status().get("quagr") == "1" and cov.status().get("visible") == "1") cov.send("BUTTON VOLDOWN") assert wait_for(lambda: cov.status().get("visible") == "0" and cov.status().get("quagr") == "0") # Dismiss with BUTTON POWER without spawning hangup-call cov.send("QUAGR Power key dismiss check") assert wait_for(lambda: cov.status().get("quagr") == "1" and cov.status().get("visible") == "1") cov.send("BUTTON POWER") assert wait_for(lambda: cov.status().get("visible") == "0" and cov.status().get("quagr") == "0") time.sleep(0.15) assert "hangup-call" not in cov.events(), f"unexpected call event: {cov.events()}" # Opening flip clears quagr alert so next close + button shows normal clock cov.send("QUAGR Clear on flip open") assert wait_for(lambda: cov.status().get("quagr") == "1") cov.set_lid("open") assert wait_for(lambda: cov.status().get("visible") == "0" and cov.status().get("quagr") == "0") cov.set_lid("closed") cov.send("BUTTON VOLUP") assert wait_for(lambda: cov.status().get("visible") == "1") assert cov.status().get("quagr") == "0" # Incoming phone call still takes side-button priority over held Quagr alert cov.send("QUAGR Behind incoming call") cov.send("CALL incoming|+1234567|Alice|SIM1") assert wait_for(lambda: cov.status().get("call") == "incoming" and cov.status().get("quagr") == "1") cov.send("BUTTON VOLUP") assert wait_for(lambda: cov.status().get("call") == "muted") assert wait_for(lambda: "mute-ring" in cov.events()) print("[ok] closed-flip cover wakes on QUAGR, holds full message, and dismisses on any side button") finally: cov.close() def main(): if not QUAGR_CPP.is_file() or not COVER_C.is_file(): sys.stderr.write("FAIL: missing quagr_plugin.cpp or bananarchy-cover-idle.c\n") return 1 with tempfile.TemporaryDirectory(prefix="bananarchy-quagr-test-") as tmp: root = pathlib.Path(tmp) so_path, runner_path, cover_exe = build_host_binaries(root) test_init_and_autostart_gating(so_path, runner_path, root) run_preload_stream_case( so_path, runner_path, root / "case-pass", rx_mode="pass", rx_secret="bananarchy-test-pass", decrypt_key=derive_quagr_pass_key("bananarchy-test-pass"), message="Meet @ gate #4 = 19:30! [OK!!]", ) print("[ok] --preload chunked stream + passphrase Rx + notif + cover dgram") hex_key_str = "00112233445566778899aabbccddeeff" * 2 run_preload_stream_case( so_path, runner_path, root / "case-hex", rx_mode="hex", rx_secret=hex_key_str, decrypt_key=bytes.fromhex(hex_key_str), message="Привет #7: OK!", ) print("[ok] --preload raw 64-hex Rx key + UTF-8 decryption + notif + cover dgram") test_cover_quagr_integration(cover_exe, root) print("quagr integration tests: all checks passed") return 0 if __name__ == "__main__": sys.exit(main())