blob: e244b3de2b3e0150e5a987145eda4e84d81975ab [file] [log] [blame]
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -07001# Copyright 2016 Google Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import json
16import os
17
18import mock
19import pytest
20
21from google.auth import _default
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -070022from google.auth import app_engine
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -070023from google.auth import compute_engine
24from google.auth import environment_vars
25from google.auth import exceptions
26from google.oauth2 import service_account
27import google.oauth2.credentials
28
29
30DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
31AUTHORIZED_USER_FILE = os.path.join(DATA_DIR, 'authorized_user.json')
32
33with open(AUTHORIZED_USER_FILE) as fh:
34 AUTHORIZED_USER_FILE_DATA = json.load(fh)
35
36SERVICE_ACCOUNT_FILE = os.path.join(DATA_DIR, 'service_account.json')
37
38with open(SERVICE_ACCOUNT_FILE) as fh:
39 SERVICE_ACCOUNT_FILE_DATA = json.load(fh)
40
41with open(os.path.join(DATA_DIR, 'cloud_sdk.cfg')) as fh:
42 CLOUD_SDK_CONFIG_DATA = fh.read()
43
44LOAD_FILE_PATCH = mock.patch(
45 'google.auth._default._load_credentials_from_file', return_value=(
46 mock.sentinel.credentials, mock.sentinel.project_id))
47
48
49def test__load_credentials_from_file_invalid_json(tmpdir):
50 jsonfile = tmpdir.join('invalid.json')
51 jsonfile.write('{')
52
53 with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
54 _default._load_credentials_from_file(str(jsonfile))
55
56 assert excinfo.match(r'not a valid json file')
57
58
59def test__load_credentials_from_file_invalid_type(tmpdir):
60 jsonfile = tmpdir.join('invalid.json')
61 jsonfile.write(json.dumps({'type': 'not-a-real-type'}))
62
63 with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
64 _default._load_credentials_from_file(str(jsonfile))
65
66 assert excinfo.match(r'does not have a valid type')
67
68
69def test__load_credentials_from_file_authorized_user():
70 credentials, project_id = _default._load_credentials_from_file(
71 AUTHORIZED_USER_FILE)
72 assert isinstance(credentials, google.oauth2.credentials.Credentials)
73 assert project_id is None
74
75
76def test__load_credentials_from_file_authorized_user_bad_format(tmpdir):
77 filename = tmpdir.join('authorized_user_bad.json')
78 filename.write(json.dumps({'type': 'authorized_user'}))
79
80 with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
81 _default._load_credentials_from_file(str(filename))
82
83 assert excinfo.match(r'Failed to load authorized user')
84 assert excinfo.match(r'missing fields')
85
86
87def test__load_credentials_from_file_service_account():
88 credentials, project_id = _default._load_credentials_from_file(
89 SERVICE_ACCOUNT_FILE)
90 assert isinstance(credentials, service_account.Credentials)
91 assert project_id == SERVICE_ACCOUNT_FILE_DATA['project_id']
92
93
94def test__load_credentials_from_file_service_account_bad_format(tmpdir):
95 filename = tmpdir.join('serivce_account_bad.json')
96 filename.write(json.dumps({'type': 'service_account'}))
97
98 with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
99 _default._load_credentials_from_file(str(filename))
100
101 assert excinfo.match(r'Failed to load service account')
102 assert excinfo.match(r'missing fields')
103
104
105@mock.patch.dict(os.environ, {}, clear=True)
106def test__get_explicit_environ_credentials_no_env():
107 assert _default._get_explicit_environ_credentials() == (None, None)
108
109
110@LOAD_FILE_PATCH
111def test__get_explicit_environ_credentials(mock_load, monkeypatch):
112 monkeypatch.setenv(environment_vars.CREDENTIALS, 'filename')
113
114 credentials, project_id = _default._get_explicit_environ_credentials()
115
116 assert credentials is mock.sentinel.credentials
117 assert project_id is mock.sentinel.project_id
118 mock_load.assert_called_with('filename')
119
120
121@LOAD_FILE_PATCH
122def test__get_explicit_environ_credentials_no_project_id(
123 mock_load, monkeypatch):
124 mock_load.return_value = (mock.sentinel.credentials, None)
125 monkeypatch.setenv(environment_vars.CREDENTIALS, 'filename')
126
127 credentials, project_id = _default._get_explicit_environ_credentials()
128
129 assert credentials is mock.sentinel.credentials
130 assert project_id is None
131
132
133@LOAD_FILE_PATCH
134@mock.patch('google.auth._cloud_sdk.get_application_default_credentials_path')
135def test__get_gcloud_sdk_credentials(
136 mock_get_adc_path, mock_load):
137 mock_get_adc_path.return_value = SERVICE_ACCOUNT_FILE
138
139 credentials, project_id = _default._get_gcloud_sdk_credentials()
140
141 assert credentials is mock.sentinel.credentials
142 assert project_id is mock.sentinel.project_id
143 mock_load.assert_called_with(SERVICE_ACCOUNT_FILE)
144
145
146@mock.patch('google.auth._cloud_sdk.get_application_default_credentials_path')
147def test__get_gcloud_sdk_credentials_non_existent(mock_get_adc_path, tmpdir):
148 non_existent = tmpdir.join('non-existent')
149 mock_get_adc_path.return_value = str(non_existent)
150
151 credentials, project_id = _default._get_gcloud_sdk_credentials()
152
153 assert credentials is None
154 assert project_id is None
155
156
157@mock.patch(
158 'google.auth._cloud_sdk.get_project_id',
159 return_value=mock.sentinel.project_id)
160@mock.patch('os.path.isfile', return_value=True)
161@LOAD_FILE_PATCH
162def test__get_gcloud_sdk_credentials_project_id(
163 mock_load, unused_mock_isfile, mock_get_project_id):
164 # Don't return a project ID from load file, make the function check
165 # the Cloud SDK project.
166 mock_load.return_value = (mock.sentinel.credentials, None)
167
168 credentials, project_id = _default._get_gcloud_sdk_credentials()
169
170 assert credentials == mock.sentinel.credentials
171 assert project_id == mock.sentinel.project_id
172 assert mock_get_project_id.called
173
174
175@mock.patch(
176 'google.auth._cloud_sdk.get_project_id',
177 return_value=None)
178@mock.patch('os.path.isfile', return_value=True)
179@LOAD_FILE_PATCH
180def test__get_gcloud_sdk_credentials_no_project_id(
181 mock_load, unused_mock_isfile, mock_get_project_id):
182 # Don't return a project ID from load file, make the function check
183 # the Cloud SDK project.
184 mock_load.return_value = (mock.sentinel.credentials, None)
185
186 credentials, project_id = _default._get_gcloud_sdk_credentials()
187
188 assert credentials == mock.sentinel.credentials
189 assert project_id is None
190
191
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -0700192@pytest.fixture
193def app_identity_mock(monkeypatch):
194 """Mocks the app_identity module for google.auth.app_engine."""
195 app_identity_mock = mock.Mock()
196 monkeypatch.setattr(
197 app_engine, 'app_identity', app_identity_mock)
198 yield app_identity_mock
199
200
201def test__get_gae_credentials(app_identity_mock):
202 app_identity_mock.get_application_id.return_value = mock.sentinel.project
203
204 credentials, project_id = _default._get_gae_credentials()
205
206 assert isinstance(credentials, app_engine.Credentials)
207 assert project_id == mock.sentinel.project
208
209
210def test__get_gae_credentials_no_apis():
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700211 assert _default._get_gae_credentials() == (None, None)
212
213
214@mock.patch(
215 'google.auth.compute_engine._metadata.ping', return_value=True)
216@mock.patch(
Jon Wayne Parrott5b03ba12016-10-24 13:51:26 -0700217 'google.auth.compute_engine._metadata.get_project_id',
218 return_value='example-project')
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700219def test__get_gce_credentials(get_mock, ping_mock):
220 credentials, project_id = _default._get_gce_credentials()
221
222 assert isinstance(credentials, compute_engine.Credentials)
223 assert project_id == 'example-project'
224
225
226@mock.patch('google.auth.compute_engine._metadata.ping', return_value=False)
227def test__get_gce_credentials_no_ping(ping_mock):
228 credentials, project_id = _default._get_gce_credentials()
229
230 assert credentials is None
231 assert project_id is None
232
233
234@mock.patch(
235 'google.auth.compute_engine._metadata.ping', return_value=True)
236@mock.patch(
Jon Wayne Parrott5b03ba12016-10-24 13:51:26 -0700237 'google.auth.compute_engine._metadata.get_project_id',
Jon Wayne Parrottaadb3de2016-10-19 09:34:05 -0700238 side_effect=exceptions.TransportError())
239def test__get_gce_credentials_no_project_id(get_mock, ping_mock):
240 credentials, project_id = _default._get_gce_credentials()
241
242 assert isinstance(credentials, compute_engine.Credentials)
243 assert project_id is None
244
245
246@mock.patch('google.auth.compute_engine._metadata.ping', return_value=False)
247def test__get_gce_credentials_explicit_request(ping_mock):
248 _default._get_gce_credentials(mock.sentinel.request)
249 ping_mock.assert_called_with(request=mock.sentinel.request)
250
251
252@mock.patch(
253 'google.auth._default._get_explicit_environ_credentials',
254 return_value=(mock.sentinel.credentials, mock.sentinel.project_id))
255def test_default_early_out(get_mock):
256 assert _default.default() == (
257 mock.sentinel.credentials, mock.sentinel.project_id)
258
259
260@mock.patch(
261 'google.auth._default._get_explicit_environ_credentials',
262 return_value=(mock.sentinel.credentials, mock.sentinel.project_id))
263def test_default_explict_project_id(get_mock, monkeypatch):
264 monkeypatch.setenv(environment_vars.PROJECT, 'explicit-env')
265 assert _default.default() == (
266 mock.sentinel.credentials, 'explicit-env')
267
268
269@mock.patch(
270 'google.auth._default._get_explicit_environ_credentials',
271 return_value=(None, None))
272@mock.patch(
273 'google.auth._default._get_gcloud_sdk_credentials',
274 return_value=(None, None))
275@mock.patch(
276 'google.auth._default._get_gae_credentials',
277 return_value=(None, None))
278@mock.patch(
279 'google.auth._default._get_gce_credentials',
280 return_value=(None, None))
281def test_default_fail(unused_gce, unused_gae, unused_sdk, unused_explicit):
282 with pytest.raises(exceptions.DefaultCredentialsError):
283 assert _default.default()