Add google.auth._oauth2client - helpers for oauth2client migration (#70)
diff --git a/google/auth/_oauth2client.py b/google/auth/_oauth2client.py
new file mode 100644
index 0000000..312326e
--- /dev/null
+++ b/google/auth/_oauth2client.py
@@ -0,0 +1,166 @@
+# Copyright 2016 Google Inc.
+#
+# 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.
+
+"""Helpers for transitioning from oauth2client to google-auth.
+
+.. warning::
+ This module is private as it is intended to assist first-party downstream
+ clients with the transition from oauth2client to google-auth.
+"""
+
+from __future__ import absolute_import
+
+from google.auth import _helpers
+import google.auth.app_engine
+import google.oauth2.credentials
+import google.oauth2.service_account
+
+try:
+ import oauth2client.client
+ import oauth2client.contrib.gce
+ import oauth2client.service_account
+except ImportError:
+ raise ImportError('oauth2client is not installed.')
+
+try:
+ import oauth2client.contrib.appengine
+ _HAS_APPENGINE = True
+except ImportError:
+ _HAS_APPENGINE = False
+
+
+_CONVERT_ERROR_TMPL = (
+ 'Unable to convert {} to a google-auth credentials class.')
+
+
+def _convert_oauth2_credentials(credentials):
+ """Converts to :class:`google.oauth2.credentials.Credentials`.
+
+ Args:
+ credentials (Union[oauth2client.client.OAuth2Credentials,
+ oauth2client.client.GoogleCredentials]): The credentials to
+ convert.
+
+ Returns:
+ google.oauth2.credentials.Credentials: The converted credentials.
+ """
+ new_credentials = google.oauth2.credentials.Credentials(
+ token=credentials.access_token,
+ refresh_token=credentials.refresh_token,
+ token_uri=credentials.token_uri,
+ client_id=credentials.client_id,
+ client_secret=credentials.client_secret,
+ scopes=credentials.scopes)
+
+ new_credentials._expires = credentials.token_expiry
+
+ return new_credentials
+
+
+def _convert_service_account_credentials(credentials):
+ """Converts to :class:`google.oauth2.service_account.Credentials`.
+
+ Args:
+ credentials (Union[
+ oauth2client.service_account.ServiceAccountCredentials,
+ oauth2client.service_account._JWTAccessCredentials]): The
+ credentials to convert.
+
+ Returns:
+ google.oauth2.service_account.Credentials: The converted credentials.
+ """
+ info = credentials.serialization_data.copy()
+ info['token_uri'] = credentials.token_uri
+ return google.oauth2.service_account.Credentials.from_service_account_info(
+ info)
+
+
+def _convert_gce_app_assertion_credentials(credentials):
+ """Converts to :class:`google.auth.compute_engine.Credentials`.
+
+ Args:
+ credentials (oauth2client.contrib.gce.AppAssertionCredentials): The
+ credentials to convert.
+
+ Returns:
+ google.oauth2.service_account.Credentials: The converted credentials.
+ """
+ return google.auth.compute_engine.Credentials(
+ service_account_email=credentials.service_account_email)
+
+
+def _convert_appengine_app_assertion_credentials(credentials):
+ """Converts to :class:`google.auth.app_engine.Credentials`.
+
+ Args:
+ credentials (oauth2client.contrib.app_engine.AppAssertionCredentials):
+ The credentials to convert.
+
+ Returns:
+ google.oauth2.service_account.Credentials: The converted credentials.
+ """
+ # pylint: disable=invalid-name
+ return google.auth.app_engine.Credentials(
+ scopes=_helpers.string_to_scopes(credentials.scope),
+ service_account_id=credentials.service_account_id)
+
+
+_CLASS_CONVERSION_MAP = {
+ oauth2client.client.OAuth2Credentials: _convert_oauth2_credentials,
+ oauth2client.client.GoogleCredentials: _convert_oauth2_credentials,
+ oauth2client.service_account.ServiceAccountCredentials:
+ _convert_service_account_credentials,
+ oauth2client.service_account._JWTAccessCredentials:
+ _convert_service_account_credentials,
+ oauth2client.contrib.gce.AppAssertionCredentials:
+ _convert_gce_app_assertion_credentials,
+}
+
+if _HAS_APPENGINE:
+ _CLASS_CONVERSION_MAP[
+ oauth2client.contrib.appengine.AppAssertionCredentials] = (
+ _convert_appengine_app_assertion_credentials)
+
+
+def convert(credentials):
+ """Convert oauth2client credentials to google-auth credentials.
+
+ This class converts:
+
+ - :class:`oauth2client.client.OAuth2Credentials` to
+ :class:`google.oauth2.credentials.Credentials`.
+ - :class:`oauth2client.client.GoogleCredentials` to
+ :class:`google.oauth2.credentials.Credentials`.
+ - :class:`oauth2client.service_account.ServiceAccountCredentials` to
+ :class:`google.oauth2.service_account.Credentials`.
+ - :class:`oauth2client.service_account._JWTAccessCredentials` to
+ :class:`google.oauth2.service_account.Credentials`.
+ - :class:`oauth2client.contrib.gce.AppAssertionCredentials` to
+ :class:`google.auth.compute_engine.Credentials`.
+ - :class:`oauth2client.contrib.appengine.AppAssertionCredentials` to
+ :class:`google.auth.app_engine.Credentials`.
+
+ Returns:
+ google.auth.credentials.Credentials: The converted credentials.
+
+ Raises:
+ ValueError: If the credentials could not be converted.
+ """
+
+ credentials_class = type(credentials)
+
+ try:
+ return _CLASS_CONVERSION_MAP[credentials_class](credentials)
+ except KeyError:
+ raise ValueError(_CONVERT_ERROR_TMPL.format(credentials_class))
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..c9e3f84
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,37 @@
+# Copyright 2016 Google Inc.
+#
+# 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 sys
+
+import mock
+import pytest
+
+
+@pytest.fixture
+def mock_non_existent_module(monkeypatch):
+ """Mocks a non-existing module in sys.modules.
+
+ Additionally mocks any non-existing modules specified in the dotted path.
+ """
+ def _mock_non_existent_module(path):
+ parts = path.split('.')
+ partial = []
+ for part in parts:
+ partial.append(part)
+ current_module = '.'.join(partial)
+ if current_module not in sys.modules:
+ monkeypatch.setitem(
+ sys.modules, current_module, mock.MagicMock())
+
+ return _mock_non_existent_module
diff --git a/tests/test__oauth2client.py b/tests/test__oauth2client.py
new file mode 100644
index 0000000..9478406
--- /dev/null
+++ b/tests/test__oauth2client.py
@@ -0,0 +1,157 @@
+# Copyright 2016 Google Inc.
+#
+# 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 sys
+
+import mock
+import oauth2client.client
+import oauth2client.contrib.gce
+import oauth2client.service_account
+import pytest
+from six.moves import reload_module
+
+from google.auth import _oauth2client
+
+
+DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
+SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, 'service_account.json')
+
+
+def test__convert_oauth2_credentials():
+ old_credentials = oauth2client.client.OAuth2Credentials(
+ 'access_token', 'client_id', 'client_secret', 'refresh_token',
+ datetime.datetime.min, 'token_uri', 'user_agent', scopes='one two')
+
+ new_credentials = _oauth2client._convert_oauth2_credentials(
+ old_credentials)
+
+ assert new_credentials.token == old_credentials.access_token
+ assert new_credentials._refresh_token == old_credentials.refresh_token
+ assert new_credentials._client_id == old_credentials.client_id
+ assert new_credentials._client_secret == old_credentials.client_secret
+ assert new_credentials._token_uri == old_credentials.token_uri
+ assert new_credentials.scopes == old_credentials.scopes
+
+
+def test__convert_service_account_credentials():
+ old_class = oauth2client.service_account.ServiceAccountCredentials
+ old_credentials = old_class.from_json_keyfile_name(
+ SERVICE_ACCOUNT_JSON_FILE)
+
+ new_credentials = _oauth2client._convert_service_account_credentials(
+ old_credentials)
+
+ assert (new_credentials._service_account_email ==
+ old_credentials.service_account_email)
+ assert new_credentials._signer.key_id == old_credentials._private_key_id
+ assert new_credentials._token_uri == old_credentials.token_uri
+
+
+def test__convert_service_account_credentials_with_jwt():
+ old_class = oauth2client.service_account._JWTAccessCredentials
+ old_credentials = old_class.from_json_keyfile_name(
+ SERVICE_ACCOUNT_JSON_FILE)
+
+ new_credentials = _oauth2client._convert_service_account_credentials(
+ old_credentials)
+
+ assert (new_credentials._service_account_email ==
+ old_credentials.service_account_email)
+ assert new_credentials._signer.key_id == old_credentials._private_key_id
+ assert new_credentials._token_uri == old_credentials.token_uri
+
+
+def test__convert_gce_app_assertion_credentials():
+ old_credentials = oauth2client.contrib.gce.AppAssertionCredentials(
+ email='some_email')
+
+ new_credentials = _oauth2client._convert_gce_app_assertion_credentials(
+ old_credentials)
+
+ assert (new_credentials._service_account_email ==
+ old_credentials.service_account_email)
+
+
+@pytest.fixture
+def mock_oauth2client_gae_imports(mock_non_existent_module):
+ mock_non_existent_module('google.appengine.api.app_identity')
+ mock_non_existent_module('google.appengine.ext.ndb')
+ mock_non_existent_module('google.appengine.ext.webapp.util')
+ mock_non_existent_module('webapp2')
+
+
+@mock.patch('google.auth.app_engine.app_identity')
+def test__convert_appengine_app_assertion_credentials(
+ app_identity, mock_oauth2client_gae_imports):
+
+ import oauth2client.contrib.appengine
+
+ service_account_id = 'service_account_id'
+ old_credentials = oauth2client.contrib.appengine.AppAssertionCredentials(
+ scope='one two', service_account_id=service_account_id)
+
+ new_credentials = (
+ _oauth2client._convert_appengine_app_assertion_credentials(
+ old_credentials))
+
+ assert new_credentials.scopes == ['one', 'two']
+ assert (new_credentials._service_account_id ==
+ old_credentials.service_account_id)
+
+
+class MockCredentials(object):
+ pass
+
+
+def test_convert_success():
+ convert_function = mock.Mock()
+ conversion_map_patch = mock.patch.object(
+ _oauth2client, '_CLASS_CONVERSION_MAP',
+ {MockCredentials: convert_function})
+ credentials = MockCredentials()
+
+ with conversion_map_patch:
+ result = _oauth2client.convert(credentials)
+
+ convert_function.assert_called_once_with(credentials)
+ assert result == convert_function.return_value
+
+
+def test_convert_not_found():
+ with pytest.raises(ValueError) as excinfo:
+ _oauth2client.convert('a string is not a real credentials class')
+
+ assert excinfo.match('Unable to convert')
+
+
+@pytest.fixture
+def reset__oauth2client_module():
+ """Reloads the _oauth2client module after a test."""
+ reload_module(_oauth2client)
+
+
+def test_import_has_app_engine(
+ mock_oauth2client_gae_imports, reset__oauth2client_module):
+ reload_module(_oauth2client)
+ assert _oauth2client._HAS_APPENGINE
+
+
+def test_import_without_oauth2client(monkeypatch, reset__oauth2client_module):
+ monkeypatch.setitem(sys.modules, 'oauth2client', None)
+ with pytest.raises(ImportError) as excinfo:
+ reload_module(_oauth2client)
+
+ assert excinfo.match('oauth2client')
diff --git a/tox.ini b/tox.ini
index c77487c..ad760bd 100644
--- a/tox.ini
+++ b/tox.ini
@@ -11,6 +11,7 @@
urllib3
certifi
requests
+ oauth2client
grpcio; platform_python_implementation != 'PyPy'
commands =
py.test --cov=google.auth --cov=google.oauth2 --cov=tests {posargs:tests}