Files
quiz/tests/test_ws_admin.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

82 lines
3.6 KiB
Python

import pytest
from starlette.websockets import WebSocketDisconnect
from conftest import admin_login, join_student
def test_instructor_ws_requires_admin_cookie(client, sid):
with pytest.raises(WebSocketDisconnect) as exc:
with client.websocket_connect(f"/ws/instructor/{sid}"):
pass
assert exc.value.code == 4001
def _drain_until(ws, target_type, max_msgs=12):
"""Helper: pull messages off `ws` until one matches `target_type`. Lets
tests skip auxiliary state-tracking messages (presence_update,
full_leaderboard) that fire as side-effects of state changes."""
for _ in range(max_msgs):
msg = ws.receive_json()
if msg["type"] == target_type:
return msg
raise AssertionError(f"did not see message {target_type!r} after {max_msgs} attempts")
def test_instructor_next_command_drives_full_loop(client, sid):
"""The 'next' WS message drives the entire lifecycle:
lobby → opens Q0 → closes Q0 + opens Q1 → ... → closes last + ends."""
join_student(client, sid, "s1", "Student One")
admin_login(client)
with client.websocket_connect(f"/ws/student/{sid}") as student_ws:
assert student_ws.receive_json()["type"] == "state"
with client.websocket_connect(f"/ws/instructor/{sid}") as admin_ws:
# Drain lobby snapshot (state + lobby_update + presence_update).
_drain_until(admin_ws, "presence_update")
# First "next" opens Q0 from lobby.
admin_ws.send_json({"type": "next"})
assert student_ws.receive_json()["type"] == "question_open"
_drain_until(admin_ws, "question_open")
_drain_until(admin_ws, "live_histogram")
# Second "next" closes Q0 and opens Q1.
admin_ws.send_json({"type": "next"})
student_msgs = [student_ws.receive_json() for _ in range(2)]
assert {m["type"] for m in student_msgs} == {"question_closed", "question_open"}
def test_instructor_close_then_next_emits_clean_open(client, sid):
join_student(client, sid, "s1", "Student One")
admin_login(client)
with client.websocket_connect(f"/ws/student/{sid}") as student_ws:
assert student_ws.receive_json()["type"] == "state"
with client.websocket_connect(f"/ws/instructor/{sid}") as admin_ws:
_drain_until(admin_ws, "presence_update")
admin_ws.send_json({"type": "open_question", "question_idx": 0, "time_limit": 2})
assert student_ws.receive_json()["type"] == "question_open"
_drain_until(admin_ws, "question_open")
_drain_until(admin_ws, "live_histogram")
admin_ws.send_json({"type": "close_question"})
assert student_ws.receive_json()["type"] == "question_closed"
_drain_until(admin_ws, "question_closed")
_drain_until(admin_ws, "full_leaderboard")
admin_ws.send_json({"type": "next"})
assert student_ws.receive_json()["type"] == "question_open"
def test_reset_command_returns_session_to_lobby(client, sid):
join_student(client, sid, "s1", "Student One")
admin_login(client)
with client.websocket_connect(f"/ws/instructor/{sid}") as admin_ws:
_drain_until(admin_ws, "presence_update")
admin_ws.send_json({"type": "open_question", "question_idx": 0, "time_limit": 2})
_drain_until(admin_ws, "question_open")
_drain_until(admin_ws, "live_histogram")
admin_ws.send_json({"type": "reset"})
# After reset, instructor receives a state=lobby snapshot.
msg = _drain_until(admin_ws, "state")
assert msg["state"] == "lobby"