summaryrefslogtreecommitdiffstats
path: root/contrib/python/google-auth/py3/tests/test_credentials.py
blob: 1fb880096916b74676d7062e9861d986c1efdef7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
import os

import mock
import pytest  # type: ignore

from google.auth import _helpers
from google.auth import credentials
from google.auth import environment_vars
from google.auth import exceptions
from google.oauth2 import _client


class CredentialsImpl(credentials.CredentialsWithTrustBoundary):
    def _refresh_token(self, request):
        self.token = "refreshed-token"
        self.expiry = (
            datetime.datetime.utcnow()
            + _helpers.REFRESH_THRESHOLD
            + datetime.timedelta(seconds=5)
        )

    def with_quota_project(self, quota_project_id):
        raise NotImplementedError()

    def _build_trust_boundary_lookup_url(self):
        # Using self.token here to make the URL dynamic for testing purposes
        return "http://mock.url/lookup_for_{}".format(self.token)


class CredentialsImplWithMetrics(credentials.Credentials):
    def refresh(self, request):
        self.token = request

    def _metric_header_for_usage(self):
        return "foo"


def test_credentials_constructor():
    credentials = CredentialsImpl()
    assert not credentials.token
    assert not credentials.expiry
    assert not credentials.expired
    assert not credentials.valid
    assert credentials.universe_domain == "googleapis.com"
    assert not credentials._use_non_blocking_refresh


def test_credentials_get_cred_info():
    credentials = CredentialsImpl()
    assert not credentials.get_cred_info()


def test_with_non_blocking_refresh():
    c = CredentialsImpl()
    c.with_non_blocking_refresh()
    assert c._use_non_blocking_refresh


def test_expired_and_valid():
    credentials = CredentialsImpl()
    credentials.token = "token"

    assert credentials.valid
    assert not credentials.expired

    # Set the expiration to one second more than now plus the clock skew
    # accomodation. These credentials should be valid.
    credentials.expiry = (
        _helpers.utcnow() + _helpers.REFRESH_THRESHOLD + datetime.timedelta(seconds=1)
    )

    assert credentials.valid
    assert not credentials.expired

    # Set the credentials expiration to now. Because of the clock skew
    # accomodation, these credentials should report as expired.
    credentials.expiry = _helpers.utcnow()

    assert not credentials.valid
    assert credentials.expired


def test_before_request():
    credentials = CredentialsImpl()
    request = mock.Mock()
    headers = {}

    # First call should call refresh, setting the token.
    credentials.before_request(request, "http://example.com", "GET", headers)
    assert credentials.valid
    assert credentials.token == "refreshed-token"
    assert headers["authorization"] == "Bearer refreshed-token"
    assert "x-allowed-locations" not in headers

    request = mock.Mock()
    headers = {}

    # Second call shouldn't call refresh.
    credentials.before_request(request, "http://example.com", "GET", headers)
    assert credentials.valid
    assert credentials.token == "refreshed-token"
    assert headers["authorization"] == "Bearer refreshed-token"
    assert "x-allowed-locations" not in headers


def test_before_request_with_trust_boundary():
    DUMMY_BOUNDARY = "0xA30"
    credentials = CredentialsImpl()
    credentials._trust_boundary = {"locations": [], "encodedLocations": DUMMY_BOUNDARY}
    request = mock.Mock()
    headers = {}

    # First call should call refresh, setting the token.
    credentials.before_request(request, "http://example.com", "GET", headers)
    assert credentials.valid
    assert credentials.token == "refreshed-token"
    assert headers["authorization"] == "Bearer refreshed-token"
    assert headers["x-allowed-locations"] == DUMMY_BOUNDARY

    request = mock.Mock()
    headers = {}

    # Second call shouldn't call refresh.
    credentials.before_request(request, "http://example.com", "GET", headers)
    assert credentials.valid
    assert credentials.token == "refreshed-token"
    assert headers["authorization"] == "Bearer refreshed-token"
    assert headers["x-allowed-locations"] == DUMMY_BOUNDARY


