-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Prevent small risk of Token overwrite
#9754
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
auvipy
merged 9 commits into
encode:master
from
mahdirahimi1999:fix-token-overwrite-9250
Aug 10, 2025
Merged
Changes from 2 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d381901
Fix #9250: Prevent token overwrite and improve security
mahdirahimi1999 06b0441
Fix code style: remove trailing whitespace and unused imports
mahdirahimi1999 705fc2b
Fix #9250: Prevent token overwrite with minimal changes
mahdirahimi1999 15a2164
Fix flake8 violations: remove extra blank lines and trailing whitespace
mahdirahimi1999 621968d
Update tests/test_authtoken.py
mahdirahimi1999 a720d71
Update tests/test_authtoken.py
mahdirahimi1999 bf3a782
Update tests/test_authtoken.py
mahdirahimi1999 e515e23
Fix token key regeneration behavior and add test
mahdirahimi1999 ae6161a
Update tests/test_authtoken.py
mahdirahimi1999 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,12 @@ | ||
| import importlib | ||
| from io import StringIO | ||
| from unittest import mock | ||
|
|
||
| import pytest | ||
| from django.contrib.admin import site | ||
| from django.contrib.auth.models import User | ||
| from django.core.management import CommandError, call_command | ||
| from django.db import IntegrityError | ||
| from django.test import TestCase, modify_settings | ||
|
|
||
| from rest_framework.authtoken.admin import TokenAdmin | ||
|
|
@@ -19,8 +21,13 @@ class AuthTokenTests(TestCase): | |
|
|
||
| def setUp(self): | ||
| self.site = site | ||
| self.user = User.objects.create_user(username='test_user') | ||
| self.token = Token.objects.create(key='test token', user=self.user) | ||
| # CORRECTED: Only create the user. Each test will now create its own | ||
| # token(s) to ensure proper test isolation. | ||
mahdirahimi1999 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self.user = User.objects.create_user( | ||
| username='test_user', | ||
| email='[email protected]', | ||
| password='password' | ||
| ) | ||
|
|
||
| def test_authtoken_can_be_imported_when_not_included_in_installed_apps(self): | ||
| import rest_framework.authtoken.models | ||
|
|
@@ -31,12 +38,16 @@ def test_authtoken_can_be_imported_when_not_included_in_installed_apps(self): | |
| importlib.reload(rest_framework.authtoken.models) | ||
|
|
||
| def test_model_admin_displayed_fields(self): | ||
| # Create a token specifically for this test. | ||
| token = Token.objects.create(user=self.user) | ||
| mock_request = object() | ||
| token_admin = TokenAdmin(self.token, self.site) | ||
| token_admin = TokenAdmin(token, self.site) | ||
| assert token_admin.get_fields(mock_request) == ('user',) | ||
|
|
||
| def test_token_string_representation(self): | ||
| assert str(self.token) == 'test token' | ||
| # Create a token with a known key specifically for this test. | ||
| token = Token.objects.create(key='test token', user=self.user) | ||
| assert str(token) == 'test token' | ||
|
|
||
| def test_validate_raise_error_if_no_credentials_provided(self): | ||
| with pytest.raises(ValidationError): | ||
|
|
@@ -48,6 +59,68 @@ def test_whitespace_in_password(self): | |
| self.user.save() | ||
| assert AuthTokenSerializer(data=data).is_valid() | ||
|
|
||
| # --- Tests for Issue #9250 and secrets module refactor --- | ||
mahdirahimi1999 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def test_token_string_representation_is_randomly_generated_key(self): | ||
| """ | ||
| Ensure the string representation of a token is its key when auto-generated. | ||
| """ | ||
| token = Token.objects.create(user=self.user) | ||
| self.assertEqual(str(token), token.key) | ||
mahdirahimi1999 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def test_token_creation_collision_raises_integrity_error(self): | ||
| """ | ||
| Verify that creating a token with an existing key raises IntegrityError. | ||
| """ | ||
mahdirahimi1999 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| user2 = User.objects.create_user('user2', '[email protected]', 'p') | ||
| existing_token = Token.objects.create(user=user2) | ||
|
|
||
| # Try to create another token with the same key | ||
| with self.assertRaises(IntegrityError): | ||
| Token.objects.create(key=existing_token.key, user=self.user) | ||
|
|
||
| def test_key_regeneration_on_save_is_not_a_breaking_change(self): | ||
| """ | ||
| Verify that when a token is created without a key, it generates one correctly. | ||
| This tests the backward compatibility scenario where existing code might | ||
| create tokens without explicitly setting a key. | ||
| """ | ||
mahdirahimi1999 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # Create a token without a key - it should generate one automatically | ||
| token = Token(user=self.user) | ||
| token.key = "" # Explicitly clear the key | ||
| token.save() | ||
|
|
||
| # Verify the key was generated | ||
| self.assertEqual(len(token.key), 40) | ||
| self.assertEqual(token.user, self.user) | ||
|
|
||
| # Verify it's saved in the database | ||
| token.refresh_from_db() | ||
| self.assertEqual(len(token.key), 40) | ||
| self.assertEqual(token.user, self.user) | ||
|
|
||
| def test_saving_existing_token_without_changes_does_not_alter_key(self): | ||
| """ | ||
| Ensure that calling save() on an existing token without modifications | ||
| does not change its key. | ||
| """ | ||
mahdirahimi1999 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| token = Token.objects.create(user=self.user) | ||
| original_key = token.key | ||
|
|
||
| token.save() | ||
| self.assertEqual(token.key, original_key) | ||
|
|
||
| def test_generate_key_uses_secrets_module(self): | ||
| """ | ||
| Verify that `generate_key` correctly calls `secrets.token_hex`. | ||
| """ | ||
| with mock.patch('rest_framework.authtoken.models.secrets.token_hex') as mock_token_hex: | ||
| mock_token_hex.return_value = 'a_mocked_key_of_proper_length_0123456789' | ||
| key = Token.generate_key() | ||
|
|
||
| mock_token_hex.assert_called_once_with(20) | ||
| self.assertEqual(key, 'a_mocked_key_of_proper_length_0123456789') | ||
|
|
||
|
|
||
| class AuthTokenCommandTests(TestCase): | ||
|
|
||
|
|
||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.