Exemplo n.º 1
0
    def _get_token(cls, request, scopes=None):
        token_url = "instance/service-accounts/default/token"

        if scopes:
            if not isinstance(scopes, str):
                scopes = ",".join(scopes)

            token_url = _helpers.update_query(token_url, {"scopes": scopes})

        token_data = _metadata.get(request, token_url)

        return token_data
 def revoke(self, request):
   query_params = {'token': self.refresh_token or self.token}
   token_revoke_uri = _helpers.update_query(GOOGLE_REVOKE_URI, query_params)
   headers = {
       'content-type': google_auth_client._URLENCODED_CONTENT_TYPE,  # pylint: disable=protected-access
   }
   response = request(token_revoke_uri, headers=headers)
   if response.status != http_client.OK:
     response_data = six.ensure_text(response.data)
     response_json = json.loads(response_data)
     error = response_json.get('error')
     error_description = response_json.get('error_description')
     raise TokenRevokeError(error, error_description)
Exemplo n.º 3
0
def get(request, path, root=_METADATA_ROOT, recursive=False):
    """Fetch a resource from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        path (str): The resource to retrieve. For example,
            ``'instance/service-accounts/default'``.
        root (str): The full path to the metadata server root.
        recursive (bool): Whether to do a recursive query of metadata. See
            https://cloud.google.com/compute/docs/metadata#aggcontents for more
            details.

    Returns:
        Union[Mapping, str]: If the metadata server returns JSON, a mapping of
            the decoded JSON is return. Otherwise, the response content is
            returned as a string.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    base_url = urlparse.urljoin(root, path)
    query_params = {}

    if recursive:
        query_params["recursive"] = "true"

    url = _helpers.update_query(base_url, query_params)

    response = request(url=url, method="GET", headers=_METADATA_HEADERS)

    if response.status == http_client.OK:
        content = _helpers.from_bytes(response.data)
        if response.headers["content-type"] == "application/json":
            try:
                return json.loads(content)
            except ValueError as caught_exc:
                new_exc = exceptions.TransportError(
                    "Received invalid JSON from the Google Compute Engine"
                    "metadata service: {:.20}".format(content))
                six.raise_from(new_exc, caught_exc)
        else:
            return content
    else:
        raise exceptions.TransportError(
            "Failed to retrieve {} from the Google Compute Engine"
            "metadata service. Status: {} Response:\n{}".format(
                url, response.status, response.data),
            response,
        )
Exemplo n.º 4
0
def get(request, path, root=_METADATA_ROOT, recursive=False):
    """Fetch a resource from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        path (str): The resource to retrieve. For example,
            ``'instance/service-accounts/default'``.
        root (str): The full path to the metadata server root.
        recursive (bool): Whether to do a recursive query of metadata. See
            https://cloud.google.com/compute/docs/metadata#aggcontents for more
            details.

    Returns:
        Union[Mapping, str]: If the metadata server returns JSON, a mapping of
            the decoded JSON is return. Otherwise, the response content is
            returned as a string.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    base_url = urlparse.urljoin(root, path)
    query_params = {}

    if recursive:
        query_params['recursive'] = 'true'

    url = _helpers.update_query(base_url, query_params)

    response = request(url=url, method='GET', headers=_METADATA_HEADERS)

    if response.status == http_client.OK:
        content = _helpers.from_bytes(response.data)
        if response.headers['content-type'] == 'application/json':
            try:
                return json.loads(content)
            except ValueError as caught_exc:
                new_exc = exceptions.TransportError(
                    'Received invalid JSON from the Google Compute Engine'
                    'metadata service: {:.20}'.format(content))
                six.raise_from(new_exc, caught_exc)
        else:
            return content
    else:
        raise exceptions.TransportError(
            'Failed to retrieve {} from the Google Compute Engine'
            'metadata service. Status: {} Response:\n{}'.format(
                url, response.status, response.data), response)
Exemplo n.º 5
0
    def _token_info(access_token=None, id_token=None):
        query_params = {}

        if access_token is not None:
            query_params['access_token'] = access_token
        elif id_token is not None:
            query_params['id_token'] = id_token
        else:
            raise ValueError('No token specified.')

        url = _helpers.update_query(TOKEN_INFO_URL, query_params)

        response = request(url=url, method='GET')

        return json.loads(response.data.decode('utf-8'))
Exemplo n.º 6
0
    def _token_info(access_token=None, id_token=None):
        query_params = {}

        if access_token is not None:
            query_params["access_token"] = access_token
        elif id_token is not None:
            query_params["id_token"] = id_token
        else:
            raise ValueError("No token specified.")

        url = _helpers.update_query(TOKEN_INFO_URL, query_params)

        response = http_request(url=url, method="GET")

        return json.loads(response.data.decode("utf-8"))