def test_before_request_metrics():
    credentials = CredentialsImplWithMetrics()
    request = "token"
    headers = {}

    credentials.before_request(request, "http://example.com", "GET", headers)
    assert headers["x-goog-api-client"] == "foo"


def test_anonymous_credentials_ctor():
    anon = credentials.AnonymousCredentials()
    assert anon.token is None
    assert anon.expiry is None
    assert not anon.expired
    assert anon.valid


def test_anonymous_credentials_refresh():
    anon = credentials.AnonymousCredentials()
    request = object()
    with pytest.raises(ValueError):
        anon.refresh(request)


def test_anonymous_credentials_apply_default():
    anon = credentials.AnonymousCredentials()
    headers = {}
    anon.apply(headers)
    assert headers == {}
    with pytest.raises(ValueError):
        anon.apply(headers, token="TOKEN")


def test_anonymous_credentials_before_request():
    anon = credentials.AnonymousCredentials()
    request = object()
    method = "GET"
    url = "https://example.com/api/endpoint"
    headers = {}
    anon.before_request(request, method, url, headers)
    assert headers == {}


class ReadOnlyScopedCredentialsImpl(credentials.ReadOnlyScoped, CredentialsImpl):
    @property
    def requires_scopes(self):
        return super(ReadOnlyScopedCredentialsImpl, self).requires_scopes


def test_readonly_scoped_credentials_constructor():
    credentials = ReadOnlyScopedCredentialsImpl()
    assert credentials._scopes is None


def test_readonly_scoped_credentials_scopes():
    credentials = ReadOnlyScopedCredentialsImpl()
    credentials._scopes = ["one", "two"]
    assert credentials.scopes == ["one", "two"]
    assert credentials.has_scopes(["one"])
    assert credentials.has_scopes(["two"])
    assert credentials.has_scopes(["one", "two"])
    assert not credentials.has_scopes(["three"])

    # Test with default scopes
    credentials_with_default = ReadOnlyScopedCredentialsImpl()
    credentials_with_default._default_scopes = ["one", "two"]
    assert credentials_with_default.has_scopes(["one", "two"])
    assert not credentials_with_default.has_scopes(["three"])

    # Test with no scopes
    credentials_no_scopes = ReadOnlyScopedCredentialsImpl()
    assert not credentials_no_scopes.has_scopes(["one"])

    assert credentials_no_scopes.has_scopes([])


def test_readonly_scoped_credentials_requires_scopes():
    credentials = ReadOnlyScopedCredentialsImpl()
    assert not credentials.requires_scopes


class RequiresScopedCredentialsImpl(credentials.Scoped, CredentialsImpl):
    def __init__(self, scopes=None, default_scopes=None):
        super(RequiresScopedCredentialsImpl, self).__init__()
        self._scopes = scopes
        self._default_scopes = default_scopes

    @property
    def requires_scopes(self):
        return not self.scopes

    def with_scopes(self, scopes, default_scopes=None):
        return RequiresScopedCredentialsImpl(
            scopes=scopes, default_scopes=default_scopes
        )


def test_create_scoped_if_required_scoped():
    unscoped_credentials = RequiresScopedCredentialsImpl()
    scoped_credentials = credentials.with_scopes_if_required(
        unscoped_credentials, ["one", "two"]
    )

    assert scoped_credentials is not unscoped_credentials
    assert not scoped_credentials.requires_scopes
    assert scoped_credentials.has_scopes(["one", "two"])


def test_create_scoped_if_required_not_scopes():
    unscoped_credentials = CredentialsImpl()
    scoped_credentials = credentials.with_scopes_if_required(
        unscoped_credentials, ["one", "two"]
    )

    assert scoped_credentials is unscoped_credentials


