Skip to content

fix: CSRF handshake and Referer header for Django 4+ HTTPS session auth - #125

Merged
ormsbee merged 3 commits into
openedx:masterfrom
mitodl:fix/csrf-https-auth
Jul 25, 2026
Merged

fix: CSRF handshake and Referer header for Django 4+ HTTPS session auth#125
ormsbee merged 3 commits into
openedx:masterfrom
mitodl:fix/csrf-https-auth

Conversation

@blarghmatey

Copy link
Copy Markdown
Contributor

Summary

xqueue-watcher authenticates against a DRF-backed xqueue endpoint via session
cookies. Two bugs in _login() caused persistent 403 responses for
put_result in production after upgrading to Django 4+/5+:

1. No CSRF token on put_result POST

_login() posted credentials directly without first obtaining a CSRF cookie.
The session therefore had no X-CSRFToken header, and DRF's
SessionAuthentication.enforce_csrf() rejected every subsequent put_result
POST with 403.

Fix: GET /xqueue/login/ before posting credentials.
openedx/edx-submissions#352
exposes a GET handler on the login endpoint for this purpose — it calls
get_token(request) which ensures Django sets the csrftoken cookie in the
response. After login, the CSRF token is persisted in session.headers so
every subsequent mutating request automatically includes X-CSRFToken.

Older deployments that only accept POST will return 405; we log and proceed
since the login POST is AllowAny and therefore CSRF-exempt.

Stale session cookies are cleared before the GET so the request arrives as an
anonymous user and receives a fresh cookie.

2. Missing Referer header on HTTPS POST (Django 4+ regression)

Django 4+ adds an extra check in CsrfViewMiddleware.process_view(): for
HTTPS POST requests with no HTTP_ORIGIN header it calls _check_referer()
which raises REASON_NO_REFERER if HTTP_REFERER is absent — before the
CSRF token is even checked. requests.Session does not add Referer
automatically, so all put_result POSTs failed this check even when the CSRF
token was correct.

Fix: after a successful login, store Referer: <xqueue_server> in the
session headers. All subsequent POSTs to the same server pass Django's
_check_referer() without any per-call plumbing.

The two fixes together fully resolve the production failure mode:

GET  /xqueue/login/           → 200 + csrftoken cookie
POST /xqueue/login/           → 200 (Referer + X-CSRFToken on this request)
# session headers now contain: Referer, X-CSRFToken
POST /xqueue/put_result/      → 200 ✓

Also in this PR

  • _request() now treats 401 and 403 as authentication failures and
    re-authenticates, matching the behaviour for 301/302 redirects. DRF returns
    these directly rather than redirecting to the login page.
  • A reauthenticated guard prevents infinite login storms on persistent
    failures.
  • New unit tests cover every part of the CSRF handshake, the Referer
    persistence, and the 403→reauth→retry cycle. All 21 tests pass.

Related

Test plan

  • All 21 unit tests pass: python -m pytest tests/test_xqueue_client.py -v
  • Deploy to a Django 4+/5+ xqueue deployment and confirm put_result no longer returns 403

🤖 Generated with Claude Code

blarghmatey and others added 2 commits June 29, 2026 12:01
DRF-based xqueue deployments (e.g. edx-submissions) return 401/403
when a session is missing or expired rather than issuing a redirect to
the login page.  Previously the watcher would treat these as fatal
errors and stop processing.

Changes:
- Extend the auth-failure branch to cover 401 and 403 in addition to
  the existing 301/302 redirect handling.
- Add a `reauthenticated` guard so a persistent auth failure (e.g.
  wrong credentials) causes one clean error rather than a login storm.
- Include the response body in the unexpected-status error message to
  aid debugging.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
xqueue-watcher authenticates via session cookies against a DRF-backed
xqueue endpoint.  Two failures caused persistent 403s in production:

