Fix race condition in OAuth2AccessToken.is_valid() causing HTTP 500 #907
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
save(update_fields=['last_used'])withQuerySet.update()to preventDatabaseErrorProblem
When multiple parallel requests authenticate with the same OAuth2 token, the Gateway crashes with:
Root cause: In
is_valid()method, there's a race condition betweenexists()check andsave()call. When concurrent requests try to updatelast_usedtimestamp on the same token:exists()→ Trueexists()→ Truesave()→ Success, row version changessave()→ Fails because Django'ssave(update_fields=...)expects to affect exactly 1 row, but the row was already modifiedSolution
Replace:
With:
QuerySet.update()is atomic and simply returns 0 if no rows match, without raising an exception. This is the expected behavior for updatinglast_used— if the token was deleted between validation and update, we don't need to error out.Test plan