def test_nonblocking_refresh_fresh_credentials():
    c = CredentialsImpl()

    c._refresh_worker = mock.MagicMock()

    request = mock.Mock()

    c.refresh(request)
    assert c.token_state == credentials.TokenState.FRESH

    c.with_non_blocking_refresh()
    c.before_request(request, "http://example.com", "GET", {})


def test_nonblocking_refresh_invalid_credentials():
    c = CredentialsImpl()
    c.with_non_blocking_refresh()

    request = mock.Mock()
    headers = {}

    assert c.token_state == credentials.TokenState.INVALID

    c.before_request(request, "http://example.com", "GET", headers)
    assert c.token_state == credentials.TokenState.FRESH
    assert c.valid
    assert c.token == "refreshed-token"
    assert headers["authorization"] == "Bearer refreshed-token"
    assert "x-identity-trust-boundary" not in headers


def test_nonblocking_refresh_stale_credentials():
    c = CredentialsImpl()
    c.with_non_blocking_refresh()

    request = mock.Mock()
    headers = {}

    # Invalid credentials MUST require a blocking refresh.
    c.before_request(request, "http://example.com", "GET", headers)
    assert c.token_state == credentials.TokenState.FRESH
    assert not c._refresh_worker._worker

    c.expiry = (
        datetime.datetime.utcnow()
        + _helpers.REFRESH_THRESHOLD
        - datetime.timedelta(seconds=1)
    )

    # STALE credentials SHOULD spawn a non-blocking worker
    assert c.token_state == credentials.TokenState.STALE
    c.before_request(request, "http://example.com", "GET", headers)
    assert c._refresh_worker._worker is not None

    assert c.token_state == credentials.TokenState.FRESH
    assert c.valid
    assert c.token == "refreshed-token"
    assert headers["authorization"] == "Bearer refreshed-token"
    assert "x-identity-trust-boundary" not in headers


def test_nonblocking_refresh_failed_credentials():
    c = CredentialsImpl()
    c.with_non_blocking_refresh()

    request = mock.Mock()
    headers = {}

    # Invalid credentials MUST require a blocking refresh.
    c.before_request(request, "http://example.com", "GET", headers)
    assert c.token_state == credentials.TokenState.FRESH
    assert not c._refresh_worker._worker

    c.expiry = (
        datetime.datetime.utcnow()
        + _helpers.REFRESH_THRESHOLD
        - datetime.timedelta(seconds=1)
    )

    # STALE credentials SHOULD spawn a non-blocking worker
    assert c.token_state == credentials.TokenState.STALE
    c._refresh_worker._worker = mock.MagicMock()
    c._refresh_worker._worker._error_info = "Some Error"
    c.before_request(request, "http://example.com", "GET", headers)
    assert c._refresh_worker._worker is not None

    assert c.token_state == credentials.TokenState.FRESH
    assert c.valid
    assert c.token == "refreshed-token"
    assert headers["authorization"] == "Bearer refreshed-token"
    assert "x-identity-trust-boundary" not in headers


def test_token_state_no_expiry():
    c = CredentialsImpl()

    request = mock.Mock()
    c.refresh(request)

    c.expiry = None
    assert c.token_state == credentials.TokenState.FRESH

    c.before_request(request, "http://example.com", "GET", {})


