Python google.auth.exceptions.TransportError() Examples

The following are 30 code examples of google.auth.exceptions.TransportError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module google.auth.exceptions , or try the search function .
Example #1
Source File: _metadata.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_service_account_token(request, service_account='default'):
    """Get the OAuth 2.0 access token for a service account.

    Args:
        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.

    Returns:
        Union[str, datetime]: The access token and its expiration.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    token_json = get(
        request,
        'instance/service-accounts/{0}/token'.format(service_account))
    token_expiry = _helpers.utcnow() + datetime.timedelta(
        seconds=token_json['expires_in'])
    return token_json['access_token'], token_expiry 
Example #2
Source File: _metadata.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def get_service_account_token(request, service_account="default"):
    """Get the OAuth 2.0 access token for a service account.

    Args:
        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.

    Returns:
        Union[str, datetime]: The access token and its expiration.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    token_json = get(
        request, "instance/service-accounts/{0}/token".format(service_account)
    )
    token_expiry = _helpers.utcnow() + datetime.timedelta(
        seconds=token_json["expires_in"]
    )
    return token_json["access_token"], token_expiry 
Example #3
Source File: credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
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 caught_exc:
            new_exc = exceptions.RefreshError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #4
Source File: iam.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def _make_signing_request(self, message):
        """Makes a request to the API signBlob API."""
        message = _helpers.to_bytes(message)

        method = "POST"
        url = _SIGN_BLOB_URI.format(self._service_account_email)
        headers = {}
        body = json.dumps(
            {"payload": base64.b64encode(message).decode("utf-8")}
        ).encode("utf-8")

        self._credentials.before_request(self._request, method, url, headers)
        response = self._request(url=url, method=method, body=body, headers=headers)

        if response.status != http_client.OK:
            raise exceptions.TransportError(
                "Error calling the IAM signBytes API: {}".format(response.data)
            )

        return json.loads(response.data.decode("utf-8")) 
Example #5
Source File: id_token.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def _fetch_certs(request, certs_url):
    """Fetches certificates.

    Google-style cerificate endpoints return JSON in the format of
    ``{'key id': 'x509 certificate'}``.

    Args:
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        certs_url (str): The certificate endpoint URL.

    Returns:
        Mapping[str, str]: A mapping of public key ID to x.509 certificate
            data.
    """
    response = request(certs_url, method="GET")

    if response.status != http_client.OK:
        raise exceptions.TransportError(
            "Could not fetch certificates at {}".format(certs_url)
        )

    return json.loads(response.data.decode("utf-8")) 
Example #6
Source File: _default.py    From alfred-gmail with MIT License 6 votes vote down vote up
def _get_gce_credentials(request=None):
    """Gets credentials and project ID from the GCE Metadata Service."""
    # Ping requires a transport, but we want application default credentials
    # to require no arguments. So, we'll use the _http_client transport which
    # uses http.client. This is only acceptable because the metadata server
    # doesn't do SSL and never requires proxies.
    from google.auth import compute_engine
    from google.auth.compute_engine import _metadata

    if request is None:
        request = google.auth.transport._http_client.Request()

    if _metadata.ping(request=request):
        # Get the project ID.
        try:
            project_id = _metadata.get_project_id(request=request)
        except exceptions.TransportError:
            project_id = None

        return compute_engine.Credentials(), project_id
    else:
        return None, None 
Example #7
Source File: credentials.py    From alfred-gmail with MIT License 6 votes vote down vote up
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 caught_exc:
            new_exc = exceptions.RefreshError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #8
Source File: _metadata.py    From alfred-gmail with MIT License 6 votes vote down vote up
def get_service_account_token(request, service_account='default'):
    """Get the OAuth 2.0 access token for a service account.

    Args:
        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.

    Returns:
        Union[str, datetime]: The access token and its expiration.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    token_json = get(
        request,
        'instance/service-accounts/{0}/token'.format(service_account))
    token_expiry = _helpers.utcnow() + datetime.timedelta(
        seconds=token_json['expires_in'])
    return token_json['access_token'], token_expiry 
Example #9
Source File: iam.py    From alfred-gmail with MIT License 6 votes vote down vote up
def _make_signing_request(self, message):
        """Makes a request to the API signBlob API."""
        message = _helpers.to_bytes(message)

        method = 'POST'
        url = _SIGN_BLOB_URI.format(self._service_account_email)
        headers = {}
        body = json.dumps({
            'bytesToSign': base64.b64encode(message).decode('utf-8'),
        })

        self._credentials.before_request(self._request, method, url, headers)
        response = self._request(
            url=url, method=method, body=body, headers=headers)

        if response.status != http_client.OK:
            raise exceptions.TransportError(
                'Error calling the IAM signBytes API: {}'.format(
                    response.data))

        return json.loads(response.data.decode('utf-8')) 
Example #10
Source File: id_token.py    From alfred-gmail with MIT License 6 votes vote down vote up
def _fetch_certs(request, certs_url):
    """Fetches certificates.

    Google-style cerificate endpoints return JSON in the format of
    ``{'key id': 'x509 certificate'}``.

    Args:
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        certs_url (str): The certificate endpoint URL.

    Returns:
        Mapping[str, str]: A mapping of public key ID to x.509 certificate
            data.
    """
    response = request(certs_url, method='GET')

    if response.status != http_client.OK:
        raise exceptions.TransportError(
            'Could not fetch certificates at {}'.format(certs_url))

    return json.loads(response.data.decode('utf-8')) 
Example #11
Source File: credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 caught_exc:
            new_exc = exceptions.RefreshError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #12
Source File: _metadata.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_service_account_token(request, service_account='default'):
    """Get the OAuth 2.0 access token for a service account.

    Args:
        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.

    Returns:
        Union[str, datetime]: The access token and its expiration.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    token_json = get(
        request,
        'instance/service-accounts/{0}/token'.format(service_account))
    token_expiry = _helpers.utcnow() + datetime.timedelta(
        seconds=token_json['expires_in'])
    return token_json['access_token'], token_expiry 
