Skip to content

fix: production deployment hardening for Cloudflare Tunnel + WJ auth flow - #57

Closed
JackyTJie wants to merge 36 commits into
mainfrom
fix/production-deploy
Closed

fix: production deployment hardening for Cloudflare Tunnel + WJ auth flow#57
JackyTJie wants to merge 36 commits into
mainfrom
fix/production-deploy

Conversation

@JackyTJie

Copy link
Copy Markdown
Contributor

Summary

Deploys the backend to production behind Cloudflare Tunnel ([api.gcers.org](http://api.gcers.org/)) and fixes every issue hit while bringing up the live environment: container builds behind GFW, CSRF/cookie handling through the Worker proxy, the ORC crawler's dead domain, and several auth bugs surfaced by real user testing of the WJ (问卷) OTP flow.

The frontend (Tech-JI/CourseFront, served from Cloudflare Pages) proxies /api/* to this backend via a Worker; all changes here assume that topology.

Changes

1. Deployment / infrastructure (fix(deploy))

  • Containerfile: replace [gcr.io/distroless/base-debian13:nonroot](http://gcr.io/distroless/base-debian13:nonroot) (unreachable from mainland China) with the [ghcr.io/astral-sh/uv](http://ghcr.io/astral-sh/uv) base image; add a nonroot user for parity.
  • compose.yaml:
    • Add a cloudflared tunnel service, token read from .env (TUNNEL_TOKEN), forced to --protocol http2 — QUIC connections to the Cloudflare edge were being dropped by the network every ~30 min, causing intermittent 1033 errors on the public hostname.
    • Mount ./config.yaml and ./.env read-only into the container so config changes no longer require an image rebuild.
    • Rename service backendCourseReview (matches the tunnel's public hostname service URL).
    • Fix PostgreSQL 18 volume mount: image now requires mounting at /var/lib/postgresql instead of /var/lib/postgresql/data.

2. Security / request plumbing (fix(security))

  • website/settings.py:
    • New CSRF_TRUSTED_ORIGINS config (defaults empty; production values in config.yaml).
    • SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") — requests arrive via HTTPS at Cloudflare but plain HTTP at gunicorn; without this, Django treats secure requests as insecure and SESSION_COOKIE_SECURE breaks cookie setting.
  • apps/web/views.py: add @ensure_csrf_cookie to user_status. The frontend calls GET /api/user/status/ on every page load; previously the csrftoken cookie was only set on OTP endpoints, so password-login users could never make CSRF-protected POSTs (votes, reviews, logout).

3. ORC crawler (fix(spider))

  • Update BASE_URL / COURSE_DETAIL_URL_PREFIX from [www.ji.sjtu.edu.cn](http://www.ji.sjtu.edu.cn/) to [gc.sjtu.edu.cn](http://gc.sjtu.edu.cn/). The old domain's TLS certificate has expired and the catalog redirects to the new host. Verified the new site's page structure (h2 headings, et_pb_text_inner blocks) still matches the parser.

4. Auth fixes (fix(auth))

  • Type cast bug (the big one): AUTH__OTP_TIMEOUT=300 set via .env injects a string into the config, and the config system does not cast it. OTP_TIMEOUT is used in a float comparison in verify_callback_apifloat > "300" raised TypeError, which the surrounding except swallowed and surfaced to users as "Invalid submission timestamp". Both apps/auth/views.py and apps/auth/utils.py now cast with int(...).
  • Turnstile siteverify hardening (apps/auth/utils.py):
    • Dedicated 15s network timeout (previously shared the 300s OTP window — a stalled network call would hang the request).
    • Retry up to 3 times on TimeoutException / HTTPError — transient connect failures to [challenges.cloudflare.com](http://challenges.cloudflare.com/) were observed in production logs.
    • Handle non-JSON responses (rate-limit 429 HTML) with a clean 502 instead of an unhandled json() exception.
  • WJ clock skew tolerance (apps/auth/views.py): the questionnaire platform's server clock was measured ~39s slow (via its HTTP Date header). Submissions made seconds after initiation were rejected as "outside validity window" because the recorded timestamp fell before the initiation time. Added a 60s tolerance on the lower bound; the upper bound (OTP window) is unchanged.
  • Python 2 syntax cleanup: except ValueError, TypeError: is valid Python 3 syntax but means "catch ValueError as TypeError"TypeError was never caught. Fixed in both auth modules. (# fmt: skip required: ruff-format incorrectly strips the tuple parens, which changes semantics.)
  • Diagnostic logging for timestamp rejection (submitted/initiated/diff values) to make future failures debuggable without re-deploys.

Verification

  • Backend built, migrated, and healthy in D+ Valkey 9 + gunicorn).
  • 349 courses crawled and imported from the ORC catalog (4 courses skipped: codes longer than the course_code
    varchar(10) limit).
  • Full login flow verified through the production chain (Cloudflare Pages → Worker proxy → Tunnel → Django): session
    cookie set, GET /api/user/status/ returnskie issued.
  • Turnstile siteverify verified with the production secret key; dummy tokens correctly rejected.
  • Signup OTP flow verified end-to-end with .edu.cnquestionnaires forsignup/login/reset are configured in.env`).
  • ruff format + ruff check pass; pre-co

Notes for reviewers

  • celery is imported by apps/spider/task in pyproject.toml`; the crawler was runwith a celery-free path in this deployment. Out of scope for this PR, but worth a follow-up.
  • 4 ORC courses with combined codes (e.g. Course.course_code` max_length=10 and areskipped on import.
  • config.yaml and .env are gitignored; server.

JackyTJie and others added 30 commits August 13, 2026 23:14
… volume path

- gcr.io distroless base is unreachable behind GFW; reuse ghcr uv image
- add cloudflared tunnel service reading TUNNEL_TOKEN from .env
- force http2 protocol (QUIC connections get dropped on this network)
- mount config.yaml and .env into container for live config updates
- rename service to CourseReview
- fix PostgreSQL 18 volume mount path
- add CSRF_TRUSTED_ORIGINS config for coursesel.gcers.org / api.gcers.org
- add SECURE_PROXY_SSL_HEADER so Django detects HTTPS behind tunnel
- set csrftoken cookie on /api/user/status/ so browser-side POSTs pass CSRF
The course catalog moved from www.ji.sjtu.edu.cn to gc.sjtu.edu.cn and the
old domain's TLS certificate has expired.
- cast OTP_TIMEOUT to int (env override injects a string, breaking float comparisons)
- retry Turnstile siteverify on transient network failures with short timeout
- handle non-JSON siteverify responses (rate limit 429 HTML)
- tolerate 60s negative timestamp offset (WJ server clock measured ~39s slow)
- fix Python 2 style except clauses that never caught TypeError
- add diagnostic logging for submission timestamp failures
- Add whitenoise middleware and STATIC_ROOT=/app/staticfiles
- Run collectstatic during image build so admin/static assets ship in the image
- Add whitenoise>=6.12.0 dependency
- models: syllabus uploaded per course+instructor, sha256-deduped file store
- settings: SYLLABUS/OLLAMA config defaults, MEDIA_ROOT, CELERY_BROKER_URL, ADMINS
- deps: celery, pypdf, pypdfium2, python-docx
- pypdf/python-docx text extraction; pypdfium2 page render + vision OCR for scans
- qwen3.8 chat analysis: course-match/legitimacy verdict + markdown summary
- comparison run against current primary when a course+instructor gains a second
  different syllabus; recommendation resolves primary, both files kept
- failed analysis marks syllabus failed with error_message
- POST courses/<id>/syllabi: multipart upload, sha256 dedup on SyllabusFile,
  idempotent per (course, instructor, file), enqueues analysis task
- GET lists per course; PATCH syllabi/<id> staff-only (summary/verdict/primary)
- GET syllabi/<id>/download streams original file to logged-in users
- course detail + course_instructors now return {id, name} instructor objects
- user/status exposes is_staff; admin models editable with reject action
- ruff-format spider crawler tests and the legacy review import test,
  whose pre-existing deviations made every pre-commit run fail
- compose.dev.yaml: worker service (`celery -A website.celery worker`,
  Ollama on host via host.containers.internal by default), backend and
  worker share the syllabus_media:/app/media volume
- Containerfile: create /app/media and chown to nonroot
- CourseSyllabiAPI/SyllabusDetailAPI: GenericAPIView+Mixins need explicit
  get/post/patch methods or they 405
- refresh Syllabus row after delay() so eager execution (tests) is visible
- move FAILED bookkeeping out of the task atomic block: a re-raise inside
  rolled the failed status back before Celery saw the error
- CourseSerializer.get_instructors: term-agnostic {id, name} pairs so
  syllabus uploads can target any instructor who taught the course
- eager_media fixture pushes task_always_eager onto the Celery app config,
  not just Django settings (celery.py snapshots settings at import time)
- staff_client gets its own APIClient so force_authenticate does not bleed
  between clients; download-auth checks use a fresh anonymous client
- SyllabusFileFactory sha256 unique per instance (unique constraint)
- fake ollama/extraction monkeypatches cover analyze, compare, OCR paths
Django processes never imported website.celery, so @shared_task resolved to
Celery's default bare app and delay() tried amqp://guest@localhost:5672
instead of the configured redis broker. Import the app from website/__init__
so every process picks up the redis broker.

Ollama /api/chat returns content nested under message.content, not top
level, so verdict parsing always saw an empty string; parse the nested
field. qwen3 thinking models emit the final answer into message.thinking
under JSON format, leaving content empty - disable thinking in options.
Also log empty-content responses with done_reason for diagnostics.

Drop NUM_CTX from 262144 to 32768: a 27B Q4 model plus a 262k-token KV
cache exceeds the 24GB GPU, spilling layers to CPU and stalling
inference.
Brings syllabus upload (models 0014, Ollama analysis task, upload/list/
download APIs, admin) into the production branch. Conflicts resolved:
settings.py keeps whitenoise static config and adds media settings;
views.py keeps both the CSRF-cookie decorator import and FileResponse.
The runtime fix moved content extraction from the top-level response key
to message.content; the canned fixture still returned top-level content,
so eager-mode analysis saw an empty body.
Production had no worker (syllabus analysis tasks would never run) and no
media mount (/app/media lives in the container overlay, lost on recreate).
CourseReview and worker now share a syllabus_media volume; the worker
reaches the host Ollama via host.docker.internal:host-gateway with
OLLAMA__BASE_URL pointing at it. --pool=solo because python3.14 prefork
is unreliable and GPU inference is serial anyway.
Replace the syllabus_media named volume with a host bind mount so uploads
live on the /mnt/data disk (uid 1000 matches the container's nonroot user).
Ignore media/ and other local artifacts in the image build.
The runtime fix moved content extraction from the top-level response key
to message.content; the canned fixture still returned top-level content,
so eager-mode analysis saw an empty body.
CodeQL flagged the user-derived syllabus_id in a log call (log injection)
and the two empty JSONDecodeError handlers. The URL regex already limits
syllabus_id to digits; strip CR/LF anyway and explain both pass branches.
gc_offerings.parse_gc_offerings already extracts term, section, and
instructor names, but import_gc_courses only created Course rows and
dropped the rest. Write Instructor (get_or_create by unique name) and
CourseOffering (get_or_create by unique (term, course, section)), then
instructors.set() so re-runs sync instructor changes instead of
accumulating stale bindings.

Co-Authored-By: Claude Code <noreply@anthropic.com>
crawl_timetable and crawl_medians tasks are commented out, so their beat
entries dispatched to nonexistent tasks every night. Add
crawl_gc_course_offerings at 1:15AM instead; its CrawledData handler
chains the import task automatically.

Co-Authored-By: Claude Code <noreply@anthropic.com>
Without a beat process the beat_schedule never fires on production.
Enable --beat on the existing worker (solo pool, low volume) instead of
a separate container.

Co-Authored-By: Claude Code <noreply@anthropic.com>
- Syllabus gains a rejected status; the analysis task moves uploads
  whose verdict match_score is below SYLLABUS.MIN_MATCH_SCORE (60) to it
  instead of analyzed. The row is kept for audit but hidden from course
  pages (frontend filters it).
- SyllabusFile rows whose last referencing syllabus is rejected or
  deleted move to media/recycle/ via a new syllabus_files helper
  (shared files stay in place), wired through a post_delete signal so
  Django admin delete_selected recycles too.
- SyllabusDetailAPI accepts staff DELETE.
…cate teachers

GC page spellings drift across terms (case, hyphens, middle names, term/CJK
annotations, name order, nickname variants), and verbatim get_or_create(name)
silently forked one teacher into several Instructor rows on every page
rotation. Clean names at parse time (strip titles, parenthetical annotations,
CJK annotations, quotes, junk like 教师/','), split curated merged cells
('Zhaoguang Wang Ting Sun'), and resolve imports against existing Instructor
rows via exact -> letters -> word-set -> subsequence (nickname-alias aware)
matching before creating new rows.
Stale CrawledData payloads (stored before canonicalization) carry unsplit
merged cells like 'Zhaoguang Wang Ting Sun'; feeding them straight to import
let subsequence matching collapse the cell to one person (Ting Sun) and drop
the other (Zhaoguang Wang) from the offering. expand_instructor_names() now
cleans, junk-filters, splits, and resolves inside the importer, so behavior
is correct regardless of how the payload was produced.
…dule path

The ORC catalog (also gc.sjtu.edu.cn) fed instructor cells to bare
get_or_create(name), so registrar-style spellings ((Fall) annotations,
all-caps, full names) forked duplicate Instructor rows the same way GC
offerings did. Reuse the gc_offerings cleaning/resolution pipeline in
orc.py's parse and import paths.

compose: celery worker --beat runs non-root in the distroless image with an
unwritable CWD, so beat died with PermissionError on ./celerybeat-schedule;
point --schedule at /tmp so scheduled crawls actually run.
…tructors

User-submitted review professor names are now matched against the course's
canonical Instructor rows (from offerings) at write time: reversed
(Lin Zibo -> Zibo Lin), misspelled (Manuel Charlamagne -> Manuel Charlemagne),
hyphen/case, nickname, and annotated variants are auto-corrected to the
canonical spelling. Only names matching nothing are kept as their own
professor, so one teacher can never split across spellings again.

Moves the pure-string name cleaning/matching helpers out of the GC crawler
into lib/name_normalization.py (shared by spider imports, the review API, and
tests), adds an edit-distance typo rule scoped to >=5-char tokens, and wires
the course into ReviewSerializer validation (POST passes context; PUT falls
back to the review's own course).
… legacy review import

- views.py: PEP 758 syntax relied on Python 3.14; parenthesized form works on any Python 3.
- import_legacy_reviews: run legacy CSV professor names through the same course-instructor canonicalization as new review submissions, and dedupe against the database by (course, comments) so re-importing a cleaned database is a no-op instead of re-inserting variant-spelling duplicates.
except ValueError, TypeError: is Python 2 syntax that only parses on
Python 3.14+ (PEP 758); the parenthesized form is valid everywhere.
Comment thread apps/web/views.py
threshold = int(param_value)
queryset = queryset.filter(**{f"{field_name}__gte": threshold})
except ValueError, TypeError:
except (ValueError, TypeError):
@JackyTJie
JackyTJie marked this pull request as draft September 5, 2026 23:49
@JackyTJie JackyTJie closed this Sep 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant