|
2 | 2 | from pathlib import Path, PurePath |
3 | 3 | from threading import Event, Lock, Thread |
4 | 4 |
|
| 5 | +import time |
| 6 | +from datetime import timedelta |
| 7 | + |
5 | 8 | import pytest |
6 | 9 | import json |
7 | 10 | import jwt |
@@ -308,6 +311,7 @@ def test_call_propagates_token_refresh_failure(self, refresh_already_failed): |
308 | 311 | auth.refresh_token = jwt.encode({"exp": 4_000_000_000}, "x" * 32, algorithm="HS256") |
309 | 312 | auth.token_endpoint = KeyAuth.DEFAULT_TOKEN_ENDPOINT |
310 | 313 | auth.refresh_future = None |
| 314 | + auth._stop = Event() |
311 | 315 | original_token = auth.access_token |
312 | 316 | request = Request("GET", "https://example.com") |
313 | 317 | refresh_error = requests.RequestException("refresh failed") |
@@ -382,3 +386,90 @@ def result(self): |
382 | 386 |
|
383 | 387 | assert not call_thread.is_alive() |
384 | 388 | assert request.headers["Authorization"] == f"Bearer {fresh_token}" |
| 389 | + |
| 390 | + |
| 391 | +class TestKeyAuthClose: |
| 392 | + """A discarded KeyAuth must be able to stop its background token refresh.""" |
| 393 | + |
| 394 | + @staticmethod |
| 395 | + def _make_auth(service_account_key_file_json, mock_post, access_token): |
| 396 | + service_account_key = ServiceAccountKey.model_validate_json(service_account_key_file_json) |
| 397 | + service_account_key.credentials.private_key = "test-private-key" |
| 398 | + response = Mock() |
| 399 | + response.raise_for_status.return_value = None |
| 400 | + response.json.return_value = { |
| 401 | + "access_token": access_token, |
| 402 | + "refresh_token": jwt.encode({"exp": 4102444800}, "secret", algorithm="HS256"), |
| 403 | + } |
| 404 | + mock_post.return_value = response |
| 405 | + return KeyAuth(service_account_key) |
| 406 | + |
| 407 | + def test_close_stops_the_refresh_thread_and_further_token_requests(self, service_account_key_file_json): |
| 408 | + def set_initial_token(auth): |
| 409 | + auth.initial_token = "test-initial-token" |
| 410 | + |
| 411 | + expired = jwt.encode({"exp": 1}, "secret", algorithm="HS256") |
| 412 | + with ( |
| 413 | + patch.object(KeyAuth, "_KeyAuth__create_initial_token", new=set_initial_token), |
| 414 | + patch.object(KeyAuth, "TOKEN_EXPIRY_CHECK_INTERVAL", timedelta(milliseconds=10)), |
| 415 | + patch("requests.post") as mock_post, |
| 416 | + ): |
| 417 | + # An access token that is always expired keeps the refresh loop busy. |
| 418 | + auth = self._make_auth(service_account_key_file_json, mock_post, expired) |
| 419 | + thread = auth._refresh_thread |
| 420 | + assert thread is not None and thread.is_alive() |
| 421 | + |
| 422 | + auth.close() |
| 423 | + |
| 424 | + assert not thread.is_alive() |
| 425 | + requests_after_close = mock_post.call_count |
| 426 | + time.sleep(0.1) # ten refresh intervals |
| 427 | + assert mock_post.call_count == requests_after_close |
| 428 | + |
| 429 | + def test_close_waits_for_a_refresh_in_progress(self, service_account_key_file_json): |
| 430 | + def set_initial_token(auth): |
| 431 | + auth.initial_token = "test-initial-token" |
| 432 | + |
| 433 | + expired = jwt.encode({"exp": 1}, "secret", algorithm="HS256") |
| 434 | + refresh_started = Event() |
| 435 | + with ( |
| 436 | + patch.object(KeyAuth, "_KeyAuth__create_initial_token", new=set_initial_token), |
| 437 | + patch.object(KeyAuth, "TOKEN_EXPIRY_CHECK_INTERVAL", timedelta(milliseconds=10)), |
| 438 | + patch("requests.post") as mock_post, |
| 439 | + ): |
| 440 | + auth = self._make_auth(service_account_key_file_json, mock_post, expired) |
| 441 | + initial_response = mock_post.return_value |
| 442 | + |
| 443 | + def slow_refresh(*args, **kwargs): |
| 444 | + refresh_started.set() |
| 445 | + time.sleep(0.2) |
| 446 | + return initial_response |
| 447 | + |
| 448 | + mock_post.side_effect = slow_refresh |
| 449 | + assert refresh_started.wait(timeout=5) |
| 450 | + |
| 451 | + auth.close() |
| 452 | + |
| 453 | + assert auth.refresh_future is not None and auth.refresh_future.done() |
| 454 | + requests_after_close = mock_post.call_count |
| 455 | + time.sleep(0.1) |
| 456 | + assert mock_post.call_count == requests_after_close |
| 457 | + |
| 458 | + def test_close_is_idempotent(self, service_account_key_file_json): |
| 459 | + def set_initial_token(auth): |
| 460 | + auth.initial_token = "test-initial-token" |
| 461 | + |
| 462 | + valid = jwt.encode({"exp": 4102444800}, "secret", algorithm="HS256") |
| 463 | + with ( |
| 464 | + patch.object(KeyAuth, "_KeyAuth__create_initial_token", new=set_initial_token), |
| 465 | + patch("requests.post") as mock_post, |
| 466 | + patch("stackit.core.auth_methods.key_auth.atexit") as mock_atexit, |
| 467 | + ): |
| 468 | + auth = self._make_auth(service_account_key_file_json, mock_post, valid) |
| 469 | + |
| 470 | + auth.close() |
| 471 | + auth.close() |
| 472 | + |
| 473 | + assert not auth._refresh_thread.is_alive() |
| 474 | + assert auth.executor._shutdown |
| 475 | + mock_atexit.unregister.assert_called_with(auth._KeyAuth__shutdown) |
0 commit comments