Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add transport #2

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion google/auth/_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ def _get_gae_credentials():


def _get_gce_credentials():
if _metadata.ping():
# TODO: Ping now requires a request argument. Figure out how to deal with

This comment was marked as spam.

This comment was marked as spam.

# that.
if _metadata.ping(request=None):
return compute_engine.Credentials()


Expand Down
47 changes: 26 additions & 21 deletions google/auth/compute_engine/_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from six.moves.urllib import parse as urlparse

from google.auth import _helpers
from google.auth import transport
from google.auth import exceptions

_METADATA_ROOT = 'http://metadata.google.internal/computeMetadata/v1/'

Expand All @@ -42,10 +42,12 @@
_METADATA_DEFAULT_TIMEOUT = 3


def ping(timeout=_METADATA_DEFAULT_TIMEOUT):
def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT):
"""Checks to see if the metadata server is available.

Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.
timeout (int): How long to wait for the metadata server to respond.

Returns:
Expand All @@ -58,8 +60,8 @@ def ping(timeout=_METADATA_DEFAULT_TIMEOUT):
# the metadata resolution was particularly slow. The latter case is
# "unlikely".
try:
response = transport.request(
None, 'GET', _METADATA_IP_ROOT, headers=_METADATA_HEADERS,
response = request(
'GET', _METADATA_IP_ROOT, headers=_METADATA_HEADERS,
timeout=timeout, retries=False)
return response.status == http_client.OK

Expand All @@ -70,11 +72,12 @@ def ping(timeout=_METADATA_DEFAULT_TIMEOUT):
return False


def get(http, path, root=_METADATA_ROOT, recursive=None):
def get(request, path, root=_METADATA_ROOT, recursive=None):
"""Fetch a resource from the metadata server.

Args:
http (Any): The transport HTTP object.
request (google.auth.transport.Request): A callable used to make
HTTP requests.
path (str): The resource to retrieve. For example,
``'instance/service-accounts/defualt'``.
root (str): The full path to the metadata server root.
Expand All @@ -88,13 +91,13 @@ def get(http, path, root=_METADATA_ROOT, recursive=None):
returned as a string.

Raises:
http_client.HTTPException: if an error occurred while retrieving
metadata.
google.auth.exceptions.TransportError: if an error occurred while
retrieving metadata.
"""
url = urlparse.urljoin(root, path)
url = _helpers.update_query(url, {'recursive': recursive})

response = transport.request(http, 'GET', url, headers=_METADATA_HEADERS)
response = request('GET', url, headers=_METADATA_HEADERS)

if response.status == http_client.OK:
content = _helpers.from_bytes(response.data)
Expand All @@ -103,17 +106,18 @@ def get(http, path, root=_METADATA_ROOT, recursive=None):
else:
return content
else:
raise http_client.HTTPException(
raise exceptions.TransportError(
'Failed to retrieve {} from the Google Compute Engine'
'metadata service. Status: {} Response:\n{}'.format(
url, response.status, response.data))
url, response.status, response.data), response)


def get_service_account_info(http, service_account='default'):
def get_service_account_info(request, service_account='default'):
"""Get information about a service account from the metadata server.

Args:
http (Any): The transport HTTP object.
request (google.auth.transport.Request): A callable used to make
HTTP requests.
service_account (str): The string 'default' or a service account email
address. The determines which service account for which to acquire
information.
Expand All @@ -128,20 +132,21 @@ def get_service_account_info(http, service_account='default'):
}

Raises:
http_client.HTTPException: if an error occurred while retrieving
metadata.
google.auth.exceptions.TransportError: if an error occurred while
retrieving metadata.
"""
return get(
http,
request,
'instance/service-accounts/{0}/'.format(service_account),
recursive=True)


def get_service_account_token(http, service_account='default'):
def get_service_account_token(request, service_account='default'):
"""Get the OAuth 2.0 access token for a service account.

Args:
http (Any): The transport HTTP object.
request (google.auth.transport.Request): A callable used to make
HTTP requests.
service_account (str): The string 'default' or a service account email
address. The determines which service account for which to acquire
an access token.
Expand All @@ -150,11 +155,11 @@ def get_service_account_token(http, service_account='default'):
Union[str, datetime]: The access token and its expiration.

Raises:
http_client.HTTPException: if an error occurred while retrieving
metadata.
google.auth.exceptions.TransportError: if an error occurred while
retrieving metadata.
"""
token_json = get(
http,
request,
'instance/service-accounts/{0}/token'.format(service_account))
token_expiry = _helpers.now() + datetime.timedelta(
seconds=token_json['expires_in'])
Expand Down
12 changes: 7 additions & 5 deletions google/auth/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,12 @@ def expired(self):
return True

@abc.abstractmethod
def refresh(self, http):
def refresh(self, request):
"""Refreshes the access token.

Args:
http (Any): The transport http object.
request (google.auth.transport.Request): A callable used to make
HTTP requests.

Raises:
google.auth.exceptions.RefreshError: If the credentials could
Expand All @@ -97,14 +98,15 @@ def apply(self, headers, token=None):
headers[b'authorization'] = 'Bearer {}'.format(
_helpers.from_bytes(token or self.token))

