"""end to end tests against a real server process. the projector websocket is used as the token source, exactly like a phone camera would read it.""" import asyncio import json import os import socket import ssl import sqlite3 import subprocess import sys import time from contextlib import asynccontextmanager from pathlib import Path import httpx import pytest import websockets ROOT = Path(__file__).resolve().parent.parent def free_port(): s = socket.socket() s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] s.close() return port TLS = os.environ.get("RV_TEST_TLS") == "1" @pytest.fixture(scope="module") def server(tmp_path_factory): port = free_port() tmp = tmp_path_factory.mktemp("db") db = tmp / "test.db" env = {**os.environ, "PORT": str(port), "HOST": "127.0.0.1", "DB_PATH": str(db), "PUBLIC_URL": ""} scheme, wscheme, ws_kw = "http", "ws", {} if TLS: cert, key = tmp / "cert.pem", tmp / "key.pem" subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1", "-subj", "/CN=127.0.0.1", "-addext", "subjectAltName=IP:127.0.0.1", "-keyout", str(key), "-out", str(cert)], check=True, capture_output=True) env.update(TLS_CERT=str(cert), TLS_KEY=str(key), PUBLIC_URL=f"https://127.0.0.1:{port}") scheme, wscheme = "https", "wss" ctx = ssl.create_default_context(cafile=str(cert)) ws_kw = {"ssl": ctx} os.environ["SSL_CERT_FILE"] = str(cert) proc = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) base = f"{scheme}://127.0.0.1:{port}" for _ in range(100): try: httpx.get(base + "/api/config", timeout=0.5, verify=ws_kw.get("ssl", True)) break except httpx.HTTPError: time.sleep(0.1) else: proc.kill() raise RuntimeError(proc.stdout.read().decode()) yield {"base": base, "ws": f"{wscheme}://127.0.0.1:{port}", "db": db, "ws_kw": ws_kw, "verify": ws_kw.get("ssl", True)} proc.terminate() proc.wait(5) def create(server, **kw): body = {"title": "Test", "interval_ms": 300, "scans_required": 3, **kw} r = httpx.post(server["base"] + "/api/polls", json=body, verify=server["verify"]) r.raise_for_status() p = r.json() p["h"] = {"authorization": f"Bearer {p['admin_key']}"} return p def admin(server, p, method, path, **kw): return httpx.request(method, f"{server['base']}/api/polls/{p['id']}{path}", headers=p["h"], verify=server["verify"], **kw) @asynccontextmanager async def projector(server, p, key=None): ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/screen", **server["ws_kw"]) await ws.send(json.dumps({"key": key or p["screen_key"]})) latest = {"tok": None, "slot": -1} changed = asyncio.Event() # keep only the newest code, like a camera looking at the screen right now async def reader(): async for raw in ws: m = json.loads(raw) if m["type"] == "qr": latest.update(tok=m["url"].split("#", 1)[1], slot=m["slot"]) changed.set() task = asyncio.create_task(reader()) returned = {"slot": -1} async def next_token(): while latest["slot"] <= returned["slot"]: changed.clear() await asyncio.wait_for(changed.wait(), 5) returned["slot"] = latest["slot"] return latest["tok"] try: yield next_token finally: task.cancel() await ws.close() async def scan_until(client, server, p, next_token, max_tokens=12): """reads fresh tokens off the projector and posts them like the phone does""" last = None seen = [] for _ in range(max_tokens): tok = await next_token() if tok in seen: continue seen.append(tok) r = await client.post(f"/api/v/{p['id']}/scan", json={"token": tok}) last = r.json() if last["status"] != "progress": return last return last def device(server): return httpx.AsyncClient(base_url=server["base"], headers={"origin": server["base"]}, verify=server["verify"]) async def enroll(server, p, next_token): c = device(server) r = await scan_until(c, server, p, next_token) assert r["status"] == "enrolled", r return c def test_full_flow_and_anonymity(server): p = create(server, expected=2) assert admin(server, p, "PATCH", "", json={"enrollment_open": True}).status_code == 200 async def run(): async with projector(server, p) as next_token: a = await enroll(server, p, next_token) b = await enroll(server, p, next_token) # same device scanning again stays the same voter again = await scan_until(a, server, p, next_token) assert again["status"] == "enrolled" st = admin(server, p, "GET", "").json() assert st["voters"] == 2 qid = admin(server, p, "POST", "/questions", json={"text": "Q1", "options": ["Pour", "Contre"], "open": True}).json()["id"] me = (await a.get(f"/api/v/{p['id']}/me")).json() assert me["enrolled"] and me["questions"][0]["id"] == qid and not me["questions"][0]["voted"] assert (await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0]})).status_code == 200 r = await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [1]}) assert r.status_code == 409 and r.json()["error"] == "already_voted" assert (await b.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": []})).status_code == 200 # tallies stay hidden while open, even for the admin q = admin(server, p, "GET", "").json()["questions"][0] assert q["participants"] == 2 and "results" not in q assert admin(server, p, "POST", f"/questions/{qid}/close").status_code == 200 q = admin(server, p, "GET", "").json()["questions"][0] assert q["results"] == {"counts": [1, 0], "blank": 1, "ballots": 2} r = await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0]}) assert r.status_code == 409 and r.json()["error"] == "not_open" # voters only see results once published me = (await a.get(f"/api/v/{p['id']}/me")).json() assert me["questions"] == [] admin(server, p, "POST", f"/questions/{qid}/publish") me = (await a.get(f"/api/v/{p['id']}/me")).json() assert me["questions"][0]["results"]["counts"] == [1, 0] await a.aclose() await b.aclose() asyncio.run(run()) con = sqlite3.connect(server["db"]) cols = [r[1] for r in con.execute("PRAGMA table_info(ballots)")] assert cols == ["id", "question_id", "choices"] # nothing that points to a voter or a time assert con.execute("SELECT COUNT(*) FROM participation").fetchone()[0] >= 2 def test_stale_duplicate_and_forged_tokens(server): p = create(server, scans_required=3) admin(server, p, "PATCH", "", json={"enrollment_open": True}) async def run(): async with projector(server, p) as next_token: c = device(server) tok = await next_token() r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json() assert r["count"] == 1 and r["accepted"] # same code twice does not count twice r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json() assert r["count"] == 1 and not r["accepted"] # forged mac slot = tok.split(".")[0] r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": f"{int(slot) + 1}.AAAAAAAAAAAA"})).json() assert not r["valid"] and r["count"] == 1 # replaying an old photo of the screen old = await next_token() await asyncio.sleep(3.2) r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": old})).json() assert not r["valid"] # a token from another poll is useless here other = create(server) admin(server, other, "PATCH", "", json={"enrollment_open": True}) async with projector(server, other) as other_next: ot = await other_next() r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": ot})).json() assert not r["valid"] await c.aclose() asyncio.run(run()) def test_slow_attempt_restarts(server): p = create(server, scans_required=3) admin(server, p, "PATCH", "", json={"enrollment_open": True}) async def run(): async with projector(server, p) as next_token: c = device(server) r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": await next_token()})).json() assert r["count"] == 1 # window is scans*interval + 8s slack await asyncio.sleep(9.2) r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": await next_token()})).json() assert r["count"] == 1 await c.aclose() asyncio.run(run()) def test_enrollment_closed_and_cap(server): p = create(server, max_voters=1) admin(server, p, "PATCH", "", json={"enrollment_open": True}) async def run(): async with projector(server, p) as next_token: a = await enroll(server, p, next_token) b = device(server) r = await scan_until(b, server, p, next_token) assert r["status"] == "full" admin(server, p, "PATCH", "", json={"enrollment_open": False, "max_voters": None}) c = device(server) r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": "1.x"})).json() assert r["status"] == "closed" # already enrolled device keeps access after closing assert (await a.get(f"/api/v/{p['id']}/me")).json()["enrolled"] for x in (a, b, c): await x.aclose() asyncio.run(run()) def test_access_codes(server): p = create(server, require_code=True, codes=3) admin(server, p, "PATCH", "", json={"enrollment_open": True}) codes = [c["code"] for c in admin(server, p, "GET", "/codes").json()["codes"]] assert len(codes) == 3 async def run(): async with projector(server, p) as next_token: a = device(server) r = await scan_until(a, server, p, next_token) assert r["status"] == "need_code" r = (await a.post(f"/api/v/{p['id']}/code", json={"code": "ZZZZ-ZZZZ"})).json() assert r["status"] == "bad_code" # lowercase and no dash is accepted r = (await a.post(f"/api/v/{p['id']}/code", json={"code": codes[0].lower().replace("-", "")})).json() assert r["status"] == "enrolled" b = device(server) assert (await scan_until(b, server, p, next_token))["status"] == "need_code" r = (await b.post(f"/api/v/{p['id']}/code", json={"code": codes[0]})).json() assert r["status"] == "bad_code" # single use # code without having proven presence c = device(server) r = (await c.post(f"/api/v/{p['id']}/code", json={"code": codes[1]})).json() assert r["status"] == "rescan" for x in (a, b, c): await x.aclose() asyncio.run(run()) used = admin(server, p, "GET", "/codes").json()["codes"] assert sum(c["used"] for c in used) == 1 def test_concurrent_double_vote(server): p = create(server) admin(server, p, "PATCH", "", json={"enrollment_open": True}) async def run(): async with projector(server, p) as next_token: a = await enroll(server, p, next_token) qid = admin(server, p, "POST", "/questions", json={"text": "Q", "options": ["A", "B", "C"], "kind": "multi", "max_choices": 2, "open": True}).json()["id"] bad = await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0, 1, 2]}) assert bad.status_code == 400 bad = await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0, 0]}) assert bad.status_code == 400 rs = await asyncio.gather(*[ a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [i % 3]}) for i in range(25)]) assert sorted(r.status_code for r in rs) == [200] + [409] * 24 admin(server, p, "POST", f"/questions/{qid}/close") q = admin(server, p, "GET", "").json()["questions"][0] assert q["results"]["ballots"] == 1 and q["participants"] == 1 await a.aclose() asyncio.run(run()) def test_auth(server): p = create(server) assert httpx.get(f"{server['base']}/api/polls/{p['id']}", headers={"authorization": "Bearer nope"}, verify=server["verify"]).status_code == 403 assert httpx.post(f"{server['base']}/api/v/{p['id']}/vote", json={"question_id": 1, "choices": [0]}, verify=server["verify"]).status_code == 403 r = httpx.post(f"{server['base']}/api/polls/{p['id']}/questions", headers={"authorization": f"Bearer {p['screen_key']}"}, json={"text": "x", "options": ["a", "b"]}, verify=server["verify"]) assert r.status_code == 403 # projector key can't administrate async def run(): ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/screen", **server["ws_kw"]) await ws.send(json.dumps({"key": "wrong"})) with pytest.raises(websockets.ConnectionClosed) as e: await asyncio.wait_for(ws.recv(), 3) assert e.value.rcvd.code == 4003 # cookie-authenticated voter socket refuses foreign origins with pytest.raises(websockets.InvalidStatus): await websockets.connect(f"{server['ws']}/ws/{p['id']}/voter", origin="https://evil.example", **server["ws_kw"]) # rotating the screen key revokes the old projector link new = admin(server, p, "POST", "/screen-key").json()["screen_key"] assert new != p["screen_key"] ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/screen", **server["ws_kw"]) await ws.send(json.dumps({"key": p["screen_key"]})) with pytest.raises(websockets.ConnectionClosed): await asyncio.wait_for(ws.recv(), 3) asyncio.run(run()) def test_security_headers(server): p = create(server) r = httpx.get(f"{server['base']}/v/{p['id']}", verify=server["verify"]) assert r.status_code == 200 assert "script-src 'self'" in r.headers["content-security-policy"] assert r.headers["referrer-policy"] == "no-referrer" assert httpx.get(f"{server['base']}/v/doesnotexist", verify=server["verify"]).status_code == 404 def test_live_push_to_connected_voter(server): """a phone that is already on the page gets questions, closing and results without reloading""" p = create(server) admin(server, p, "PATCH", "", json={"enrollment_open": True}) async def run(): async with projector(server, p) as next_token: a = await enroll(server, p, next_token) cred = a.cookies.get(f"rv_{p['id']}") ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/voter", origin=server["base"], additional_headers={"Cookie": f"rv_{p['id']}={cred}"}, **server["ws_kw"]) first = json.loads(await asyncio.wait_for(ws.recv(), 3)) assert first["type"] == "state" and first["questions"] == [] async def wait_for(pred): while True: m = json.loads(await asyncio.wait_for(ws.recv(), 1.5)) if m["type"] == "state" and pred(m): return m qid = admin(server, p, "POST", "/questions", json={"text": "Live", "options": ["A", "B"], "open": True}).json()["id"] m = await wait_for(lambda m: m["questions"] and m["questions"][0]["state"] == "open") assert m["questions"][0]["id"] == qid and not m["questions"][0]["voted"] await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [1]}) await wait_for(lambda m: m["questions"][0]["voted"]) admin(server, p, "POST", f"/questions/{qid}/close") await wait_for(lambda m: m["questions"] == []) # closed + unpublished disappears admin(server, p, "POST", f"/questions/{qid}/publish") m = await wait_for(lambda m: m["questions"] and "results" in m["questions"][0]) assert m["questions"][0]["results"]["counts"] == [0, 1] await ws.close() await a.aclose() asyncio.run(run()) def test_cookie_secure_flag(server): p = create(server) admin(server, p, "PATCH", "", json={"enrollment_open": True}) r = httpx.post(f"{server['base']}/api/v/{p['id']}/scan", json={"token": "1.x"}, verify=server["verify"]) sc = r.headers["set-cookie"].lower() assert "httponly" in sc and "samesite=strict" in sc assert ("secure" in sc) == TLS @pytest.fixture(scope="module") def proxied(tmp_path_factory): """plain http server as it runs behind a TLS proxy that rewrites Host""" port = free_port() db = tmp_path_factory.mktemp("proxy") / "p.db" env = {**os.environ, "PORT": str(port), "HOST": "127.0.0.1", "DB_PATH": str(db), "PUBLIC_URL": "", "BEHIND_PROXY": "1", "TLS_CERT": "", "TLS_KEY": ""} proc = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) base = f"http://127.0.0.1:{port}" for _ in range(100): try: httpx.get(base + "/api/config", timeout=0.5) break except httpx.HTTPError: time.sleep(0.1) yield {"base": base, "ws": f"ws://127.0.0.1:{port}"} proc.terminate() proc.wait(5) def test_behind_proxy(proxied): fwd = {"X-Forwarded-Host": "vote.example.org", "X-Forwarded-Proto": "https"} p = httpx.post(proxied["base"] + "/api/polls", json={"title": "P", "interval_ms": 300, "scans_required": 3}).json() httpx.patch(f"{proxied['base']}/api/polls/{p['id']}", json={"enrollment_open": True}, headers={"authorization": f"Bearer {p['admin_key']}"}) async def run(): ws = await websockets.connect(f"{proxied['ws']}/ws/{p['id']}/screen", additional_headers=fwd) await ws.send(json.dumps({"key": p["screen_key"]})) while True: m = json.loads(await asyncio.wait_for(ws.recv(), 3)) if m["type"] == "qr": break assert m["url"].startswith(f"https://vote.example.org/v/{p['id']}#") await ws.close() # browser origin is the public host, not the rewritten Host: must pass the origin check v = await websockets.connect(f"{proxied['ws']}/ws/{p['id']}/voter", origin="https://vote.example.org", additional_headers=fwd) msg = json.loads(await asyncio.wait_for(v.recv(), 3)) assert msg["type"] == "not_enrolled" with pytest.raises(websockets.ConnectionClosed) as e: await asyncio.wait_for(v.recv(), 3) assert e.value.rcvd.code == 4004 with pytest.raises(websockets.InvalidStatus): await websockets.connect(f"{proxied['ws']}/ws/{p['id']}/voter", origin="https://evil.example", additional_headers=fwd) asyncio.run(run())