Python google.auth.exceptions.RefreshError() Examples

The following are 30 code examples of google.auth.exceptions.RefreshError(). 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: 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 #2
Source File: test_credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def test_refresh_error(self, sign, get, utcnow):
        get.side_effect = [
            {"email": "service-account@example.com", "scopes": ["one", "two"]}
        ]
        sign.side_effect = [b"signature"]

        request = mock.create_autospec(transport.Request, instance=True)
        response = mock.Mock()
        response.data = b'{"error": "http error"}'
        response.status = 500
        request.side_effect = [response]

        self.credentials = credentials.IDTokenCredentials(
            request=request, target_audience="https://audience.com"
        )

        with pytest.raises(exceptions.RefreshError) as excinfo:
            self.credentials.refresh(request)

        assert excinfo.match(r"http error") 
Example #3
Source File: test_impersonated_credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def test_refresh_failure_unauthorzed(self, mock_donor_credentials):
        credentials = self.make_credentials(lifetime=None)

        response_body = {
            "error": {
                "code": 403,
                "message": "The caller does not have permission",
                "status": "PERMISSION_DENIED",
            }
        }

        request = self.make_request(
            data=json.dumps(response_body), status=http_client.UNAUTHORIZED
        )

        with pytest.raises(exceptions.RefreshError) as excinfo:
            credentials.refresh(request)

        assert excinfo.match(impersonated_credentials._REFRESH_ERROR)

        assert not credentials.valid
        assert credentials.expired 
Example #4
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 #5
Source File: test_impersonated_credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def test_refresh_failure_http_error(self, mock_donor_credentials):
        credentials = self.make_credentials(lifetime=None)

        response_body = {}

        request = self.make_request(
            data=json.dumps(response_body), status=http_client.HTTPException
        )

        with pytest.raises(exceptions.RefreshError) as excinfo:
            credentials.refresh(request)

        assert excinfo.match(impersonated_credentials._REFRESH_ERROR)

        assert not credentials.valid
        assert credentials.expired 
Example #6
Source File: _client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _handle_error_response(response_body):
    """"Translates an error response into an exception.

    Args:
        response_body (str): The decoded response data.

    Raises:
        google.auth.exceptions.RefreshError
    """
    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))
    # If no details could be extracted, use the response data.
    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body) 
Example #7
Source File: kaggle_gcp.py    From docker-python with Apache License 2.0 6 votes vote down vote up
def refresh(self, request):
        try:
            client = UserSecretsClient()
            if self.target == GcpTarget.BIGQUERY:
                self.token, self.expiry = client.get_bigquery_access_token()
            elif self.target == GcpTarget.GCS:
                self.token, self.expiry = client._get_gcs_access_token()
            elif self.target == GcpTarget.AUTOML:
                self.token, self.expiry = client._get_automl_access_token()
        except ConnectionError as e:
            Log.error(f"Connection error trying to refresh access token: {e}")
            print("There was a connection error trying to fetch the access token. "
                  f"Please ensure internet is on in order to use the {self.target.service} Integration.")
            raise RefreshError('Unable to refresh access token due to connection error.') from e
        except Exception as e:
            Log.error(f"Error trying to refresh access token: {e}")
            if (not get_integrations().has_integration(self.target)):
                Log.error(f"No {self.target.service} integration found.")
                print(
                   f"Please ensure you have selected a {self.target.service} account in the Notebook Add-ons menu.")
            raise RefreshError('Unable to refresh access token.') from e 
Example #8
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 #9
Source File: _client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _handle_error_response(response_body):
    """"Translates an error response into an exception.

    Args:
        response_body (str): The decoded response data.

    Raises:
        google.auth.exceptions.RefreshError
    """
    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))
    # If no details could be extracted, use the response data.
    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body) 
Example #10
Source File: test__client.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def test__token_endpoint_request_internal_failure_error():
    request = make_request(
        {"error_description": "internal_failure"}, status=http_client.BAD_REQUEST
    )

    with pytest.raises(exceptions.RefreshError):
        _client._token_endpoint_request(
            request, "http://example.com", {"error_description": "internal_failure"}
        )

    request = make_request(
        {"error": "internal_failure"}, status=http_client.BAD_REQUEST
    )

    with pytest.raises(exceptions.RefreshError):
        _client._token_endpoint_request(
            request, "http://example.com", {"error": "internal_failure"}
        ) 
Example #11
Source File: _client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _handle_error_response(response_body):
    """"Translates an error response into an exception.

    Args:
        response_body (str): The decoded response data.

    Raises:
        google.auth.exceptions.RefreshError
    """
    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))
    # If no details could be extracted, use the response data.
    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body) 
