Repository: GoogleCloudPlatform/google-auth-library-python
Pull request #22 (2016-10-14 21:25:15)

Add compute engine credentials


Patch:
diff --git a/docs/reference/google.oauth2.credentials.rst b/docs/reference/google.oauth2.credentials.rst
new file mode 100644
index 0000000..ca978d1
--- /dev/null
+++ b/docs/reference/google.oauth2.credentials.rst
@@ -0,0 +1,7 @@
+google.oauth2.credentials module
+================================
+
+.. automodule:: google.oauth2.credentials
+    :members:
+    :inherited-members:
+    :show-inheritance:
diff --git a/google/auth/_helpers.py b/google/auth/_helpers.py
index 9c49e06..5a6c3a8 100644
--- a/google/auth/_helpers.py
+++ b/google/auth/_helpers.py
@@ -21,6 +21,38 @@ import six
 from six.moves import urllib
 
 
+def copy_docstring(source_class):
+    """Decorator that copies a method's docstring from another class.
+
+    Args:
+        source_class (type): The class that has the documented method.
+
+    Returns:
+        Callable: A decorator that will copy the docstring of the same
+            named method in the source class to the decorated method.
+    """
+    def decorator(method):
+        """Decorator implementation.
+
+        Args:
+            method (Callable): The method to copy the docstring to.
+
+        Returns:
+            Callable: the same method passed in with an updated docstring.
+
+        Raises:
+            ValueError: if the method already has a docstring.
+        """
+        if method.__doc__:
+            raise ValueError('Method already has a docstring.')
+
+        source_method = getattr(source_class, method.__name__)
+        method.__doc__ = source_method.__doc__
+
+        return method
+    return decorator
+
+
 def utcnow():
     """Returns the current UTC datetime.
 
diff --git a/google/auth/compute_engine/__init__.py b/google/auth/compute_engine/__init__.py
index e3a7f6c..3794be2 100644
--- a/google/auth/compute_engine/__init__.py
+++ b/google/auth/compute_engine/__init__.py
@@ -11,3 +11,12 @@
 # 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.
+
+"""Google Compute Engine authentication."""
+
+from google.auth.compute_engine.credentials import Credentials
+
+
+__all__ = [
+    'Credentials'
+]
diff --git a/google/auth/compute_engine/credentials.py b/google/auth/compute_engine/credentials.py
new file mode 100644
index 0000000..f0616d1
--- /dev/null
+++ b/google/auth/compute_engine/credentials.py
@@ -0,0 +1,113 @@
+# 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.
+
+"""Google Compute Engine credentials.
+
+This module provides authentication for application running on Google Compute
+Engine using the Compute Engine metadata server.
+
+"""
+
+from google.auth import _helpers
+from google.auth import credentials
+from google.auth import exceptions
+from google.auth.compute_engine import _metadata
+
+
+class Credentials(credentials.Scoped, credentials.Credentials):
+    """Compute Engine Credentials.
+
+    These credentials use the Google Compute Engine metadata server to obtain
+    OAuth 2.0 access tokens associated with the instance's service account.
+
+    For more information about Compute Engine authentication, including how
+    to configure scopes, see the `Compute Engine authentication
+    documentation`_.
+
+    .. note:: Compute Engine instances can be created with scopes and therefore
+        these credentials are considered to be 'scoped'. However, you can
+        not use :meth:`~google.auth.credentials.ScopedCredentials.with_scopes`
+        because it is not possible to change the scopes that the instance
+        has. Also note that
+        :meth:`~google.auth.credentials.ScopedCredentials.has_scopes` will not
+        work until the credentials have been refreshed.
+
+    .. _Compute Engine authentication documentation:
+        https://cloud.google.com/compute/docs/authentication#using
+    """
+
+    def __init__(self, service_account_email='default'):
+        """
+        Args:
+            service_account_email (str): The service account email to use, or
+                'default'. A Compute Engine instance may have multiple service
+                accounts.
+        """
+        super(Credentials, self).__init__()
+        self._service_account_email = service_account_email
+
+    def _retrieve_info(self, request):
+        """Retrieve information about the service account.
+
+        Updates the scopes and retrieves the full service account email.
+
+        Args:
+            request (google.auth.transport.Request): The object used to make
+                HTTP requests.
+        """
+        info = _metadata.get_service_account_info(
+            request,
+            service_account=self._service_account_email)
+
+        self._service_account_email = info['email']
+        self._scopes = _helpers.string_to_scopes(info['scopes'])
+
+    def refresh(self, request):
+        """Refresh the access token and scopes.
+
+        Args:
+            request (google.auth.transport.Request): The object used to make
+                HTTP requests.
+
+        Raises:
+            google.auth.exceptions.RefreshError: If the Compute Engine metadata
+                service can't be reached if if the instance has not
+                credentials.
+        """
+        try:
+            self._retrieve_info(request)
+            self.token, self.expiry = _metadata.get_service_account_token(
+                request,
+                service_account=self._service_account_email)
+        except exceptions.TransportError as exc:
+            raise exceptions.RefreshError(exc)
+
+    @property
+    def requires_scopes(self):
+        """False: Compute Engine credentials can not be scoped."""
+        return False
+
+    def with_scopes(self, scopes):
+        """Unavailable, Compute Engine credentials can not be scoped.
+
+        Scopes can only be set at Compute Engine instance creation time.
+        See the `Compute Engine authentication documentation`_ for details on
+        how to configure instance scopes.
+
+        .. _Compute Engine authentication documentation:
+            https://cloud.google.com/compute/docs/authentication#using
+        """
+        raise NotImplementedError(
+            'Compute Engine credentials can not set scopes. Scopes must be '
+            'set when the Compute Engine instance is created.')
diff --git a/google/auth/credentials.py b/google/auth/credentials.py
index b10e63e..ef28bd7 100644
--- a/google/auth/credentials.py
+++ b/google/auth/credentials.py
@@ -102,7 +102,7 @@ class Credentials(object):
         apply the token to the authentication header.
 
         Args:
-            request (google.auth.transport.Request): the object used to make
+            request (google.auth.transport.Request): The object used to make
                 HTTP requests.
             method (str): The request's HTTP method.
             url (str): The request's URI.
diff --git a/google/oauth2/credentials.py b/google/oauth2/credentials.py
new file mode 100644
index 0000000..9727e18
--- /dev/null
+++ b/google/oauth2/credentials.py
@@ -0,0 +1,94 @@
+# 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.
+
+"""OAuth 2.0 Credentials.
+
+This module provides credentials based on OAuth 2.0 access and refresh tokens.
+These credentials usually access resources on behalf of a user (resource
+owner).
+
+Specifically, this is intended to use access tokens acquired using the
+`Authorization Code grant`_ and can refresh those tokens using a
+optional `refresh token`_.
+
+Obtaining the initial access and refresh token is outside of the scope of this
+module. Consult `rfc6749 section 4.1`_ for complete details on the
+Authorization Code grant flow.
+
+.. _Authorization Code grant: https://tools.ietf.org/html/rfc6749#section-1.3.1
+.. _refresh token: https://tools.ietf.org/html/rfc6749#section-6
+.. _rfc6749 section 4.1: https://tools.ietf.org/html/rfc6749#section-4.1
+"""
+
+from google.auth import _helpers
+from google.auth import credentials
+from google.oauth2 import _client
+
+
+class Credentials(credentials.Scoped, credentials.Credentials):
+    """Credentials using OAuth 2.0 access and refresh tokens."""
+
+    def __init__(self, token, refresh_token=None, token_uri=None,
+                 client_id=None, client_secret=None, scopes=None):
+        """
+        Args:
+            token (Optional(str)): The OAuth 2.0 access token. Can be None
+                if refresh information is provided.
+            refresh_token (str): The OAuth 2.0 refresh token. If specified,
+                credentials can be refreshed.
+            token_uri (str): The OAuth 2.0 authorization server's token
+                endpoint URI. Must be specified for refresh, can be left as
+                None if the token can not be refreshed.
+            client_id (str): The OAuth 2.0 client ID. Must be specified for
+                refresh, can be left as None if the token can not be refreshed.
+            client_secret(str): The OAuth 2.0 client secret. Must be specified
+                for refresh, can be left as None if the token can not be
+                refreshed.
+            scopes (Sequence[str]): The scopes that were originally used
+                to obtain authorization. This is a purely informative parameter
+                that can be used by :meth:`has_scopes`. OAuth 2.0 credentials
+                can not request additional scopes after authorization.
+        """
+        super(Credentials, self).__init__()
+        self.token = token
+        self._refresh_token = refresh_token
+        self._scopes = scopes
+        self._token_uri = token_uri
+        self._client_id = client_id
+        self._client_secret = client_secret
+
+    @property
+    def requires_scopes(self):
+        """False: OAuth 2.0 credentials have their scopes set when
+        the initial token is requested and can not be changed."""
+        return False
+
+    def with_scopes(self, scopes):
+        """Unavailable, OAuth 2.0 credentials can not be re-scoped.
+
+        OAuth 2.0 credentials have their scopes set when the initial token is
+        requested and can not be changed.
+        """
+        raise NotImplementedError(
+            'OAuth 2.0 Credentials can not modify their scopes.')
+
+    @_helpers.copy_docstring(credentials.Credentials)
+    def refresh(self, request):
+        access_token, refresh_token, expiry, _ = _client.refresh_grant(
+            request, self._token_uri, self._refresh_token, self._client_id,
+            self._client_secret)
+
+        self.token = access_token
+        self.expiry = expiry
+        self._refresh_token = refresh_token


Test patch:
diff --git a/tests/compute_engine/test_credentials.py b/tests/compute_engine/test_credentials.py
new file mode 100644
index 0000000..90ce2fe
--- /dev/null
+++ b/tests/compute_engine/test_credentials.py
@@ -0,0 +1,105 @@
+# 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 mock
+import pytest
+
+from google.auth import exceptions
+from google.auth.compute_engine import credentials
+
+
+class TestCredentials(object):
+    credentials = None
+
+    @pytest.fixture(autouse=True)
+    def credentials_fixture(self):
+        self.credentials = credentials.Credentials()
+
+    def test_default_state(self):
+        assert not self.credentials.valid
+        # Expiration hasn't been set yet
+        assert not self.credentials.expired
+        # Scopes aren't needed
+        assert not self.credentials.requires_scopes
+
+    @mock.patch(
+        'google.auth._helpers.utcnow', return_value=datetime.datetime.min)
+    @mock.patch('google.auth.compute_engine._metadata.get')
+    def test_refresh_success(self, get_mock, now_mock):
+        get_mock.side_effect = [{
+            # First request is for sevice account info.
+            'email': 'service-account@example.com',
+            'scopes': 'one two'
+        }, {
+            # Second request is for the token.
+            'access_token': 'token',
+            'expires_in': 500
+        }]
+
+        # Refresh credentials
+        self.credentials.refresh(None)
+
+        # Check that the credentials have the token and proper expiration
+        assert self.credentials.token == 'token'
+        assert self.credentials.expiry == (
+            datetime.datetime.min + datetime.timedelta(seconds=500))
+
+        # Check the credential info
+        assert (self.credentials._service_account_email ==
+                'service-account@example.com')
+        assert self.credentials._scopes == ['one', 'two']
+
+        # Check that the credentials are valid (have a token and are not
+        # expired)
+        assert self.credentials.valid
+
+    @mock.patch('google.auth.compute_engine._metadata.get')
+    def test_refresh_error(self, get_mock):
+        get_mock.side_effect = exceptions.TransportError('http error')
+
+        with pytest.raises(exceptions.RefreshError) as excinfo:
+            self.credentials.refresh(None)
+
+        assert excinfo.match(r'http error')
+
+    @mock.patch('google.auth.compute_engine._metadata.get')
+    def test_before_request_refreshes(self, get_mock):
+        get_mock.side_effect = [{
+            # First request is for sevice account info.
+            'email': 'service-account@example.com',
+            'scopes': 'one two'
+        }, {
+            # Second request is for the token.
+            'access_token': 'token',
+            'expires_in': 500
+        }]
+
+        # Credentials should start as invalid
+        assert not self.credentials.valid
+
+        # before_request should cause a refresh
+        self.credentials.before_request(
+            mock.Mock(), 'GET', 'http://example.com?a=1#3', {})
+
+        # The refresh endpoint should've been called.
+        assert get_mock.called
+
+        # Credentials should now be valid.
+        assert self.credentials.valid
+
+    def test_with_scopes(self):
+        with pytest.raises(NotImplementedError):
+            self.credentials.with_scopes(['one', 'two'])
diff --git a/tests/oauth2/test_credentials.py b/tests/oauth2/test_credentials.py
new file mode 100644
index 0000000..173bb00
--- /dev/null
+++ b/tests/oauth2/test_credentials.py
@@ -0,0 +1,79 @@
+# 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 mock
+import pytest
+
+from google.auth import _helpers
+from google.oauth2 import credentials
+
+
+class TestCredentials(object):
+    TOKEN_URI = 'https://example.com/oauth2/token'
+    REFRESH_TOKEN = 'refresh_token'
+    CLIENT_ID = 'client_id'
+    CLIENT_SECRET = 'client_secret'
+
+    @pytest.fixture(autouse=True)
+    def credentials(self):
+        self.credentials = credentials.Credentials(
+            token=None, refresh_token=self.REFRESH_TOKEN,
+            token_uri=self.TOKEN_URI, client_id=self.CLIENT_ID,
+            client_secret=self.CLIENT_SECRET)
+
+    def test_default_state(self):
+        assert not self.credentials.valid
+        # Expiration hasn't been set yet
+        assert not self.credentials.expired
+        # Scopes aren't required for these credentials
+        assert not self.credentials.requires_scopes
+
+    def test_create_scoped(self):
+        with pytest.raises(NotImplementedError):
+            self.credentials.with_scopes(['email'])
+
+    @mock.patch('google.oauth2._client.refresh_grant')
+    @mock.patch(
+        'google.auth._helpers.utcnow', return_value=datetime.datetime.min)
+    def test_refresh_success(self, now_mock, refresh_grant_mock):
+        token = 'token'
+        expiry = _helpers.utcnow() + datetime.timedelta(seconds=500)
+        refresh_grant_mock.return_value = (
+            # Access token
+            token,
+            # New refresh token
+            None,
+            # Expiry,
+            expiry,
+            # Extra data
+            {})
+        request_mock = mock.Mock()
+
+        # Refresh credentials
+        self.credentials.refresh(request_mock)
+
+        # Check jwt grant call.
+        refresh_grant_mock.assert_called_with(
+            request_mock, self.TOKEN_URI, self.REFRESH_TOKEN, self.CLIENT_ID,
+            self.CLIENT_SECRET)
+
+        # Check that the credentials have the token and expiry
+        assert self.credentials.token == token
+        assert self.credentials.expiry == expiry
+
+        # Check that the credentials are valid (have a token and are not
+        # expired)
+        assert self.credentials.valid
diff --git a/tests/test__helpers.py b/tests/test__helpers.py
index 86cacef..d413adc 100644
--- a/tests/test__helpers.py
+++ b/tests/test__helpers.py
@@ -20,6 +20,37 @@ from six.moves import urllib
 from google.auth import _helpers
 
 
+class SourceClass(object):
+    def func(self):  # pragma: NO COVER
+        """example docstring"""
+
+
+def test_copy_docstring_success():
+    def func():  # pragma: NO COVER
+        pass
+
+    _helpers.copy_docstring(SourceClass)(func)
+
+    assert func.__doc__ == SourceClass.func.__doc__
+
+
+def test_copy_docstring_conflict():
+    def func():  # pragma: NO COVER
+        """existing docstring"""
+        pass
+
+    with pytest.raises(ValueError):
+        _helpers.copy_docstring(SourceClass)(func)
+
+
+def test_copy_docstring_non_existing():
+    def func2():  # pragma: NO COVER
+        pass
+
+    with pytest.raises(AttributeError):
+        _helpers.copy_docstring(SourceClass)(func2)
+
+
 def test_utcnow():
     assert isinstance(_helpers.utcnow(), datetime.datetime)