Repository navigation
refactor: enhance file auth cookie handling for cross-site HTTPS support - #8201
Conversation
| cookie = response.cookies[FILE_AUTH_COOKIE] | ||
| self.assertEqual(cookie["max-age"], 0) | ||
| self.assertTrue(cookie["secure"]) | ||
| self.assertEqual(cookie["samesite"], "None") |
There was a problem hiding this comment.
No syntax problems are obvious from the diff, but there are several security, correctness, and test-quality concerns.
Main concerns
-
Trusting
X-Forwarded-Protodirectly is risky- The test simulates HTTPS only by setting
HTTP_X_FORWARDED_PROTO="https". - If production code reads that header directly, clients may spoof it unless the app is strictly behind a trusted proxy.
- Prefer Django’s
request.is_secure()together withSECURE_PROXY_SSL_HEADER, e.g.:or test direct HTTPS with@override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))secure=True. - Also handle multi-value headers such as
https,httpcorrectly if you keep manual parsing.
- The test simulates HTTPS only by setting
-
Cookie deletion must match the original cookie’s
pathanddomain- The logout test checks
max-age,secure, andsamesite, but notpathordomain. - The login test sets
path="/chat/portal". If logout deletes the cookie with a different path, the browser will not clear it. - Add assertions for
path,domain, and ideallyexpiresin the logout test. - Better: centralize cookie attribute generation so login and logout cannot diverge.
- The logout test checks
-
SameSite=Nonemust never be emitted withoutSecure- The positive HTTPS test is useful, but add a negative test for plain HTTP.
- Ensure the fallback is something like
SameSite=LaxandSecure=Falsewhen HTTPS is not detected.
-
SimpleTestCasemay be too restrictiveSimpleTestCaseforbids database access. IfLogoutperforms any unpatched DB/cache/log operation, the test will fail.- Patching only
cache.deleteandcommon.log.log.Log.savemay be too narrow. If the view usesLog.objects.create, async logging, or another cache method, the patch will not cover it. - Consider using
TestCaseif database behavior is relevant, or patch exactly what the view calls.
-
force_authenticatewithSimpleNamespacemay be incomplete- If any permission class checks
request.user.is_authenticated,SimpleNamespacewill raiseAttributeErrorunless you include:is_authenticated=True
- Safer to use a proper user object or a
Mockwith the required attributes.
- If any permission class checks
Test-quality issues
-
Patched calls are not asserted
- The logout test patches
cache.deleteandLog.savebut never asserts they were called. - A regression where logout stops invalidating the token would not be caught.
- Use
assert_called_once_with(...)where possible.
- The logout test patches
-
Login test does not exercise the login endpoint
test_file_auth_cookie_supports_cross_site_https_logincallsgenerate()directly, not the actual login view.- That tests the helper but not whether the login endpoint uses it correctly.
- Consider adding an integration-style test through the login view.
-
Missing
HttpOnly/ security-attribute assertions- Authentication-related cookies should usually be
HttpOnly. - Add assertions for
httponly,path, anddomainif those attributes are part of the intended contract.
- Authentication-related cookies should usually be
Minor suggestions
-
Avoid importing
FILE_AUTH_COOKIEfrom the view module- Better to define shared cookie constants in a constants module. Importing from
chat.views.v3.chatcouples tests to a view module and can create circular-import risk.
- Better to define shared cookie constants in a constants module. Importing from
-
Avoid
accessTokenin the query string- The logout URL includes
?accessToken=access-token. Query-string tokens can leak through logs, proxies, and referrers. - If production still supports this, consider deprecating it in favor of
Authorizationor request-body credentials.
- The logout URL includes
-
The cookie assertions are only partially verifying behavior
cookie["max-age"]may be represented as an integer or string depending on how it is set. If you see fragility, compare against the exact expected representation or use Django’s cookie helpers.
Overall: the tests add useful coverage, but they should be hardened around proxy-header trust, cookie path/domain consistency, negative HTTP cases, and mock verification.
| auth = request.META.get("HTTP_AUTHORIZATION") | ||
| cache.delete(get_key(token=auth[7:]), version=version) | ||
| return clear_file_auth_cookie(result.success(True), request.query_params.get("accessToken")) | ||
| return clear_file_auth_cookie(request, result.success(True), request.query_params.get("accessToken")) |
There was a problem hiding this comment.
Here is an analysis of the provided code changes, highlighting potential issues and optimization suggestions:
1. Critical Issue: Secure Flag Mismatch in Cookie Deletion
Location: clear_file_auth_cookie function.
-
Problem: The
response.delete_cookiemethod removes a cookie by setting it with an expiration date in the past. For the browser to successfully remove a cookie, the attributes (specificallydomain,path, and criticallysecure) must match those used when the cookie was originally set. -
Inconsistency: In the
generatemethod (where the cookie is likely set), the code dynamically setssamesite="None" if secure else "Lax". However, it does not explicitly show thesecureparameter being passed toset_cookie. If the originalset_cookiecall usessecure=secure(which is standard practice whensamesite='None'is required for cross-site or HTTPS contexts), then the deletion attempt might fail if thesecureflag is not handled consistently. -
Recommendation: Ensure that the
delete_cookiecall includessecure=secureif the original cookie was set withsecure=True. Django’sdelete_cookiesupports thesecurekeyword argument. Without matching this attribute, browsers may ignore the deletion command.# Suggested fix in clear_file_auth_cookie response.delete_cookie( FILE_AUTH_COOKIE, path=get_chat_user_cookie_path(access_token), samesite="None" if secure else "Lax", secure=secure, # Add this line to match the original cookie's secure attribute )
2. Security Consideration: Samesite="None" Requires Secure
Location: Both generate and clear_file_auth_cookie.
- Standard Compliance: Modern browsers (Chrome, Firefox, Safari) will reject cookies with
Samesite="None"if they do not also have theSecureattribute (secure=True). - Potential Bug: In
clear_file_auth_cookie, you are conditionally settingsamesite="None"based onrequest.is_secure(). Whileis_secure()checks for HTTPS, it's crucial to ensure that thesecureprotocol attribute is also explicitly set toTruein the cookie operations (both setting and deleting) wheneversamesite="None"is used. Your logic implies correctness, but explicit enforcement in the code is safer.
3. Code Clarity and Maintainability
Location: Repeated conditional logic "None" if secure else "Lax".
-
Suggestion: This conditional logic is repeated in two places (
generateandclear_file_auth_cookie). To reduce duplication and ensure consistency, define a helper function or a variable at the module level or within the class scope.def get_samesite_value(request): return "None" if request.is_secure() else "Lax" def get_secure_flag(request): return request.is_secure()
Then use these helpers in both functions:
# In generate and clear_file_auth_cookie: secure = request.is_secure() samesite = "None" if secure else "Lax"
4. API Consistency in Function Signature
Location: clear_file_auth_cookie.
- Observation: The function signature changed from
(response: HttpResponse, access_token)to(request: Request, response: HttpResponse, access_token). - Critique: Passing both
requestandresponsecan sometimes be avoided if theResponseobject already contains the context or ifrequestis accessible via middleware/context. However, in Django views, passingrequestto a helper is common. The change is acceptable and necessary here becausesecurestatus depends on therequest. Just ensure all callers (as seen in thepostmethod update) are updated correctly. - Verification: The caller in
posthas been updated correctly:return clear_file_auth_cookie(request, result.success(True), request.query_params.get("accessToken"))
5. Edge Case: Empty or Invalid access_token
Location: get_chat_user_cookie_path(access_token).
- Current Behavior:
f"/chat/{access_token or 'portal'}". Ifaccess_tokenis empty string""orNone, it defaults to/chat/portal. - Risk: When logging out (
clear_file_auth_cookie), ifaccess_tokenis fetched asrequest.query_params.get("accessToken")and it isNone, the path becomes/chat/portal. You must ensure that the original login also used/chat/portalin such cases. Mismatched paths between setting and deleting will cause the cookie to persist. - Recommendation: Verify that the cookie-setting procedure uses the exact same fallback logic for the path when the token is missing.
Summary of Recommended Actions
- Add
secure=securetoresponse.delete_cookie(...)to ensure successful cookie deletion in browsers that enforce strict attribute matching. - Refactor the
samesiteandsecuredetermination logic into a helper to avoid duplication. - Verify that the cookie path logic during logout exactly mirrors the path logic used during login, especially regarding the default
'portal'case.
refactor: enhance file auth cookie handling for cross-site HTTPS support