Skip to content
This repository has been archived by the owner on Nov 5, 2019. It is now read-only.

Force GCE metadata querying to be done without proxies #120

Closed
wants to merge 9 commits into from
3 changes: 2 additions & 1 deletion oauth2client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -941,8 +941,9 @@ def _detect_gce_environment(urlopen=None):
# could lead to false negatives in the event that we are on GCE, but
# the metadata resolution was particularly slow. The latter case is
# "unlikely".
no_proxy_conf = urllib.request.build_opener(urllib.request.ProxyHandler({}))
try:
response = urlopen('http://169.254.169.254/', timeout=1)
response = no_proxy_conf.open('http://169.254.169.254/', timeout=1)
return response.info().get('Metadata-Flavor', '') == 'Google'
except socket.timeout:
logger.info('Timeout attempting to reach GCE metadata service.')
Expand Down
14 changes: 8 additions & 6 deletions tests/test_oauth2client.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,21 +209,23 @@ def test_get_environment_gae_local(self):

def test_get_environment_gce_production(self):
os.environ['SERVER_SOFTWARE'] = ''
no_proxy_conf = urllib.request.build_opener(urllib.request.ProxyHandler({}))
response = MockResponse({'Metadata-Flavor': 'Google'})
with mock.patch.object(urllib.request, 'urlopen',
with mock.patch.object(no_proxy_conf, 'open',
return_value=response,
autospec=True) as urlopen:
autospec=True) as no_proxy_conf_open:
self.assertEqual('GCE_PRODUCTION', _get_environment())
urlopen.assert_called_once_with(
no_proxy_conf_open.assert_called_once_with(
'http://169.254.169.254/', timeout=1)

def test_get_environment_unknown(self):
os.environ['SERVER_SOFTWARE'] = ''
with mock.patch.object(urllib.request, 'urlopen',
no_proxy_conf = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with mock.patch.object(no_proxy_conf, 'open',
return_value=MockResponse({}),
autospec=True) as urlopen:
autospec=True) as no_proxy_conf_open:
self.assertEqual(DEFAULT_ENV_NAME, _get_environment())
urlopen.assert_called_once_with(
no_proxy_conf_open.assert_called_once_with(
'http://169.254.169.254/', timeout=1)

def test_get_environment_variable_file(self):
Expand Down