def before_request(self, http, method, url, headers):
def before_request(self, request, method, url, headers):
"""Performs credential-specific before request logic.

Refreshes the credentials if necessary, then calls :meth:`apply` to
apply the token to the authentication header.

Args:
http (Any): The transport HTTP object.
request (google.auth.transport.Request): A callable used to make
HTTP requests.
method (str): The request's HTTP method.
url (str): The request's URI.
headers (Mapping): The request's headers.
Expand All @@ -113,7 +115,7 @@ def before_request(self, http, method, url, headers):
# (Subclasses may use these arguments to ascertain information about
# the http request.)
if not self.valid:
self.refresh(http)
self.refresh(request)
self.apply(headers)


Expand Down
5 changes: 5 additions & 0 deletions google/auth/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ class GoogleAuthError(Exception):
pass


class TransportError(Exception):
"""Used to indicate an error occurred during an HTTP request."""
pass

This comment was marked as spam.

This comment was marked as spam.



class RefreshError(GoogleAuthError):
"""Used to indicate that an error occurred while refreshing the
credentials' access token."""
Expand Down
10 changes: 5 additions & 5 deletions google/auth/jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,11 +392,11 @@ def _make_one_time_jwt(self, uri):
token, _ = self._make_jwt(audience=audience)
return token

def refresh(self, http):
def refresh(self, request):
"""Refreshes the access token.

Args:
http (Any): The transport http object.
request (Any): Unused.
"""
# pylint: disable=unused-argument
# (pylint doens't correctly recognize overriden methods.)
Expand All @@ -414,7 +414,7 @@ def sign_bytes(self, message):
"""
return self._signer.sign(message)

def before_request(self, http, method, url, headers):
def before_request(self, request, method, url, headers):
"""Performs credential-specific before request logic.

If an audience is specified it will refresh the credentials if
Expand All @@ -423,7 +423,7 @@ def before_request(self, http, method, url, headers):
authorization header in headers to the token.

Args:
http (Any): The transport http object.
request (Any): Unused.
method (str): The request's HTTP method.
url (str): The request's URI.
headers (Mapping): The request's headers.
Expand All @@ -435,7 +435,7 @@ def before_request(self, http, method, url, headers):
# there is a valid token and apply the auth headers.
if self._audience:
if not self.valid:
self.refresh(http)
self.refresh(request)
self.apply(headers)
# Otherwise, generate a one-time token using the URL
# (without the query string and fragement) as the audience.
Expand Down
8 changes: 3 additions & 5 deletions google/auth/service_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@
from google.auth import credentials
from google.auth import exceptions
from google.auth import jwt
from google.auth import transport

_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in sections
_JWT_TOKEN_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
Expand Down Expand Up @@ -257,7 +256,7 @@ def _make_authorization_grant_assertion(self):
return token

@_helpers.copy_docstring(credentials.Credentials)
def refresh(self, http):
def refresh(self, request):
assertion = self._make_authorization_grant_assertion()

body = urllib.parse.urlencode({
Expand All @@ -269,9 +268,8 @@ def refresh(self, http):
'content-type': 'application/x-www-form-urlencoded',
}

response = transport.request(
http, method='POST', url=self._token_uri, headers=headers,
body=body)
response = request(
url=self._token_uri, method='POST', headers=headers, body=body)

if response.status != http_client.OK:
# Try to decode the response and extract details.
Expand Down
29 changes: 0 additions & 29 deletions google/auth/transport.py

This file was deleted.

82 changes: 82 additions & 0 deletions google/auth/transport/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Copyright 2016 Google Inc. All rights reserved.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

#
# 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.

"""Transport - HTTP client library support.

:mod:`google.auth` is designed to work with various HTTP client libraries such
as urllib3 and requests. In order to work across these libraries with different
interfaces some abstraction is needed.

This module provides two interfaces that are implemented by transport adapters
to support HTTP libraries. :class:`Request` defines the interface expected by
:mod:`google.auth` to make requests. :class:`Response` defines the interface
for the return value of :class:`Request`.
"""

import abc

import six


@six.add_metaclass(abc.ABCMeta)
class Response(object):
"""HTTP Response data."""

@abc.abstractproperty
def status(self):
"""int: The HTTP status code."""

@abc.abstractproperty
def headers(self):
"""Mapping: The HTTP response headers."""

@abc.abstractproperty
def data(self):
"""bytes: The response body."""


@six.add_metaclass(abc.ABCMeta)
class Request(object):
"""Interface for a callable that makes HTTP requests.

Specific transport implementations should provide an implementation of
this that adapts their specific request / response API.
"""

@abc.abstractmethod
def __call__(self, url, method='GET', body=None, headers=None,
timeout=None, **kwargs):
"""Make an HTTP request.

Args:
url (str): The URI to be requested.
method (str): The HTTP method to use for the request. Defaults
to 'GET'.
body (bytes): The payload / body in HTTP request.
headers (Mapping): Request headers.
timeout (Optional(int)): The number of seconds to wait for a
response from the server. If not specified or if None, the
transport-specific default timeout will be used.
kwargs: Additionally arguments passed on to the transport's
request method.

Returns:
Response: The HTTP response.

Raises:
google.auth.exceptions.TransportError: If any exception occurred.
"""
# pylint: disable=redundant-returns-doc, missing-raises-doc
# (pylint doesn't play well with abstract docstrings.)
raise NotImplementedError('__call__ must be implemented.')

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

Loading