Exemplo n.º 7
0
def test_credentials():
    credentials = app_engine.Credentials()
    scoped_credentials = credentials.with_scopes([EMAIL_SCOPE])

    scoped_credentials.refresh(None)

    assert scoped_credentials.valid
    assert scoped_credentials.token is not None

    # Get token info and verify scope
    url = _helpers.update_query(TOKEN_INFO_URL,
                                {"access_token": scoped_credentials.token})
    response = HTTP_REQUEST(url=url, method="GET")
    token_info = json.loads(response.data.decode("utf-8"))

    assert token_info["scope"] == EMAIL_SCOPE
Exemplo n.º 8
0
def get(
    request, path, root=_METADATA_ROOT, params=None, recursive=False, retry_count=5
):
    """Fetch a resource from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        path (str): The resource to retrieve. For example,
            ``'instance/service-accounts/default'``.
        root (str): The full path to the metadata server root.
        params (Optional[Mapping[str, str]]): A mapping of query parameter
            keys to values.
        recursive (bool): Whether to do a recursive query of metadata. See
            https://cloud.google.com/compute/docs/metadata#aggcontents for more
            details.
        retry_count (int): How many times to attempt connecting to metadata
            server using above timeout.

    Returns:
        Union[Mapping, str]: If the metadata server returns JSON, a mapping of
            the decoded JSON is return. Otherwise, the response content is
            returned as a string.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    """
    base_url = urlparse.urljoin(root, path)
    query_params = {} if params is None else params

    if recursive:
        query_params["recursive"] = "true"

    url = _helpers.update_query(base_url, query_params)

    retries = 0
    while retries < retry_count:
        try:
            response = request(url=url, method="GET", headers=_METADATA_HEADERS)
            break

        except exceptions.TransportError as e:
            _LOGGER.warning(
                "Compute Engine Metadata server unavailable on "
                "attempt %s of %s. Reason: %s",
                retries + 1,
                retry_count,
                e,
            )
            retries += 1
    else:
        raise exceptions.TransportError(
            "Failed to retrieve {} from the Google Compute Engine"
            "metadata service. Compute Engine Metadata server unavailable".format(url)
        )

    if response.status == http.client.OK:
        content = _helpers.from_bytes(response.data)
        if response.headers["content-type"] == "application/json":
            try:
                return json.loads(content)
            except ValueError as caught_exc:
                new_exc = exceptions.TransportError(
                    "Received invalid JSON from the Google Compute Engine"
                    "metadata service: {:.20}".format(content)
                )
                raise new_exc from caught_exc
        else:
            return content
    else:
        raise exceptions.TransportError(
            "Failed to retrieve {} from the Google Compute Engine"
            "metadata service. Status: {} Response:\n{}".format(
                url, response.status, response.data
            ),
            response,
        )
Exemplo n.º 9
0
def test_update_query_remove_param():
    base_uri = 'http://www.google.com'
    uri = base_uri + '?x=a'
    updated = _helpers.update_query(uri, {'y': 'c'}, remove=['x'])
    _assert_query(updated, {'y': ['c']})
Exemplo n.º 10
0
def test_update_query_replace_param():
    base_uri = 'http://www.google.com'
    uri = base_uri + '?x=a'
    updated = _helpers.update_query(uri, {'x': 'b', 'y': 'c'})
    _assert_query(updated, {'x': ['b'], 'y': ['c']})
Exemplo n.º 11
0
def test_update_query_existing_params():
    uri = 'http://www.google.com?x=y'
    updated = _helpers.update_query(uri, {'a': 'b', 'c': 'd&'})
    _assert_query(updated, {'x': ['y'], 'a': ['b'], 'c': ['d&']})
Exemplo n.º 12
0
def test_update_query_params_no_params():
    uri = 'http://www.google.com'
    updated = _helpers.update_query(uri, {'a': 'b'})
    assert updated == uri + '?a=b'
def test_update_query_remove_param():
    base_uri = "http://www.google.com"
    uri = base_uri + "?x=a"
    updated = _helpers.update_query(uri, {"y": "c"}, remove=["x"])
    _assert_query(updated, {"y": ["c"]})
def test_update_query_replace_param():
    base_uri = "http://www.google.com"
    uri = base_uri + "?x=a"
    updated = _helpers.update_query(uri, {"x": "b", "y": "c"})
    _assert_query(updated, {"x": ["b"], "y": ["c"]})
def test_update_query_existing_params():
    uri = "http://www.google.com?x=y"
    updated = _helpers.update_query(uri, {"a": "b", "c": "d&"})
    _assert_query(updated, {"x": ["y"], "a": ["b"], "c": ["d&"]})
def test_update_query_params_no_params():
    uri = "http://www.google.com"
    updated = _helpers.update_query(uri, {"a": "b"})
    assert updated == uri + "?a=b"