Files
quiz/tests/test_projector.py
ameer 9ea0a8b039 feat: anti-cheat + presence panel + projector view
Refinement pass on top of the validated v1.2 base.

Hardening / quick fixes
- Caddyfile.tpl: CSP / HSTS / X-Frame / Referrer-Policy / Permissions-Policy,
  1 MiB request body cap, X-Forwarded-For pass-through; stock-Caddy compatible.
- auth.py: STUDENT_MAX_AGE 1y -> 30d.
- bootstrap.sh: stage 5 prepends `git config --add safe.directory` so the
  re-bootstrap path no longer 'detected dubious ownership' faults.
- admin.js: drop the misleading `closedPayload?.state || session.state`
  shim; state derives from session only.

Anti-cheat
- New `student_events` audit table; new POST /api/session/{sid}/event for
  blur / visibility_hidden / focus / visibility_visible. quiz.js debounces
  events at 1.5s and uses sendBeacon for visibility_hidden so the event
  survives a navigation. Counts surface in admin presence + CSV export.
- First-claim-wins on join: add_participant raises DuplicateStudentId on
  PK violation; route returns 409 + records a duplicate_join audit event
  with attempted name + IP + UA. Admin dashboard surfaces a per-row red
  badge for hits on real participants and a top-of-page alert for orphan
  attempts.
- DELETE /admin/api/students/{id} as the recovery hatch: clears the
  participant + submissions, kicks active WS sockets so a stale cookie
  cannot continue submitting. quiz.js surfaces the FastAPI detail message
  in the join form so users see the 'already in use' guidance.

Presence panel
- New presence_update WS message; in-process presence map keyed on
  student_id tracks ws_count + last_seen_ms. Admin dashboard renders
  per-student rows: connected/idle/dropped dot, blur+hidden+duplicate
  badges, 'answered current Q' tick, and a clear-student button.

Projector view (public, read-only)
- /projector/?sid=..., GET /api/session/{sid}/projector, WS
  /ws/projector/{sid}. Single self-contained projector_state snapshot
  pushed on every state change. Public leaderboard strips student_id;
  QR rendered server-side as data: URL (CSP-compliant).
- Includes per-Q answer histogram, 8-bucket response-time distribution,
  10-bucket score distribution.
- static/projector.{html,css,js}: editorial-broadside design — masthead,
  registration crosses, conic-gradient countdown ring, SVG stepped-area
  score distribution with median tick, leaderboard row-stagger. Inherits
  light/dark tokens from style.css; honours prefers-reduced-motion. No
  scroll at 1366x768 / 1920x1080 / 3440x1440.

Tests
- tests/test_anti_cheat.py: blur logging + CSV count, unknown-kind 422,
  unauthenticated event 401, duplicate-join 409 + audit, admin
  clear-student happy + 404, server-side submit lockout regression.
- tests/test_projector.py: snapshot shape, leaderboard student_id
  redaction, WS push on state change, 404 for unknown sid, page redirect
  when no sid.
- Existing tests updated for the new presence_update snapshot frame +
  CSV header columns + first-claim-wins refusal of re-key.

57/57 pytest green; smoke-tested locally end-to-end.
2026-05-04 16:08:59 +08:00

77 lines
2.9 KiB
Python

"""Projector view (public read-only):
- snapshot endpoint returns the expected shape
- leaderboard never carries student_ids (privacy)
- WS client receives a projector_state message on connect
- state changes (open question, submit, close) push fresh snapshots
"""
from __future__ import annotations
import pytest
from starlette.websockets import WebSocketDisconnect
from conftest import admin_login, join_student
def test_projector_snapshot_includes_required_fields(client, sid):
join_student(client, sid, "s1", "Alice")
response = client.get(f"/api/session/{sid}/projector")
assert response.status_code == 200
body = response.json()
assert body["type"] == "projector_state"
assert body["state"] == "lobby"
assert body["sid"] == sid
assert body["participant_count"] == 1
assert "qr_url" in body and body["qr_url"].startswith("data:image/svg+xml")
assert "join_url" in body
assert body["pool_meta"]["question_count"] >= 1
assert "score_distribution" in body
assert "leaderboard" in body
def test_projector_leaderboard_redacts_student_ids(client, sid):
"""The /admin board carries student_ids; the public projector
leaderboard must NOT — student_id namespace is private."""
join_student(client, sid, "s1", "Alice")
join_student(client, sid, "s2", "Bob")
rooms = client.app.state.rooms
client.portal.call(rooms.open_question, sid, 0, 5)
client.portal.call(rooms.submit_answer, sid, "s1", 0, "B")
client.portal.call(rooms.close_question, sid)
snapshot = client.get(f"/api/session/{sid}/projector").json()
for row in snapshot["leaderboard"]:
assert "student_id" not in row, "projector leaderboard leaks student_ids"
def test_projector_ws_pushes_snapshot_on_state_change(client, sid):
join_student(client, sid, "s1", "Alice")
admin_login(client)
with client.websocket_connect(f"/ws/projector/{sid}") as ws:
initial = ws.receive_json()
assert initial["type"] == "projector_state"
assert initial["state"] == "lobby"
# Trigger a state change via the room manager directly.
rooms = client.app.state.rooms
client.portal.call(rooms.open_question, sid, 0, 5)
push = ws.receive_json()
assert push["type"] == "projector_state"
assert push["state"] == "question_open"
assert push["question"] is not None
assert push["question"]["idx"] == 0
def test_projector_404_for_unknown_sid(client):
assert client.get("/api/session/UNKNOWN/projector").status_code == 404
with pytest.raises(WebSocketDisconnect) as exc:
with client.websocket_connect("/ws/projector/UNKNOWN"):
pass
assert exc.value.code == 4001
def test_projector_page_redirects_when_no_sid(client, sid):
response = client.get("/projector/", follow_redirects=False)
assert response.status_code == 302
assert response.headers["location"].endswith(f"sid={sid}")