Example #12
Source File: credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def refresh(self, request):
        """Refreshes the ID token.

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

        Raises:
            google.auth.exceptions.RefreshError: If the credentials could
                not be refreshed.
            ValueError: If extracting expiry from the obtained ID token fails.
        """
        if self._use_metadata_identity_endpoint:
            self.token, self.expiry = self._call_metadata_identity_endpoint(request)
        else:
            assertion = self._make_authorization_grant_assertion()
            access_token, expiry, _ = _client.id_token_jwt_grant(
                request, self._token_uri, assertion
            )
            self.token = access_token
            self.expiry = expiry 
Example #13
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 #14
Source File: _client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _handle_error_response(response_body):
    """"Translates an error response into an exception.

    Args:
        response_body (str): The decoded response data.

    Raises:
        google.auth.exceptions.RefreshError
    """
    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))
    # If no details could be extracted, use the response data.
    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body) 
Example #15
Source File: _client.py    From alfred-gmail with MIT License 6 votes vote down vote up
def _handle_error_response(response_body):
    """"Translates an error response into an exception.

    Args:
        response_body (str): The decoded response data.

    Raises:
        google.auth.exceptions.RefreshError
    """
    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))
    # If no details could be extracted, use the response data.
    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body) 
Example #16
Source File: credentials.py    From alfred-gmail with MIT License 6 votes vote down vote up
def refresh(self, request):
        if (self._refresh_token is None or
                self._token_uri is None or
                self._client_id is None or
                self._client_secret is None):
            raise exceptions.RefreshError(
                'The credentials do not contain the necessary fields need to '
                'refresh the access token. You must specify refresh_token, '
                'token_uri, client_id, and client_secret.')

        access_token, refresh_token, expiry, grant_response = (
            _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
        self._id_token = grant_response.get('id_token') 
Example #17
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 #18
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 #19
Source File: _client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _handle_error_response(response_body):
    """"Translates an error response into an exception.

    Args:
        response_body (str): The decoded response data.

    Raises:
        google.auth.exceptions.RefreshError
    """
    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))
    # If no details could be extracted, use the response data.
    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body) 
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: _client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _handle_error_response(response_body):
    """"Translates an error response into an exception.

    Args:
        response_body (str): The decoded response data.

    Raises:
        google.auth.exceptions.RefreshError
    """
    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))
    # If no details could be extracted, use the response data.
    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body) 
Example #22
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 #23
Source File: credentials.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):
        if (self._refresh_token is None or
                self._token_uri is None or
                self._client_id is None or
                self._client_secret is None):
            raise exceptions.RefreshError(
                'The credentials do not contain the necessary fields need to '
                'refresh the access token. You must specify refresh_token, '
                'token_uri, client_id, and client_secret.')

        access_token, refresh_token, expiry, grant_response = (
            _client.refresh_grant(
                request, self._token_uri, self._refresh_token, self._client_id,
                self._client_secret, self._scopes))

        self.token = access_token
        self.expiry = expiry
        self._refresh_token = refresh_token
        self._id_token = grant_response.get('id_token')

        if self._scopes and 'scopes' in grant_response:
            requested_scopes = frozenset(self._scopes)
            granted_scopes = frozenset(grant_response['scopes'].split())
            scopes_requested_but_not_granted = (
                requested_scopes - granted_scopes)
            if scopes_requested_but_not_granted:
                raise exceptions.RefreshError(
                    'Not all requested scopes were granted by the '
                    'authorization server, missing scopes {}.'.format(
                        ', '.join(scopes_requested_but_not_granted))) 
Example #24
Source File: _client.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def jwt_grant(request, token_uri, assertion):
    """Implements the JWT Profile for OAuth 2.0 Authorization Grants.

    For more details, see `rfc7523 section 4`_.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        assertion (str): The OAuth 2.0 assertion.

    Returns:
        Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
            expiration, and additional data returned by the token endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.

    .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
    """
    body = {
        'assertion': assertion,
        'grant_type': _JWT_GRANT_TYPE,
    }

    response_data = _token_endpoint_request(request, token_uri, body)

    try:
        access_token = response_data['access_token']
    except KeyError as caught_exc:
        new_exc = exceptions.RefreshError(
            'No access token in response.', response_data)
        six.raise_from(new_exc, caught_exc)

    expiry = _parse_expiry(response_data)

    return access_token, expiry, response_data 