Example #13
Source File: _metadata.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_service_account_token(request, service_account='default'):
    """Get the OAuth 2.0 access token for a service account.

    Args:
        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.

    Returns:
        Union[str, datetime]: The access token and its expiration.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    token_json = get(
        request,
        'instance/service-accounts/{0}/token'.format(service_account))
    token_expiry = _helpers.utcnow() + datetime.timedelta(
        seconds=token_json['expires_in'])
    return token_json['access_token'], token_expiry 
Example #14
Source File: iam.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _make_signing_request(self, message):
        """Makes a request to the API signBlob API."""
        message = _helpers.to_bytes(message)

        method = 'POST'
        url = _SIGN_BLOB_URI.format(self._service_account_email)
        headers = {}
        body = json.dumps({
            'bytesToSign': base64.b64encode(message).decode('utf-8'),
        })

        self._credentials.before_request(self._request, method, url, headers)
        response = self._request(
            url=url, method=method, body=body, headers=headers)

        if response.status != http_client.OK:
            raise exceptions.TransportError(
                'Error calling the IAM signBytes API: {}'.format(
                    response.data))

        return json.loads(response.data.decode('utf-8')) 
Example #15
Source File: credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 caught_exc:
            new_exc = exceptions.RefreshError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #16
Source File: _metadata.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_service_account_token(request, service_account='default'):
    """Get the OAuth 2.0 access token for a service account.

    Args:
        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.

    Returns:
        Union[str, datetime]: The access token and its expiration.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    token_json = get(
        request,
        'instance/service-accounts/{0}/token'.format(service_account))
    token_expiry = _helpers.utcnow() + datetime.timedelta(
        seconds=token_json['expires_in'])
    return token_json['access_token'], token_expiry 
Example #17
Source File: iam.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _make_signing_request(self, message):
        """Makes a request to the API signBlob API."""
        message = _helpers.to_bytes(message)

        method = 'POST'
        url = _SIGN_BLOB_URI.format(self._service_account_email)
        headers = {}
        body = json.dumps({
            'bytesToSign': base64.b64encode(message).decode('utf-8'),
        })

        self._credentials.before_request(self._request, method, url, headers)
        response = self._request(
            url=url, method=method, body=body, headers=headers)

        if response.status != http_client.OK:
            raise exceptions.TransportError(
                'Error calling the IAM signBytes API: {}'.format(
                    response.data))

        return json.loads(response.data.decode('utf-8')) 
Example #18
Source File: credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 caught_exc:
            new_exc = exceptions.RefreshError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #19
