@@ -329,14 +329,23 @@ def send(self, request: requests.Request, **kwargs) -> DetailedResponse:
329329 while response .is_redirect and response .next is not None and redirects_count < MAX_REDIRECTS :
330330 redirects_count += 1
331331
332+ if redirects_count > MAX_REDIRECTS :
333+ # Raise an error if the maximum number of redirects has been reached.
334+ raise MaxRetryError (
335+ None , response .url , reason = f'reached the maximum number of redirects: { MAX_REDIRECTS } '
336+ )
337+
332338 # urllib3 has already prepared a request that can almost be used as-is.
333339 next_request = response .next
334340
341+ from_domain = urlparse (response .request .url ).netloc
342+ to_domain = urlparse (next_request .url ).netloc
343+ same_host = from_domain == to_domain
344+ safe_domain = from_domain .endswith ('.cloud.ibm.com' ) and to_domain .endswith ('.cloud.ibm.com' )
345+
335346 # If both the original and the redirected URL are under the `.cloud.ibm.com` domain,
336347 # copy the safe headers that are used for authentication purposes,
337- if self .service_url .endswith ('.cloud.ibm.com' ) and urlparse (next_request .url ).netloc .endswith (
338- '.cloud.ibm.com'
339- ):
348+ if same_host or safe_domain :
340349 original_headers = request .get ('headers' )
341350 for header , value in original_headers .items ():
342351 if header .lower () in SAFE_HEADERS :
@@ -348,13 +357,6 @@ def send(self, request: requests.Request, **kwargs) -> DetailedResponse:
348357
349358 response = self .http_client .send (next_request , ** kwargs )
350359
351- # If we reached the max number of redirects and the last response is still a redirect
352- # stop processing the response and return an error to the user.
353- if redirects_count == MAX_REDIRECTS and response .is_redirect :
354- raise MaxRetryError (
355- None , response .url , reason = f'reached the maximum number of redirects: { MAX_REDIRECTS } '
356- )
357-
358360 # Process a "success" response.
359361 if 200 <= response .status_code <= 299 :
360362 if response .status_code == 204 or request ['method' ] == 'HEAD' :
0 commit comments