Skip to content

refactor: enhance file auth cookie handling for cross-site HTTPS support - #8201

Merged
wxg0103 merged 1 commit into
v3from
pr@v3@fix_cookie
Nov 27, 2026
Merged

wxg0103 merged 1 commit into
v3from
pr@v3@fix_cookie

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

refactor: enhance file auth cookie handling for cross-site HTTPS support

cookie = response.cookies[FILE_AUTH_COOKIE]
self.assertEqual(cookie["max-age"], 0)
self.assertTrue(cookie["secure"])
self.assertEqual(cookie["samesite"], "None")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No syntax problems are obvious from the diff, but there are several security, correctness, and test-quality concerns.

Main concerns

  1. Trusting X-Forwarded-Proto directly 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 with SECURE_PROXY_SSL_HEADER, e.g.:
      @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
      or test direct HTTPS with secure=True.
    • Also handle multi-value headers such as https,http correctly if you keep manual parsing.
  2. Cookie deletion must match the original cookie’s path and domain

    • The logout test checks max-age, secure, and samesite, but not path or domain.
    • 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 ideally expires in the logout test.
    • Better: centralize cookie attribute generation so login and logout cannot diverge.
  3. SameSite=None must never be emitted without Secure

    • The positive HTTPS test is useful, but add a negative test for plain HTTP.
    • Ensure the fallback is something like SameSite=Lax and Secure=False when HTTPS is not detected.
  4. SimpleTestCase may be too restrictive

    • SimpleTestCase forbids database access. If Logout performs any unpatched DB/cache/log operation, the test will fail.
    • Patching only cache.delete and common.log.log.Log.save may be too narrow. If the view uses Log.objects.create, async logging, or another cache method, the patch will not cover it.
    • Consider using TestCase if database behavior is relevant, or patch exactly what the view calls.
  5. force_authenticate with SimpleNamespace may be incomplete

    • If any permission class checks request.user.is_authenticated, SimpleNamespace will raise AttributeError unless you include:
      is_authenticated=True
    • Safer to use a proper user object or a Mock with the required attributes.

Test-quality issues

  1. Patched calls are not asserted

    • The logout test patches cache.delete and Log.save but never asserts they were called.
    • A regression where logout stops invalidating the token would not be caught.
    • Use assert_called_once_with(...) where possible.
  2. Login test does not exercise the login endpoint

    • test_file_auth_cookie_supports_cross_site_https_login calls generate() 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.
  3. Missing HttpOnly / security-attribute assertions

    • Authentication-related cookies should usually be HttpOnly.
    • Add assertions for httponly, path, and domain if those attributes are part of the intended contract.

Minor suggestions

  1. Avoid importing FILE_AUTH_COOKIE from the view module

    • Better to define shared cookie constants in a constants module. Importing from chat.views.v3.chat couples tests to a view module and can create circular-import risk.
  2. Avoid accessToken in 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 Authorization or request-body credentials.
  3. 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.

@wxg0103
wxg0103 merged commit cf4894b into v3 Nov 27, 2026
3 of 4 checks passed
@wxg0103
wxg0103 deleted the pr@v3@fix_cookie branch November 27, 2026 06:44
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"))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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_cookie method removes a cookie by setting it with an expiration date in the past. For the browser to successfully remove a cookie, the attributes (specifically domain, path, and critically secure) must match those used when the cookie was originally set.

  • Inconsistency: In the generate method (where the cookie is likely set), the code dynamically sets samesite="None" if secure else "Lax". However, it does not explicitly show the secure parameter being passed to set_cookie. If the original set_cookie call uses secure=secure (which is standard practice when samesite='None' is required for cross-site or HTTPS contexts), then the deletion attempt might fail if the secure flag is not handled consistently.

  • Recommendation: Ensure that the delete_cookie call includes secure=secure if the original cookie was set with secure=True. Django’s delete_cookie supports the secure keyword 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 the Secure attribute (secure=True).
  • Potential Bug: In clear_file_auth_cookie, you are conditionally setting samesite="None" based on request.is_secure(). While is_secure() checks for HTTPS, it's crucial to ensure that the secure protocol attribute is also explicitly set to True in the cookie operations (both setting and deleting) whenever samesite="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 (generate and clear_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 request and response can sometimes be avoided if the Response object already contains the context or if request is accessible via middleware/context. However, in Django views, passing request to a helper is common. The change is acceptable and necessary here because secure status depends on the request. Just ensure all callers (as seen in the post method update) are updated correctly.
  • Verification: The caller in post has 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'}". If access_token is empty string "" or None, it defaults to /chat/portal.
  • Risk: When logging out (clear_file_auth_cookie), if access_token is fetched as request.query_params.get("accessToken") and it is None, the path becomes /chat/portal. You must ensure that the original login also used /chat/portal in 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

  1. Add secure=secure to response.delete_cookie(...) to ensure successful cookie deletion in browsers that enforce strict attribute matching.
  2. Refactor the samesite and secure determination logic into a helper to avoid duplication.
  3. Verify that the cookie path logic during logout exactly mirrors the path logic used during login, especially regarding the default 'portal' case.

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