Skip to content
This repository was archived by the owner on Nov 1, 2023. It is now read-only.

Commit 4aec5ed

Browse files
authored
CLI: Retry on connection errors while acquiring token (#2668)
While running tests we sometimes see token acquisition fail due to "Connection reset by peer". This should be retried by default.
1 parent be066bd commit 4aec5ed

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

src/cli/onefuzz/backend.py

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -208,16 +208,8 @@ def access_token_from_client_secret(self, scopes: List[str]) -> Any:
208208

209209
# try each scope until we successfully get an access token
210210
for scope in scopes:
211-
result = self.app.acquire_token_for_client(scopes=[scope])
212-
if "error" not in result:
213-
break
214-
215-
# AADSTS500011: The resource principal named ... was not found in the tenant named ...
216-
# This error is caused by a by mismatch between the identifierUr and the scope provided in the request.
217-
if "AADSTS500011" in result["error_description"]:
218-
LOGGER.warning(f"failed to get access token with scope {scope}")
219-
else:
220-
# unexpected error
211+
done, result = self.acquire_token_for_scope(self.app, scope)
212+
if done:
221213
break
222214

223215
if "error" in result:
@@ -227,6 +219,31 @@ def access_token_from_client_secret(self, scopes: List[str]) -> Any:
227219
)
228220
return result
229221

222+
def acquire_token_for_scope(
223+
self, app: msal.ConfidentialClientApplication, scope: str
224+
) -> Tuple[bool, Any]:
225+
# retry in the face of any connection errors
226+
# e.g. connection reset by peer, due to connection timeout
227+
retriesLeft = 5
228+
while True:
229+
try:
230+
result = app.acquire_token_for_client(scopes=[scope])
231+
if "error" not in result:
232+
return (True, result)
233+
234+
# AADSTS500011: The resource principal named ... was not found in the tenant named ...
235+
# This error is caused by a by mismatch between the identifierUrl and the scope provided in the request.
236+
if "AADSTS500011" in result["error_description"]:
237+
LOGGER.warning(f"failed to get access token with scope {scope}")
238+
return (False, result)
239+
else:
240+
# unexpected error
241+
return (True, result)
242+
except requests.exceptions.ConnectionError:
243+
retriesLeft -= 1
244+
if retriesLeft == 0:
245+
raise
246+
230247
def do_login(self, scopes: List[str]) -> Any:
231248
if not self.app:
232249
self.app = msal.PublicClientApplication(

0 commit comments

Comments
 (0)