Source File: _metadata.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_service_account_token(request, service_account='default'):
    """Get the OAuth 2.0 access token for a service account.

    Args:
        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.

    Returns:
        Union[str, datetime]: The access token and its expiration.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    token_json = get(
        request,
        'instance/service-accounts/{0}/token'.format(service_account))
    token_expiry = _helpers.utcnow() + datetime.timedelta(
        seconds=token_json['expires_in'])
    return token_json['access_token'], token_expiry 
Example #20
Source File: credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 caught_exc:
            new_exc = exceptions.RefreshError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #21
Source File: iam.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _make_signing_request(self, message):
        """Makes a request to the API signBlob API."""
        message = _helpers.to_bytes(message)

        method = 'POST'
        url = _SIGN_BLOB_URI.format(self._service_account_email)
        headers = {}
        body = json.dumps({
            'bytesToSign': base64.b64encode(message).decode('utf-8'),
        })

        self._credentials.before_request(self._request, method, url, headers)
        response = self._request(
            url=url, method=method, body=body, headers=headers)

        if response.status != http_client.OK:
            raise exceptions.TransportError(
                'Error calling the IAM signBytes API: {}'.format(
                    response.data))

        return json.loads(response.data.decode('utf-8')) 
Example #22
Source File: iam.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _make_signing_request(self, message):
        """Makes a request to the API signBlob API."""
        message = _helpers.to_bytes(message)

        method = 'POST'
        url = _SIGN_BLOB_URI.format(self._service_account_email)
        headers = {}
        body = json.dumps({
            'bytesToSign': base64.b64encode(message).decode('utf-8'),
        })

        self._credentials.before_request(self._request, method, url, headers)
        response = self._request(
            url=url, method=method, body=body, headers=headers)

        if response.status != http_client.OK:
            raise exceptions.TransportError(
                'Error calling the IAM signBytes API: {}'.format(
                    response.data))

        return json.loads(response.data.decode('utf-8')) 
Example #23
Source File: credentials.py    From luci-py with Apache License 2.0 6 votes vote down vote up
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 caught_exc:
            new_exc = exceptions.RefreshError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #24
Source File: requests.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def __call__(
        self,
        url,
        method="GET",
        body=None,
        headers=None,
        timeout=_DEFAULT_TIMEOUT,
        **kwargs
    ):
        """Make an HTTP request using requests.

        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[str, str]): Request headers.
            timeout (Optional[int]): The number of seconds to wait for a
                response from the server. If not specified or if None, the
                requests default timeout will be used.
            kwargs: Additional arguments passed through to the underlying
                requests :meth:`~requests.Session.request` method.

        Returns:
            google.auth.transport.Response: The HTTP response.

        Raises:
            google.auth.exceptions.TransportError: If any exception occurred.
        """
        try:
            _LOGGER.debug("Making request: %s %s", method, url)
            response = self.session.request(
                method, url, data=body, headers=headers, timeout=timeout, **kwargs
            )
            return _Response(response)
        except requests.exceptions.RequestException as caught_exc:
            new_exc = exceptions.TransportError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #25
Source File: _metadata.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_project_id(request):
    """Get the Google Cloud Project ID from the metadata server.

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

    Returns:
        str: The project ID

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    return get(request, 'project/project-id') 
Example #26
Source File: test__http_client.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def test_non_http(self):
        request = self.make_request()
        with pytest.raises(exceptions.TransportError) as excinfo:
            request(url="https://{}".format(compliance.NXDOMAIN), method="GET")

        assert excinfo.match("https") 
Example #27
Source File: test__metadata.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def test_get_failure_bad_json():
    request = make_request("{", headers={"content-type": "application/json"})

    with pytest.raises(exceptions.TransportError) as excinfo:
        _metadata.get(request, PATH)

    assert excinfo.match(r"invalid JSON")

    request.assert_called_once_with(
        method="GET",
        url=_metadata._METADATA_ROOT + PATH,
        headers=_metadata._METADATA_HEADERS,
    ) 
Example #28
Source File: urllib3.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __call__(self, url, method='GET', body=None, headers=None,
                 timeout=None, **kwargs):
        """Make an HTTP request using urllib3.

        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[str, str]): Request headers.
            timeout (Optional[int]): The number of seconds to wait for a
                response from the server. If not specified or if None, the
                urllib3 default timeout will be used.
            kwargs: Additional arguments passed throught to the underlying
                urllib3 :meth:`urlopen` method.

        Returns:
            google.auth.transport.Response: The HTTP response.

        Raises:
            google.auth.exceptions.TransportError: If any exception occurred.
        """
        # urllib3 uses a sentinel default value for timeout, so only set it if
        # specified.
        if timeout is not None:
            kwargs['timeout'] = timeout

        try:
            _LOGGER.debug('Making request: %s %s', method, url)
            response = self.http.request(
                method, url, body=body, headers=headers, **kwargs)
            return _Response(response)
        except urllib3.exceptions.HTTPError as caught_exc:
            new_exc = exceptions.TransportError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #29
Source File: requests.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __call__(self, url, method='GET', body=None, headers=None,
                 timeout=None, **kwargs):
        """Make an HTTP request using requests.

        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[str, str]): Request headers.
            timeout (Optional[int]): The number of seconds to wait for a
                response from the server. If not specified or if None, the
                requests default timeout will be used.
            kwargs: Additional arguments passed through to the underlying
                requests :meth:`~requests.Session.request` method.

        Returns:
            google.auth.transport.Response: The HTTP response.

        Raises:
            google.auth.exceptions.TransportError: If any exception occurred.
        """
        try:
            _LOGGER.debug('Making request: %s %s', method, url)
            response = self.session.request(
                method, url, data=body, headers=headers, timeout=timeout,
                **kwargs)
            return _Response(response)
        except requests.exceptions.RequestException as caught_exc:
            new_exc = exceptions.TransportError(caught_exc)
            six.raise_from(new_exc, caught_exc) 
Example #30
Source File: compliance.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def test_request_with_timeout_failure(self, server):
        request = self.make_request()

        with pytest.raises(exceptions.TransportError):
            request(url=server.url + "/wait", method="GET", timeout=1)