Skip to content

Enforce CSRF for cookie-authenticated API requests. Closes #1705 - #1778

Merged
regulartim merged 4 commits into
GreedyBear-Project:developfrom
saisiddi:csrf-cookie-auth-1705
Nov 3, 2026
Merged

regulartim merged 4 commits into
GreedyBear-Project:developfrom
saisiddi:csrf-cookie-auth-1705

Conversation

@saisiddi

@saisiddi saisiddi commented Oct 20, 2026 •

Copy link
Copy Markdown

Description

Cookie-authenticated API requests had no CSRF protection, only SameSite=Strict on the auth cookie (see #1705). This PR adds a CSRF check for those requests, as discussed in the issue.

  • New CSRFProtectedCookieTokenAuthentication in api/authentication.py. It runs Django's CSRF check only when the token came from the cookie and the method is not safe (POST/PUT/PATCH/DELETE). Clients using Authorization: Token (sensors, scripts) are not affected.
  • It replaces CookieTokenAuthentication in the DRF default and in every view that set it explicitly. LogoutView and APIAccessTokenView come from durin, so I added small local subclasses for them.
  • check_authentication now calls get_token(), so the frontend gets the csrftoken cookie on page load.
  • CSRF_COOKIE_HTTPONLY is now False (option 1 from the issue), so axios can read the cookie. Django's docs say HttpOnly on this cookie gives no real protection, since XSS can already make same-origin requests.
  • The frontend uses axios's built-in xsrfCookieName / xsrfHeaderName, so no interceptor was needed.

Two things to check:

  • DashboardConfigView had SessionAuthentication as a second class, but it never ran because the cookie class always succeeds first. I removed it. This only affects a superuser logged in only through a Django session (no token cookie) calling this API directly, which the frontend never does.
  • The include("certego_saas.apps.auth.urls") in authentication/urls.py is now fully shadowed, since login and logout both have local routes. I left it to keep this PR small. Should I remove it here or in a follow-up?

Testing

I tested it through nginx (http://localhost), not only the dev server:

Test Result
Log in works
csrftoken cookie set yes
Superuser opens /dashboard directly and saves the config 200, request has X-CSRFToken
Create / delete API token 201 / 204
Change password works
Log out works
Same request with the cookie but without X-CSRFToken 403 CSRF Failed: CSRF token missing.
POST with only Authorization: Token 200

I also added tests/authentication/test_csrf_cookie_auth.py (5 tests, using APIClient(enforce_csrf_checks=True) and a real auth cookie, since the existing tests use force_authenticate and never run the authentication class).

Related issues

Closes #1705
Follows from Discussion #1693

Type of change

  • Bug fix (non-breaking change which fixes an issue).
  • New feature (non-breaking change which adds functionality).
  • Breaking change (fix or feature that would cause existing functionality to not work as expected).
  • Chore (refactoring, dependency updates, CI/CD changes, code cleanup, docs-only changes).

Checklist

Formalities

  • I have read and understood the rules about how to Contribute to this project.
  • I chose an appropriate title for the pull request in the form: <feature name>. Closes #999
  • My branch is based on develop.
  • The pull request is for the branch develop.
  • I have reviewed and verified any LLM-generated code included in this PR.

Docs and tests

  • I documented my code changes with docstrings and/or comments.
  • I have checked if my changes affect user-facing behavior that is described in the docs. If so, I also included an update to the wiki in the description of this PR.
  • Linter (Ruff) gave 0 errors.
  • I have added tests for the feature/bug I solved.
  • All the tests gave 0 errors.

GUI changes

No visible UI changes. Only the axios defaults in index.jsx changed; frontend tests pass.

@saisiddi

Copy link
Copy Markdown
Author

@regulartim Plz take a look!

@saisiddi

Copy link
Copy Markdown
Author

Hello @regulartim I know you will be busy, if you have time, plz take a look at it!

@regulartim regulartim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hey @saisiddi , good work! 👍

DashboardConfigView had SessionAuthentication as a second class, but it never ran because the cookie class always succeeds first. I removed it. This only affects a superuser logged in only through a Django session (no token cookie) calling this API directly, which the frontend never does.

Should be fine! :)

The include("certego_saas.apps.auth.urls") in authentication/urls.py is now fully shadowed, since login and logout both have local routes. I left it to keep this PR small. Should I remove it here or in a follow-up?

I think the question here is a different one: do we need the new LogoutView / APIAccessTokenView subclasses and the logout route? Durin's views should pic up DEFAULT_AUTHENTICATION_CLASSES, which you already changed. Then, of course, we still need certego_saas.apps.auth.urls. Can you please check?

@saisiddi

Copy link
Copy Markdown
Author

You're right, durin's views don't set authentication_classes, so they already pick up the new default. I removed the two subclasses and the extra logout route, and kept certego_saas.apps.auth.urls. Checked locally: a cookie POST to /api/auth/logout and /api/auth/apiaccess without X-CSRFToken still gets 403, and with the token it works.

@saisiddi
saisiddi requested a review from regulartim October 27, 2026 14:12

@regulartim regulartim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @saisiddi ! :)

I found another issue while testing: normal, non-superuser users get a 403 on their first unsafe request after logging in. I created such a user, logged in at the frontend, clicked "log out" and immediately got a toast that it failed (forgot what the toast said). My guess is that that it does not receive an CSRF cookie. Can you check and add a test for non-superusers?

Maybe a @ensure_csrf_cookie decorator on render_reactapp in greedybear/urls.py could resolve the issue?

@saisiddi
saisiddi force-pushed the csrf-cookie-auth-1705 branch from 7992f3e to 45f8ca6 Compare November 2, 2026 15:05
@saisiddi

saisiddi commented Nov 2, 2026

Copy link
Copy Markdown
Author

Good catch, thanks! @regulartim The cause: on first load the user is anonymous, so check_authentication returns 401 before get_token() runs. At login, only superusers get a csrftoken cookie, through Django's login() -> rotate_token(). Normal users had no cookie until the 403 interceptor triggered another check_authentication, which is why only the first unsafe request failed. My tests missed it because they only used a superuser.

Fix:

  • @ensure_csrf_cookie on render_reactapp, as you suggested.
  • get_token() in LoginView.post for every user, so it also works when the HTML isn't served by Django (the Vite dev server only proxies /api).
  • Removed the get_token() call from check_authentication, since it never ran for anonymous users and the two changes above cover it.

Added tests with a non-superuser: the login response sets the cookie, logout with the token returns 204, and without it 403. I also checked it manually through nginx with a normal user: csrftoken is set on the first page load, and logout works. Rebased on develop and resolved the conflicts with QueryParamValidationMixin.

@saisiddi
saisiddi requested a review from regulartim November 2, 2026 15:43

@regulartim regulartim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hey @saisiddi ! Good job, thank you! :)

@regulartim
regulartim merged commit d757d99 into GreedyBear-Project:develop Nov 3, 2026
8 checks passed
@saisiddi
saisiddi deleted the csrf-cookie-auth-1705 branch November 3, 2026 16:28
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.

2 participants