|
1 | 1 | """Test the API Key Manager functionality.""" |
2 | 2 |
|
| 3 | +import hashlib |
| 4 | +import hmac |
3 | 5 | from uuid import uuid4 |
4 | 6 |
|
5 | 7 | import pytest |
@@ -318,3 +320,47 @@ async def test_api_key_auth_user_not_found_in_db_no_auto_error( |
318 | 320 | auth = ApiKeyAuth(auto_error=False) |
319 | 321 | result = await auth(request=mock_req, db=test_db) |
320 | 322 | assert result is None |
| 323 | + |
| 324 | + def test_hash_key_uses_hmac(self, mocker) -> None: |
| 325 | + """Test that API key hashing uses HMAC-SHA256 with secret key.""" |
| 326 | + # Mock the settings |
| 327 | + mock_settings = mocker.patch("app.managers.api_key.get_settings") |
| 328 | + test_secret = "test_secret_key_12345" # noqa: S105 |
| 329 | + mock_settings.return_value.secret_key = test_secret |
| 330 | + |
| 331 | + test_key = "pk_test_key_123456789" |
| 332 | + result = ApiKeyManager._hash_key(test_key) |
| 333 | + |
| 334 | + # Calculate expected HMAC manually |
| 335 | + expected = hmac.new( |
| 336 | + test_secret.encode(), test_key.encode(), hashlib.sha256 |
| 337 | + ).hexdigest() |
| 338 | + |
| 339 | + assert result == expected |
| 340 | + assert len(result) == 64 # SHA256 hex digest length # noqa: PLR2004 |
| 341 | + |
| 342 | + def test_hash_key_different_secrets_different_hashes(self, mocker) -> None: |
| 343 | + """Test that different secret keys produce different hashes.""" |
| 344 | + test_key = "pk_same_key_123" |
| 345 | + |
| 346 | + # First hash with secret 1 |
| 347 | + mock_settings = mocker.patch("app.managers.api_key.get_settings") |
| 348 | + mock_settings.return_value.secret_key = "secret1" # noqa: S105 |
| 349 | + hash1 = ApiKeyManager._hash_key(test_key) |
| 350 | + |
| 351 | + # Second hash with secret 2 |
| 352 | + mock_settings.return_value.secret_key = "secret2" # noqa: S105 |
| 353 | + hash2 = ApiKeyManager._hash_key(test_key) |
| 354 | + |
| 355 | + assert hash1 != hash2 |
| 356 | + |
| 357 | + def test_hash_key_deterministic(self, mocker) -> None: |
| 358 | + """Test that the same key produces the same hash consistently.""" |
| 359 | + mock_settings = mocker.patch("app.managers.api_key.get_settings") |
| 360 | + mock_settings.return_value.secret_key = "consistent_secret" # noqa: S105 |
| 361 | + |
| 362 | + test_key = "pk_deterministic_test" |
| 363 | + hash1 = ApiKeyManager._hash_key(test_key) |
| 364 | + hash2 = ApiKeyManager._hash_key(test_key) |
| 365 | + |
| 366 | + assert hash1 == hash2 |
0 commit comments