class TestCredentialsWithTrustBoundary(object):
    @mock.patch.object(_client, "_lookup_trust_boundary")
    def test_lookup_trust_boundary_env_var_not_true(self, mock_lookup_tb):
        creds = CredentialsImpl()
        request = mock.Mock()

        # Ensure env var is not "true"
        with mock.patch.dict(
            os.environ, {environment_vars.GOOGLE_AUTH_TRUST_BOUNDARY_ENABLED: "false"}
        ):
            result = creds._refresh_trust_boundary(request)

        assert result is None
        mock_lookup_tb.assert_not_called()

    @mock.patch.object(_client, "_lookup_trust_boundary")
    def test_lookup_trust_boundary_env_var_missing(self, mock_lookup_tb):
        creds = CredentialsImpl()
        request = mock.Mock()

        # Ensure env var is missing
        with mock.patch.dict(os.environ, clear=True):
            result = creds._refresh_trust_boundary(request)

        assert result is None
        mock_lookup_tb.assert_not_called()

    @mock.patch.object(_client, "_lookup_trust_boundary")
    def test_lookup_trust_boundary_non_default_universe(self, mock_lookup_tb):
        creds = CredentialsImpl()
        creds._universe_domain = "my.universe.com"  # Non-GDU
        request = mock.Mock()

        with mock.patch.dict(
            os.environ, {environment_vars.GOOGLE_AUTH_TRUST_BOUNDARY_ENABLED: "true"}
        ):
            result = creds._refresh_trust_boundary(request)

        assert result is None
        mock_lookup_tb.assert_not_called()

    @mock.patch.object(_client, "_lookup_trust_boundary")
    def test_lookup_trust_boundary_calls_client_and_build_url(self, mock_lookup_tb):
        creds = CredentialsImpl()
        creds.token = "test_token"  # For _build_trust_boundary_lookup_url
        request = mock.Mock()
        expected_url = "http://mock.url/lookup_for_test_token"
        expected_boundary_info = {"encodedLocations": "0xABC"}
        mock_lookup_tb.return_value = expected_boundary_info

        # Mock _build_trust_boundary_lookup_url to ensure it's called.
        mock_build_url = mock.Mock(return_value=expected_url)
        creds._build_trust_boundary_lookup_url = mock_build_url

        with mock.patch.dict(
            os.environ, {environment_vars.GOOGLE_AUTH_TRUST_BOUNDARY_ENABLED: "true"}
        ):
            result = creds._lookup_trust_boundary(request)

        assert result == expected_boundary_info
        mock_build_url.assert_called_once()
        expected_headers = {"authorization": "Bearer test_token"}
        mock_lookup_tb.assert_called_once_with(
            request, expected_url, headers=expected_headers
        )

    @mock.patch.object(_client, "_lookup_trust_boundary")
    def test_lookup_trust_boundary_build_url_returns_none(self, mock_lookup_tb):
        creds = CredentialsImpl()
        request = mock.Mock()

        # Mock _build_trust_boundary_lookup_url to return None
        mock_build_url = mock.Mock(return_value=None)
        creds._build_trust_boundary_lookup_url = mock_build_url

        with mock.patch.dict(
            os.environ, {environment_vars.GOOGLE_AUTH_TRUST_BOUNDARY_ENABLED: "true"}
        ):
            with pytest.raises(
                exceptions.InvalidValue,
                match="Failed to build trust boundary lookup URL.",
            ):
                creds._lookup_trust_boundary(request)

        mock_build_url.assert_called_once()  # Ensure _build_trust_boundary_lookup_url was called
        mock_lookup_tb.assert_not_called()  # Ensure _client.lookup_trust_boundary was not called

    @mock.patch("google.auth.credentials._LOGGER")
    @mock.patch("google.auth._helpers.is_logging_enabled", return_value=True)
    @mock.patch.object(_client, "_lookup_trust_boundary")
    def test_refresh_trust_boundary_fails_with_cached_data_and_logging(
        self, mock_lookup_tb, mock_is_logging_enabled, mock_logger
    ):
        creds = CredentialsImpl()
        creds._trust_boundary = {"encodedLocations": "0xABC"}
        request = mock.Mock()

        refresh_error = exceptions.RefreshError("Lookup failed")
        mock_lookup_tb.side_effect = refresh_error

        with mock.patch.dict(
            os.environ, {environment_vars.GOOGLE_AUTH_TRUST_BOUNDARY_ENABLED: "true"}
        ):
            creds.refresh(request)

        mock_lookup_tb.assert_called_once()
        mock_is_logging_enabled.assert_called_once_with(mock_logger)
        mock_logger.debug.assert_called_once_with(
            "Using cached trust boundary due to refresh error: %s", refresh_error
        )