test_id_token.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # Copyright 2014 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. import json
  15. import os
  16. import mock
  17. import pytest
  18. from google.auth import environment_vars
  19. from google.auth import exceptions
  20. from google.auth import transport
  21. import google.auth.compute_engine._metadata
  22. from google.oauth2 import id_token
  23. from google.oauth2 import service_account
  24. import yatest.common
  25. SERVICE_ACCOUNT_FILE = os.path.join(
  26. yatest.common.test_source_path(), "data/service_account.json"
  27. )
  28. def make_request(status, data=None):
  29. response = mock.create_autospec(transport.Response, instance=True)
  30. response.status = status
  31. if data is not None:
  32. response.data = json.dumps(data).encode("utf-8")
  33. request = mock.create_autospec(transport.Request)
  34. request.return_value = response
  35. return request
  36. def test__fetch_certs_success():
  37. certs = {"1": "cert"}
  38. request = make_request(200, certs)
  39. returned_certs = id_token._fetch_certs(request, mock.sentinel.cert_url)
  40. request.assert_called_once_with(mock.sentinel.cert_url, method="GET")
  41. assert returned_certs == certs
  42. def test__fetch_certs_failure():
  43. request = make_request(404)
  44. with pytest.raises(exceptions.TransportError):
  45. id_token._fetch_certs(request, mock.sentinel.cert_url)
  46. request.assert_called_once_with(mock.sentinel.cert_url, method="GET")
  47. @mock.patch("google.auth.jwt.decode", autospec=True)
  48. @mock.patch("google.oauth2.id_token._fetch_certs", autospec=True)
  49. def test_verify_token(_fetch_certs, decode):
  50. result = id_token.verify_token(mock.sentinel.token, mock.sentinel.request)
  51. assert result == decode.return_value
  52. _fetch_certs.assert_called_once_with(
  53. mock.sentinel.request, id_token._GOOGLE_OAUTH2_CERTS_URL
  54. )
  55. decode.assert_called_once_with(
  56. mock.sentinel.token, certs=_fetch_certs.return_value, audience=None
  57. )
  58. @mock.patch("google.auth.jwt.decode", autospec=True)
  59. @mock.patch("google.oauth2.id_token._fetch_certs", autospec=True)
  60. def test_verify_token_args(_fetch_certs, decode):
  61. result = id_token.verify_token(
  62. mock.sentinel.token,
  63. mock.sentinel.request,
  64. audience=mock.sentinel.audience,
  65. certs_url=mock.sentinel.certs_url,
  66. )
  67. assert result == decode.return_value
  68. _fetch_certs.assert_called_once_with(mock.sentinel.request, mock.sentinel.certs_url)
  69. decode.assert_called_once_with(
  70. mock.sentinel.token,
  71. certs=_fetch_certs.return_value,
  72. audience=mock.sentinel.audience,
  73. )
  74. @mock.patch("google.oauth2.id_token.verify_token", autospec=True)
  75. def test_verify_oauth2_token(verify_token):
  76. verify_token.return_value = {"iss": "accounts.google.com"}
  77. result = id_token.verify_oauth2_token(
  78. mock.sentinel.token, mock.sentinel.request, audience=mock.sentinel.audience
  79. )
  80. assert result == verify_token.return_value
  81. verify_token.assert_called_once_with(
  82. mock.sentinel.token,
  83. mock.sentinel.request,
  84. audience=mock.sentinel.audience,
  85. certs_url=id_token._GOOGLE_OAUTH2_CERTS_URL,
  86. )
  87. @mock.patch("google.oauth2.id_token.verify_token", autospec=True)
  88. def test_verify_oauth2_token_invalid_iss(verify_token):
  89. verify_token.return_value = {"iss": "invalid_issuer"}
  90. with pytest.raises(exceptions.GoogleAuthError):
  91. id_token.verify_oauth2_token(
  92. mock.sentinel.token, mock.sentinel.request, audience=mock.sentinel.audience
  93. )
  94. @mock.patch("google.oauth2.id_token.verify_token", autospec=True)
  95. def test_verify_firebase_token(verify_token):
  96. result = id_token.verify_firebase_token(
  97. mock.sentinel.token, mock.sentinel.request, audience=mock.sentinel.audience
  98. )
  99. assert result == verify_token.return_value
  100. verify_token.assert_called_once_with(
  101. mock.sentinel.token,
  102. mock.sentinel.request,
  103. audience=mock.sentinel.audience,
  104. certs_url=id_token._GOOGLE_APIS_CERTS_URL,
  105. )
  106. def test_fetch_id_token_from_metadata_server(monkeypatch):
  107. monkeypatch.delenv(environment_vars.CREDENTIALS, raising=False)
  108. def mock_init(self, request, audience, use_metadata_identity_endpoint):
  109. assert use_metadata_identity_endpoint
  110. self.token = "id_token"
  111. with mock.patch("google.auth.compute_engine._metadata.ping", return_value=True):
  112. with mock.patch.multiple(
  113. google.auth.compute_engine.IDTokenCredentials,
  114. __init__=mock_init,
  115. refresh=mock.Mock(),
  116. ):
  117. request = mock.Mock()
  118. token = id_token.fetch_id_token(request, "https://pubsub.googleapis.com")
  119. assert token == "id_token"
  120. def test_fetch_id_token_from_explicit_cred_json_file(monkeypatch):
  121. monkeypatch.setenv(environment_vars.CREDENTIALS, SERVICE_ACCOUNT_FILE)
  122. def mock_refresh(self, request):
  123. self.token = "id_token"
  124. with mock.patch.object(service_account.IDTokenCredentials, "refresh", mock_refresh):
  125. request = mock.Mock()
  126. token = id_token.fetch_id_token(request, "https://pubsub.googleapis.com")
  127. assert token == "id_token"
  128. def test_fetch_id_token_no_cred_exists(monkeypatch):
  129. monkeypatch.delenv(environment_vars.CREDENTIALS, raising=False)
  130. with mock.patch(
  131. "google.auth.compute_engine._metadata.ping",
  132. side_effect=exceptions.TransportError(),
  133. ):
  134. with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
  135. request = mock.Mock()
  136. id_token.fetch_id_token(request, "https://pubsub.googleapis.com")
  137. assert excinfo.match(
  138. r"Neither metadata server or valid service account credentials are found."
  139. )
  140. with mock.patch("google.auth.compute_engine._metadata.ping", return_value=False):
  141. with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
  142. request = mock.Mock()
  143. id_token.fetch_id_token(request, "https://pubsub.googleapis.com")
  144. assert excinfo.match(
  145. r"Neither metadata server or valid service account credentials are found."
  146. )
  147. def test_fetch_id_token_invalid_cred_file_type(monkeypatch):
  148. user_credentials_file = os.path.join(
  149. yatest.common.test_source_path(), "data/authorized_user.json"
  150. )
  151. monkeypatch.setenv(environment_vars.CREDENTIALS, user_credentials_file)
  152. with mock.patch("google.auth.compute_engine._metadata.ping", return_value=False):
  153. with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
  154. request = mock.Mock()
  155. id_token.fetch_id_token(request, "https://pubsub.googleapis.com")
  156. assert excinfo.match(
  157. r"Neither metadata server or valid service account credentials are found."
  158. )
  159. def test_fetch_id_token_invalid_json(monkeypatch):
  160. not_json_file = os.path.join(yatest.common.test_source_path(), "data/public_cert.pem")
  161. monkeypatch.setenv(environment_vars.CREDENTIALS, not_json_file)
  162. with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
  163. request = mock.Mock()
  164. id_token.fetch_id_token(request, "https://pubsub.googleapis.com")
  165. assert excinfo.match(
  166. r"GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials."
  167. )
  168. def test_fetch_id_token_invalid_cred_path(monkeypatch):
  169. not_json_file = os.path.join(yatest.common.test_source_path(), "data/not_exists.json")
  170. monkeypatch.setenv(environment_vars.CREDENTIALS, not_json_file)
  171. with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
  172. request = mock.Mock()
  173. id_token.fetch_id_token(request, "https://pubsub.googleapis.com")
  174. assert excinfo.match(
  175. r"GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid."
  176. )