Example #25
Source File: jwt.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):
        """Raises an exception, these credentials can not be directly
        refreshed.

        Args:
            request (Any): Unused.

        Raises:
            google.auth.RefreshError
        """
        # pylint: disable=unused-argument
        # (pylint doesn't correctly recognize overridden methods.)
        raise exceptions.RefreshError(
            'OnDemandCredentials can not be directly refreshed.') 
Example #26
Source File: credentials.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):
        if (self._refresh_token is None or
                self._token_uri is None or
                self._client_id is None or
                self._client_secret is None):
            raise exceptions.RefreshError(
                'The credentials do not contain the necessary fields need to '
                'refresh the access token. You must specify refresh_token, '
                'token_uri, client_id, and client_secret.')

        access_token, refresh_token, expiry, grant_response = (
            _client.refresh_grant(
                request, self._token_uri, self._refresh_token, self._client_id,
                self._client_secret, self._scopes))

        self.token = access_token
        self.expiry = expiry
        self._refresh_token = refresh_token
        self._id_token = grant_response.get('id_token')

        if self._scopes and 'scopes' in grant_response:
            requested_scopes = frozenset(self._scopes)
            granted_scopes = frozenset(grant_response['scopes'].split())
            scopes_requested_but_not_granted = (
                requested_scopes - granted_scopes)
            if scopes_requested_but_not_granted:
                raise exceptions.RefreshError(
                    'Not all requested scopes were granted by the '
                    'authorization server, missing scopes {}.'.format(
                        ', '.join(scopes_requested_but_not_granted))) 
Example #27
Source File: jwt.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):
        """Raises an exception, these credentials can not be directly
        refreshed.

        Args:
            request (Any): Unused.

        Raises:
            google.auth.RefreshError
        """
        # pylint: disable=unused-argument
        # (pylint doesn't correctly recognize overridden methods.)
        raise exceptions.RefreshError(
            'OnDemandCredentials can not be directly refreshed.') 
Example #28
Source File: jwt.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):
        """Raises an exception, these credentials can not be directly
        refreshed.

        Args:
            request (Any): Unused.

        Raises:
            google.auth.RefreshError
        """
        # pylint: disable=unused-argument
        # (pylint doesn't correctly recognize overridden methods.)
        raise exceptions.RefreshError(
            'OnDemandCredentials can not be directly refreshed.') 
Example #29
Source File: credentials.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):
        if (self._refresh_token is None or
                self._token_uri is None or
                self._client_id is None or
                self._client_secret is None):
            raise exceptions.RefreshError(
                'The credentials do not contain the necessary fields need to '
                'refresh the access token. You must specify refresh_token, '
                'token_uri, client_id, and client_secret.')

        access_token, refresh_token, expiry, grant_response = (
            _client.refresh_grant(
                request, self._token_uri, self._refresh_token, self._client_id,
                self._client_secret, self._scopes))

        self.token = access_token
        self.expiry = expiry
        self._refresh_token = refresh_token
        self._id_token = grant_response.get('id_token')

        if self._scopes and 'scopes' in grant_response:
            requested_scopes = frozenset(self._scopes)
            granted_scopes = frozenset(grant_response['scopes'].split())
            scopes_requested_but_not_granted = (
                requested_scopes - granted_scopes)
            if scopes_requested_but_not_granted:
                raise exceptions.RefreshError(
                    'Not all requested scopes were granted by the '
                    'authorization server, missing scopes {}.'.format(
                        ', '.join(scopes_requested_but_not_granted))) 
Example #30
Source File: credentials.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def refresh(self, request):
        if (self._refresh_token is None or
                self._token_uri is None or
                self._client_id is None or
                self._client_secret is None):
            raise exceptions.RefreshError(
                'The credentials do not contain the necessary fields need to '
                'refresh the access token. You must specify refresh_token, '
                'token_uri, client_id, and client_secret.')

        access_token, refresh_token, expiry, grant_response = (
            _client.refresh_grant(
                request, self._token_uri, self._refresh_token, self._client_id,
                self._client_secret, self._scopes))

        self.token = access_token
        self.expiry = expiry
        self._refresh_token = refresh_token
        self._id_token = grant_response.get('id_token')

        if self._scopes and 'scopes' in grant_response:
            requested_scopes = frozenset(self._scopes)
            granted_scopes = frozenset(grant_response['scopes'].split())
            scopes_requested_but_not_granted = (
                requested_scopes - granted_scopes)
            if scopes_requested_but_not_granted:
                raise exceptions.RefreshError(
                    'Not all requested scopes were granted by the '
                    'authorization server, missing scopes {}.'.format(
                        ', '.join(scopes_requested_but_not_granted)))