Logging in failed once with a CSRF error and succeeded on retry.
`_csrf_tokens_match` validates the user id embedded in the token against
the current request's user. A browser holding a token bound to user N,
whose server-side session is gone (container restart, session expiry,
Redis flush), makes an anonymous login POST. N != None, so the request is
rejected. The rejection response then rotates the cookie, which is why the
second attempt works.
Keep the double-submit check and the cookie/header user agreement
unconditionally, and enforce the caller binding only when there is a
caller. An anonymous request cannot be forged this way regardless: an
attacker cannot read the cookie cross-origin, so it cannot produce the
matching header.
This is the mirror of #3420, which fixed the authenticated direction by
rotating the cookie on safe requests. That path is untouched here, and
test_authenticated_user_binding_still_enforced pins it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
ASGI spec only allows headers on the http.response.start message;
appending Set-Cookie to body messages is out-of-spec and may break on
some servers. Early-return for non-start messages.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>