1. No CSRF token on put_result POST
   xqueue-watcher's _login() POSTed credentials without first obtaining
   a CSRF cookie, so the session CSRF token was never set.  Subsequent
   put_result POSTs arrived with no X-CSRFToken header and DRF's
   SessionAuthentication.enforce_csrf() rejected them with 403.

   Fix: GET /xqueue/login/ before POSTing credentials.
   edx-submissions now exposes GET on this endpoint for exactly this
   purpose (openedx/edx-submissions#352).  Older deployments that only
   accept POST return 405; we log and proceed since the login POST is
   AllowAny and therefore CSRF-exempt.

   After login, persist the CSRF token in the session headers so every
   subsequent mutating request automatically includes X-CSRFToken.  Also
   clear any stale session cookies before the GET so the request arrives
   as an anonymous user and receives a fresh CSRF cookie.

2. Missing Referer header on HTTPS POST
   Django 4+ enforces an additional check on HTTPS POST requests: if
   the request has neither an Origin nor a Referer header, it returns 403
   (REASON_NO_REFERER) even when the CSRF token itself is correct.
   requests.Session does not set Referer automatically.

   Fix: after a successful login, store Referer: <xqueue_server> in the
   session headers.  All subsequent POSTs to the same server then pass
   Django's _check_referer() without any per-call plumbing.

Both fixes are validated by new unit tests covering the full CSRF
handshake, the Referer persistence, and the 403→reauth→retry cycle.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@openedx-webhooks openedx-webhooks added the open-source-contribution PR author is not from Axim or 2U label Jun 29, 2026
@openedx-webhooks

Copy link
Copy Markdown

Thanks for the pull request, @blarghmatey!

This repository is currently unmaintained.

🔘 Find a technical reviewer To get help with finding a technical reviewer, reach out to the community contributions project manager for this PR:
  1. On the right-hand side of the PR, find the Contributions project, click the caret in the top right corner to expand it, and check the "Primary PM" field for the name of your project manager.
  2. Find their GitHub handle here.

Once you've gone through the following steps feel free to tag them in a comment and let them know that your changes are ready for engineering review.

🔘 Get product approval

If you haven't already, check this list to see if your contribution needs to go through the product review process.

  • If it does, you'll need to submit a product proposal for your contribution, and have it reviewed by the Product Working Group.
    • This process (including the steps you'll need to take) is documented here.
  • If it doesn't, simply proceed with the next step.
🔘 Provide context

To help your reviewers and other members of the community understand the purpose and larger context of your changes, feel free to add as much of the following information to the PR description as you can:

  • Dependencies

    This PR must be merged before / after / at the same time as ...

  • Blockers

    This PR is waiting for OEP-1234 to be accepted.

  • Timeline information

    This PR must be merged by XX date because ...

  • Partner information

    This is for a course on edx.org.

  • Supporting documentation
  • Relevant Open edX discussion forum threads
🔘 Get a green build

If one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green.

Details
Where can I find more information?

If you'd like to get more details on all aspects of the review process for open source pull requests (OSPRs), check out the following resources:

When can I expect my changes to be merged?

Our goal is to get community contributions seen and reviewed as efficiently as possible.

However, the amount of time that it takes to review and merge a PR can vary significantly based on factors such as:

  • The size and impact of the changes that it introduces
  • The need for product review
  • Maintenance status of the parent repository

💡 As a result it may take up to several weeks or months to complete a review and merge your PR.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes session-cookie authentication failures against a DRF-backed xqueue on Django 4+/5+ by implementing a CSRF “prefetch” handshake and ensuring HTTPS POSTs include a Referer, then adding retry logic for 401/403 responses.

Changes:

  • Add a GET-before-POST login flow to obtain/persist CSRF cookies and set X-CSRFToken for subsequent mutating requests.
  • Persist a Referer header in the session to satisfy Django 4+ HTTPS CSRF referer checks.
  • Treat 401/403 as auth failures in _request() with a one-time reauth guard; expand unit tests to cover the new handshake and retry behavior.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
xqueue_watcher/client.py Adds CSRF prefetch + persisted Referer/X-CSRFToken, and reauth-on-401/403 with loop-guarding.
tests/test_xqueue_client.py Extends the mock session and adds tests covering CSRF/Referer persistence and 401/403 reauth retry behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread xqueue_watcher/client.py Outdated
Comment thread xqueue_watcher/client.py Outdated
Comment thread tests/test_xqueue_client.py
- Truncate response body in the unexpected-status error message so a
  large or sensitive HTML error page can't bloat logs.
- Fix the CSRF-prefetch comment to say "log at debug level", matching
  the actual log.debug call instead of claiming a warning.
- Tighten test_login_persists_csrf_in_session_headers so the mock only
  injects the CSRF cookie on the POST response, not the GET prefetch
  too — the old condition matched both requests and would have passed
  even if the login code stopped reading cookies set by the POST.
@blarghmatey

Copy link
Copy Markdown
Contributor Author

Addressed all 3 Copilot review comments in 87e7a99: truncated the response body in the unexpected-status error message, fixed the CSRF-prefetch comment to match the actual debug-level log call, and tightened the CSRF-persistence test's mock condition so it only fires on the login POST (not the GET prefetch too). All threads resolved, tests pass (129/129), and CI is green.

@ormsbee
ormsbee self-requested a review July 17, 2026 17:05
@ormsbee
ormsbee merged commit cd46603 into openedx:master Jul 25, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from Ready for Review to Done in Contributions Jul 25, 2026
@openedx-webhooks openedx-webhooks removed the needs reviewer assigned PR needs to be (re-)assigned a new reviewer label Jul 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

open-source-contribution PR author is not from Axim or 2U

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

5 participants