From 14710572d14a066c9edb276b86277258549d53e8 Mon Sep 17 00:00:00 2001 From: theluckystrike <51033404+theluckystrike@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:54:05 +0700 Subject: [PATCH] fix: sign a new token request when a retry replays the nonce A token request that a fallback host retries is sent with the same nonce. When the server used that nonce on an attempt whose response was lost, it rejects the retry with 40105. request_token now signs a new token request and sends it once more in that case, when the library made the nonce. Fixes #710 --- ably/pubsub/http/auth.py | 29 +++++++++++--- test/unit/token_request_nonce_test.py | 57 +++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 5 deletions(-) create mode 100644 test/unit/token_request_nonce_test.py diff --git a/ably/pubsub/http/auth.py b/ably/pubsub/http/auth.py index 372cfa2d..83bb4bb4 100644 --- a/ably/pubsub/http/auth.py +++ b/ably/pubsub/http/auth.py @@ -221,6 +221,7 @@ async def request_token(self, token_params: dict | None = None, auth_headers = auth_headers or self.auth_options.auth_headers or {} log.debug(f"Token Params: {token_params}") + signed_with_key = False if auth_callback: log.debug("using token auth with authCallback") try: @@ -239,6 +240,7 @@ async def request_token(self, token_params: dict | None = None, token_request = await self.create_token_request( token_params, key_name=key_name, key_secret=key_secret, query_time=query_time) + signed_with_key = True else: msg = "Need a new token but auth_options does not include a way to request one" log.exception(msg) @@ -263,11 +265,28 @@ async def request_token(self, token_params: dict | None = None, token_path = f"/keys/{token_request.key_name}/requestToken" - response = await self.ably.http.post( - token_path, - body=token_request.to_dict(), - skip_auth=True - ) + try: + response = await self.ably.http.post( + token_path, + body=token_request.to_dict(), + skip_auth=True + ) + except AblyException as e: + # A fallback host retry sends the same body again. When the server used the + # nonce on an attempt whose response was lost, it rejects the retry as a + # replay (40105). Sign a new token request with a new nonce and send it once more. + if not (signed_with_key and e.code == 40105 + and token_params.get('nonce') is None and token_params.get('mac') is None): + raise + log.debug("Token request nonce was replayed, sending a new token request") + token_request = await self.create_token_request( + token_params, key_name=key_name, key_secret=key_secret, + query_time=query_time) + response = await self.ably.http.post( + token_path, + body=token_request.to_dict(), + skip_auth=True + ) AblyException.raise_for_response(response) response_dict = response.to_native() diff --git a/test/unit/token_request_nonce_test.py b/test/unit/token_request_nonce_test.py new file mode 100644 index 00000000..26e46a55 --- /dev/null +++ b/test/unit/token_request_nonce_test.py @@ -0,0 +1,57 @@ +import json + +import pytest + +from ably.pubsub.util.exceptions import AblyException +from test.uts.helpers.client import rest_client +from test.uts.helpers.mock_http import MockHttpClient + +KEY = 'appId.keyId:keySecret' +REPLAYED_BODY = {'error': {'code': 40105, 'statusCode': 401, 'message': 'Nonce value replayed'}} +TOKEN_BODY = {'token': 'obtained-token', 'expires': 9999999999999, 'keyName': 'appId.keyId'} + + +def nonce_server(): + """A requestToken endpoint that uses each nonce one time only and loses the first response.""" + used_nonces = [] + + def on_request(request): + nonce = json.loads(request.body)['nonce'] + if nonce in used_nonces: + request.respond_with(401, REPLAYED_BODY) + return + used_nonces.append(nonce) + if len(used_nonces) == 1: + # The server used the nonce, but the response does not reach the client + request.respond_with_timeout() + else: + request.respond_with(200, TOKEN_BODY) + + mock_http = MockHttpClient( + on_connection_attempt=lambda conn: conn.respond_with_success(), + on_request=on_request, + ) + return mock_http, used_nonces + + +async def test_request_token_signs_a_new_nonce_after_a_replayed_retry(): + mock_http, used_nonces = nonce_server() + client = rest_client(mock_http, key=KEY, use_binary_protocol=False, + fallback_hosts=['a.example.com', 'b.example.com']) + + token_details = await client.auth.request_token() + + assert token_details.token == 'obtained-token' + assert len(used_nonces) == 2 + + +async def test_request_token_keeps_a_nonce_the_caller_gives(): + mock_http, used_nonces = nonce_server() + client = rest_client(mock_http, key=KEY, use_binary_protocol=False, + fallback_hosts=['a.example.com', 'b.example.com']) + + with pytest.raises(AblyException) as excinfo: + await client.auth.request_token({'nonce': 'fixed-nonce-value'}) + + assert excinfo.value.code == 40105 + assert used_nonces == ['fixed-nonce-value']