|
2 | 2 | import string
|
3 | 3 |
|
4 | 4 | import pytest
|
| 5 | +from django.contrib.auth.hashers import make_password |
5 | 6 | from django.core.exceptions import ValidationError
|
6 | 7 | from django.db.utils import IntegrityError
|
7 | 8 | from test_project.heroes.models import Hero, HeroAPIKey
|
@@ -65,6 +66,29 @@ def test_custom_api_key_model() -> None:
|
65 | 66 | assert hero.api_keys.first() == hero_api_key
|
66 | 67 |
|
67 | 68 |
|
| 69 | +@pytest.mark.django_db |
| 70 | +def test_api_key_hash_upgrade() -> None: |
| 71 | + """Tests the hashing algo upgrade from Django's PW hashers to sha512.""" |
| 72 | + key_generator = APIKey.objects.key_generator |
| 73 | + |
| 74 | + api_key, generated_key = APIKey.objects.create_key(name="test") |
| 75 | + assert api_key.is_valid(generated_key) |
| 76 | + assert key_generator.using_preferred_hasher(api_key.hashed_key) |
| 77 | + |
| 78 | + # Use Django's built-in hashers, the old way of storing a key |
| 79 | + api_key.hashed_key = make_password(generated_key) |
| 80 | + api_key.save() |
| 81 | + |
| 82 | + # Simple sanity check to ensure the hash is still being checked |
| 83 | + # and that we aren't using the preferred hasher (using Django's slower hashers) |
| 84 | + assert not api_key.is_valid(key_generator.hash("invalid-key")) |
| 85 | + assert not key_generator.using_preferred_hasher(api_key.hashed_key) |
| 86 | + |
| 87 | + # After calling `is_valid`, the key has been upgraded to use the preferred hasher |
| 88 | + assert api_key.is_valid(generated_key) |
| 89 | + assert key_generator.using_preferred_hasher(api_key.hashed_key) |
| 90 | + |
| 91 | + |
68 | 92 | @pytest.mark.django_db
|
69 | 93 | def test_api_key_manager_get_from_key() -> None:
|
70 | 94 | api_key, generated_key = APIKey.objects.create_key(name="test")
|
|
0 commit comments