diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 0954585f2..cb06536da 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:df50e8d462f86d6bcb42f27ecad55bb12c404f1c65de9c6fe4c4d25120080bd6 + digest: sha256:5ff7446edeaede81c3ed58b23a4e76a5403fba1350ce28478045657303b6479d diff --git a/.kokoro/docker/docs/Dockerfile b/.kokoro/docker/docs/Dockerfile index 412b0b56a..4e1b1fb8b 100644 --- a/.kokoro/docker/docs/Dockerfile +++ b/.kokoro/docker/docs/Dockerfile @@ -40,6 +40,7 @@ RUN apt-get update \ libssl-dev \ libsqlite3-dev \ portaudio19-dev \ + python3-distutils \ redis-server \ software-properties-common \ ssh \ @@ -59,40 +60,8 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* \ && rm -f /var/cache/apt/archives/*.deb - -COPY fetch_gpg_keys.sh /tmp -# Install the desired versions of Python. -RUN set -ex \ - && export GNUPGHOME="$(mktemp -d)" \ - && echo "disable-ipv6" >> "${GNUPGHOME}/dirmngr.conf" \ - && /tmp/fetch_gpg_keys.sh \ - && for PYTHON_VERSION in 3.7.8 3.8.5; do \ - wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \ - && wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc" \ - && gpg --batch --verify python-${PYTHON_VERSION}.tar.xz.asc python-${PYTHON_VERSION}.tar.xz \ - && rm -r python-${PYTHON_VERSION}.tar.xz.asc \ - && mkdir -p /usr/src/python-${PYTHON_VERSION} \ - && tar -xJC /usr/src/python-${PYTHON_VERSION} --strip-components=1 -f python-${PYTHON_VERSION}.tar.xz \ - && rm python-${PYTHON_VERSION}.tar.xz \ - && cd /usr/src/python-${PYTHON_VERSION} \ - && ./configure \ - --enable-shared \ - # This works only on Python 2.7 and throws a warning on every other - # version, but seems otherwise harmless. - --enable-unicode=ucs4 \ - --with-system-ffi \ - --without-ensurepip \ - && make -j$(nproc) \ - && make install \ - && ldconfig \ - ; done \ - && rm -rf "${GNUPGHOME}" \ - && rm -rf /usr/src/python* \ - && rm -rf ~/.cache/ - RUN wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \ - && python3.7 /tmp/get-pip.py \ && python3.8 /tmp/get-pip.py \ && rm /tmp/get-pip.py -CMD ["python3.7"] +CMD ["python3.8"] diff --git a/.kokoro/docker/docs/fetch_gpg_keys.sh b/.kokoro/docker/docs/fetch_gpg_keys.sh deleted file mode 100755 index d653dd868..000000000 --- a/.kokoro/docker/docs/fetch_gpg_keys.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/bash -# Copyright 2020 Google LLC -# -# 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. - -# A script to fetch gpg keys with retry. -# Avoid jinja parsing the file. -# - -function retry { - if [[ "${#}" -le 1 ]]; then - echo "Usage: ${0} retry_count commands.." - exit 1 - fi - local retries=${1} - local command="${@:2}" - until [[ "${retries}" -le 0 ]]; do - $command && return 0 - if [[ $? -ne 0 ]]; then - echo "command failed, retrying" - ((retries--)) - fi - done - return 1 -} - -# 3.6.9, 3.7.5 (Ned Deily) -retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ - 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D - -# 3.8.0 (Ɓukasz Langa) -retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ - E3FF2839C048B25C084DEBE9B26995E310250568 - -# diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh index cf5de74c1..311a8d54b 100755 --- a/.kokoro/test-samples-impl.sh +++ b/.kokoro/test-samples-impl.sh @@ -20,9 +20,9 @@ set -eo pipefail # Enables `**` to include files nested inside sub-folders shopt -s globstar -# Exit early if samples directory doesn't exist -if [ ! -d "./samples" ]; then - echo "No tests run. `./samples` not found" +# Exit early if samples don't exist +if ! find samples -name 'requirements.txt' | grep -q .; then + echo "No tests run. './samples/**/requirements.txt' not found" exit 0 fi diff --git a/CHANGELOG.md b/CHANGELOG.md index d04dad5b0..5ccadc42b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ [1]: https://pypi.org/project/google-auth/#history +## [1.33.0](https://www.github.com/googleapis/google-auth-library-python/compare/v1.32.1...v1.33.0) (2021-07-14) + + +### Features + +* define `CredentialAccessBoundary` classes ([#793](https://www.github.com/googleapis/google-auth-library-python/issues/793)) ([d883921](https://www.github.com/googleapis/google-auth-library-python/commit/d883921ae8fdc92b2c2cf1b3a5cd389e1287eb60)) +* define `google.auth.downscoped.Credentials` class ([#801](https://www.github.com/googleapis/google-auth-library-python/issues/801)) ([2f5c3a6](https://www.github.com/googleapis/google-auth-library-python/commit/2f5c3a636192c20cf4c92c3831d1f485031d24d2)) +* service account is able to use a private token endpoint ([#784](https://www.github.com/googleapis/google-auth-library-python/issues/784)) ([0e26409](https://www.github.com/googleapis/google-auth-library-python/commit/0e264092e35ac02ad68d5d91424ecba5397daa41)) + + +### Bug Fixes + +* fix fetch_id_token credential lookup order to match adc ([#748](https://www.github.com/googleapis/google-auth-library-python/issues/748)) ([c34452e](https://www.github.com/googleapis/google-auth-library-python/commit/c34452ef450c42cfef37a1b0c548bb422302dd5d)) + + +### Documentation + +* fix code block formatting in 'user-guide.rst' ([#794](https://www.github.com/googleapis/google-auth-library-python/issues/794)) ([4fd84bd](https://www.github.com/googleapis/google-auth-library-python/commit/4fd84bdf43694af5107dc8c8b443c06ba2f61d2c)) + ### [1.32.1](https://www.github.com/googleapis/google-auth-library-python/compare/v1.32.0...v1.32.1) (2021-06-30) diff --git a/docs/user-guide.rst b/docs/user-guide.rst index 6674c5aef..4a45cde91 100644 --- a/docs/user-guide.rst +++ b/docs/user-guide.rst @@ -479,16 +479,16 @@ IDToken verification can be done for various type of IDTokens using the and ES256 algorithms. However, ES256 algorithm won't be available unless `cryptography` dependency of version at least 1.4.0 is installed. You can check the dependency with `pip freeze` or try `from google.auth.crypt import es256`. -The following is an example of verifying ID tokens: +The following is an example of verifying ID tokens :: from google.auth2 import id_token request = google.auth.transport.requests.Request() try: - decoded_token = id_token.verify_token(token_to_verify,request) + decoded_token = id_token.verify_token(token_to_verify,request) except ValueError: - # Verification failed. + # Verification failed. A sample end-to-end flow using an ID Token against a Cloud Run endpoint maybe :: diff --git a/google/auth/downscoped.py b/google/auth/downscoped.py new file mode 100644 index 000000000..800f2894c --- /dev/null +++ b/google/auth/downscoped.py @@ -0,0 +1,491 @@ +# Copyright 2021 Google LLC +# +# 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. + +"""Downscoping with Credential Access Boundaries + +This module provides the ability to downscope credentials using +`Downscoping with Credential Access Boundaries`_. This is useful to restrict the +Identity and Access Management (IAM) permissions that a short-lived credential +can use. + +To downscope permissions of a source credential, a Credential Access Boundary +that specifies which resources the new credential can access, as well as +an upper bound on the permissions that are available on each resource, has to +be defined. A downscoped credential can then be instantiated using the source +credential and the Credential Access Boundary. + +The common pattern of usage is to have a token broker with elevated access +generate these downscoped credentials from higher access source credentials and +pass the downscoped short-lived access tokens to a token consumer via some +secure authenticated channel for limited access to Google Cloud Storage +resources. + +For example, a token broker can be set up on a server in a private network. +Various workloads (token consumers) in the same network will send authenticated +requests to that broker for downscoped tokens to access or modify specific google +cloud storage buckets. + +The broker will instantiate downscoped credentials instances that can be used to +generate short lived downscoped access tokens that can be passed to the token +consumer. These downscoped access tokens can be injected by the consumer into +google.oauth2.Credentials and used to initialize a storage client instance to +access Google Cloud Storage resources with restricted access. + +Note: Only Cloud Storage supports Credential Access Boundaries. Other Google +Cloud services do not support this feature. + +.. _Downscoping with Credential Access Boundaries: https://cloud.google.com/iam/docs/downscoping-short-lived-credentials +""" + +import datetime + +from google.auth import _helpers +from google.auth import credentials +from google.oauth2 import sts + +# The maximum number of access boundary rules a Credential Access Boundary can +# contain. +_MAX_ACCESS_BOUNDARY_RULES_COUNT = 10 +# The token exchange grant_type used for exchanging credentials. +_STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" +# The token exchange requested_token_type. This is always an access_token. +_STS_REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" +# The STS token URL used to exchanged a short lived access token for a downscoped one. +_STS_TOKEN_URL = "https://sts.googleapis.com/v1/token" +# The subject token type to use when exchanging a short lived access token for a +# downscoped token. +_STS_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" + + +class CredentialAccessBoundary(object): + """Defines a Credential Access Boundary which contains a list of access boundary + rules. Each rule contains information on the resource that the rule applies to, + the upper bound of the permissions that are available on that resource and an + optional condition to further restrict permissions. + """ + + def __init__(self, rules=[]): + """Instantiates a Credential Access Boundary. A Credential Access Boundary + can contain up to 10 access boundary rules. + + Args: + rules (Sequence[google.auth.downscoped.AccessBoundaryRule]): The list of + access boundary rules limiting the access that a downscoped credential + will have. + Raises: + TypeError: If any of the rules are not a valid type. + ValueError: If the provided rules exceed the maximum allowed. + """ + self.rules = rules + + @property + def rules(self): + """Returns the list of access boundary rules defined on the Credential + Access Boundary. + + Returns: + Tuple[google.auth.downscoped.AccessBoundaryRule, ...]: The list of access + boundary rules defined on the Credential Access Boundary. These are returned + as an immutable tuple to prevent modification. + """ + return tuple(self._rules) + + @rules.setter + def rules(self, value): + """Updates the current rules on the Credential Access Boundary. This will overwrite + the existing set of rules. + + Args: + value (Sequence[google.auth.downscoped.AccessBoundaryRule]): The list of + access boundary rules limiting the access that a downscoped credential + will have. + Raises: + TypeError: If any of the rules are not a valid type. + ValueError: If the provided rules exceed the maximum allowed. + """ + if len(value) > _MAX_ACCESS_BOUNDARY_RULES_COUNT: + raise ValueError( + "Credential access boundary rules can have a maximum of {} rules.".format( + _MAX_ACCESS_BOUNDARY_RULES_COUNT + ) + ) + for access_boundary_rule in value: + if not isinstance(access_boundary_rule, AccessBoundaryRule): + raise TypeError( + "List of rules provided do not contain a valid 'google.auth.downscoped.AccessBoundaryRule'." + ) + # Make a copy of the original list. + self._rules = list(value) + + def add_rule(self, rule): + """Adds a single access boundary rule to the existing rules. + + Args: + rule (google.auth.downscoped.AccessBoundaryRule): The access boundary rule, + limiting the access that a downscoped credential will have, to be added to + the existing rules. + Raises: + TypeError: If any of the rules are not a valid type. + ValueError: If the provided rules exceed the maximum allowed. + """ + if len(self.rules) == _MAX_ACCESS_BOUNDARY_RULES_COUNT: + raise ValueError( + "Credential access boundary rules can have a maximum of {} rules.".format( + _MAX_ACCESS_BOUNDARY_RULES_COUNT + ) + ) + if not isinstance(rule, AccessBoundaryRule): + raise TypeError( + "The provided rule does not contain a valid 'google.auth.downscoped.AccessBoundaryRule'." + ) + self._rules.append(rule) + + def to_json(self): + """Generates the dictionary representation of the Credential Access Boundary. + This uses the format expected by the Security Token Service API as documented in + `Defining a Credential Access Boundary`_. + + .. _Defining a Credential Access Boundary: + https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary + + Returns: + Mapping: Credential Access Boundary Rule represented in a dictionary object. + """ + rules = [] + for access_boundary_rule in self.rules: + rules.append(access_boundary_rule.to_json()) + + return {"accessBoundary": {"accessBoundaryRules": rules}} + + +class AccessBoundaryRule(object): + """Defines an access boundary rule which contains information on the resource that + the rule applies to, the upper bound of the permissions that are available on that + resource and an optional condition to further restrict permissions. + """ + + def __init__( + self, available_resource, available_permissions, availability_condition=None + ): + """Instantiates a single access boundary rule. + + Args: + available_resource (str): The full resource name of the Cloud Storage bucket + that the rule applies to. Use the format + "//storage.googleapis.com/projects/_/buckets/bucket-name". + available_permissions (Sequence[str]): A list defining the upper bound that + the downscoped token will have on the available permissions for the + resource. Each value is the identifier for an IAM predefined role or + custom role, with the prefix "inRole:". For example: + "inRole:roles/storage.objectViewer". + Only the permissions in these roles will be available. + availability_condition (Optional[google.auth.downscoped.AvailabilityCondition]): + Optional condition that restricts the availability of permissions to + specific Cloud Storage objects. + + Raises: + TypeError: If any of the parameters are not of the expected types. + ValueError: If any of the parameters are not of the expected values. + """ + self.available_resource = available_resource + self.available_permissions = available_permissions + self.availability_condition = availability_condition + + @property + def available_resource(self): + """Returns the current available resource. + + Returns: + str: The current available resource. + """ + return self._available_resource + + @available_resource.setter + def available_resource(self, value): + """Updates the current available resource. + + Args: + value (str): The updated value of the available resource. + + Raises: + TypeError: If the value is not a string. + """ + if not isinstance(value, str): + raise TypeError("The provided available_resource is not a string.") + self._available_resource = value + + @property + def available_permissions(self): + """Returns the current available permissions. + + Returns: + Tuple[str, ...]: The current available permissions. These are returned + as an immutable tuple to prevent modification. + """ + return tuple(self._available_permissions) + + @available_permissions.setter + def available_permissions(self, value): + """Updates the current available permissions. + + Args: + value (Sequence[str]): The updated value of the available permissions. + + Raises: + TypeError: If the value is not a list of strings. + ValueError: If the value is not valid. + """ + for available_permission in value: + if not isinstance(available_permission, str): + raise TypeError( + "Provided available_permissions are not a list of strings." + ) + if available_permission.find("inRole:") != 0: + raise ValueError( + "available_permissions must be prefixed with 'inRole:'." + ) + # Make a copy of the original list. + self._available_permissions = list(value) + + @property + def availability_condition(self): + """Returns the current availability condition. + + Returns: + Optional[google.auth.downscoped.AvailabilityCondition]: The current + availability condition. + """ + return self._availability_condition + + @availability_condition.setter + def availability_condition(self, value): + """Updates the current availability condition. + + Args: + value (Optional[google.auth.downscoped.AvailabilityCondition]): The updated + value of the availability condition. + + Raises: + TypeError: If the value is not of type google.auth.downscoped.AvailabilityCondition + or None. + """ + if not isinstance(value, AvailabilityCondition) and value is not None: + raise TypeError( + "The provided availability_condition is not a 'google.auth.downscoped.AvailabilityCondition' or None." + ) + self._availability_condition = value + + def to_json(self): + """Generates the dictionary representation of the access boundary rule. + This uses the format expected by the Security Token Service API as documented in + `Defining a Credential Access Boundary`_. + + .. _Defining a Credential Access Boundary: + https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary + + Returns: + Mapping: The access boundary rule represented in a dictionary object. + """ + json = { + "availablePermissions": list(self.available_permissions), + "availableResource": self.available_resource, + } + if self.availability_condition: + json["availabilityCondition"] = self.availability_condition.to_json() + return json + + +class AvailabilityCondition(object): + """An optional condition that can be used as part of a Credential Access Boundary + to further restrict permissions.""" + + def __init__(self, expression, title=None, description=None): + """Instantiates an availability condition using the provided expression and + optional title or description. + + Args: + expression (str): A condition expression that specifies the Cloud Storage + objects where permissions are available. For example, this expression + makes permissions available for objects whose name starts with "customer-a": + "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a')" + title (Optional[str]): An optional short string that identifies the purpose of + the condition. + description (Optional[str]): Optional details about the purpose of the condition. + + Raises: + TypeError: If any of the parameters are not of the expected types. + ValueError: If any of the parameters are not of the expected values. + """ + self.expression = expression + self.title = title + self.description = description + + @property + def expression(self): + """Returns the current condition expression. + + Returns: + str: The current conditon expression. + """ + return self._expression + + @expression.setter + def expression(self, value): + """Updates the current condition expression. + + Args: + value (str): The updated value of the condition expression. + + Raises: + TypeError: If the value is not of type string. + """ + if not isinstance(value, str): + raise TypeError("The provided expression is not a string.") + self._expression = value + + @property + def title(self): + """Returns the current title. + + Returns: + Optional[str]: The current title. + """ + return self._title + + @title.setter + def title(self, value): + """Updates the current title. + + Args: + value (Optional[str]): The updated value of the title. + + Raises: + TypeError: If the value is not of type string or None. + """ + if not isinstance(value, str) and value is not None: + raise TypeError("The provided title is not a string or None.") + self._title = value + + @property + def description(self): + """Returns the current description. + + Returns: + Optional[str]: The current description. + """ + return self._description + + @description.setter + def description(self, value): + """Updates the current description. + + Args: + value (Optional[str]): The updated value of the description. + + Raises: + TypeError: If the value is not of type string or None. + """ + if not isinstance(value, str) and value is not None: + raise TypeError("The provided description is not a string or None.") + self._description = value + + def to_json(self): + """Generates the dictionary representation of the availability condition. + This uses the format expected by the Security Token Service API as documented in + `Defining a Credential Access Boundary`_. + + .. _Defining a Credential Access Boundary: + https://cloud.google.com/iam/docs/downscoping-short-lived-credentials#define-boundary + + Returns: + Mapping[str, str]: The availability condition represented in a dictionary + object. + """ + json = {"expression": self.expression} + if self.title: + json["title"] = self.title + if self.description: + json["description"] = self.description + return json + + +class Credentials(credentials.CredentialsWithQuotaProject): + """Defines a set of Google credentials that are downscoped from an existing set + of Google OAuth2 credentials. This is useful to restrict the Identity and Access + Management (IAM) permissions that a short-lived credential can use. + The common pattern of usage is to have a token broker with elevated access + generate these downscoped credentials from higher access source credentials and + pass the downscoped short-lived access tokens to a token consumer via some + secure authenticated channel for limited access to Google Cloud Storage + resources. + """ + + def __init__( + self, source_credentials, credential_access_boundary, quota_project_id=None + ): + """Instantiates a downscoped credentials object using the provided source + credentials and credential access boundary rules. + To downscope permissions of a source credential, a Credential Access Boundary + that specifies which resources the new credential can access, as well as an + upper bound on the permissions that are available on each resource, has to be + defined. A downscoped credential can then be instantiated using the source + credential and the Credential Access Boundary. + + Args: + source_credentials (google.auth.credentials.Credentials): The source credentials + to be downscoped based on the provided Credential Access Boundary rules. + credential_access_boundary (google.auth.downscoped.CredentialAccessBoundary): + The Credential Access Boundary which contains a list of access boundary + rules. Each rule contains information on the resource that the rule applies to, + the upper bound of the permissions that are available on that resource and an + optional condition to further restrict permissions. + quota_project_id (Optional[str]): The optional quota project ID. + Raises: + google.auth.exceptions.RefreshError: If the source credentials + return an error on token refresh. + google.auth.exceptions.OAuthError: If the STS token exchange + endpoint returned an error during downscoped token generation. + """ + + super(Credentials, self).__init__() + self._source_credentials = source_credentials + self._credential_access_boundary = credential_access_boundary + self._quota_project_id = quota_project_id + self._sts_client = sts.Client(_STS_TOKEN_URL) + + @_helpers.copy_docstring(credentials.Credentials) + def refresh(self, request): + # Generate an access token from the source credentials. + self._source_credentials.refresh(request) + now = _helpers.utcnow() + # Exchange the access token for a downscoped access token. + response_data = self._sts_client.exchange_token( + request=request, + grant_type=_STS_GRANT_TYPE, + subject_token=self._source_credentials.token, + subject_token_type=_STS_SUBJECT_TOKEN_TYPE, + requested_token_type=_STS_REQUESTED_TOKEN_TYPE, + additional_options=self._credential_access_boundary.to_json(), + ) + self.token = response_data.get("access_token") + lifetime = datetime.timedelta(seconds=response_data.get("expires_in")) + self.expiry = now + lifetime + + @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject) + def with_quota_project(self, quota_project_id): + return self.__class__( + self._source_credentials, + self._credential_access_boundary, + quota_project_id=quota_project_id, + ) diff --git a/google/auth/version.py b/google/auth/version.py index 2ffa8a43a..e74f1e70f 100644 --- a/google/auth/version.py +++ b/google/auth/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "1.32.1" +__version__ = "1.33.0" diff --git a/google/oauth2/_id_token_async.py b/google/oauth2/_id_token_async.py index f5ef8baff..ab681a9cb 100644 --- a/google/oauth2/_id_token_async.py +++ b/google/oauth2/_id_token_async.py @@ -180,13 +180,14 @@ async def verify_firebase_token(id_token, request, audience=None): async def fetch_id_token(request, audience): """Fetch the ID Token from the current environment. - This function acquires ID token from the environment in the following order: + This function acquires ID token from the environment in the following order. + See https://google.aip.dev/auth/4110. - 1. If the application is running in Compute Engine, App Engine or Cloud Run, - then the ID token are obtained from the metadata server. - 2. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set + 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON file, then ID token is acquired using this service account credentials. + 2. If the application is running in Compute Engine, App Engine or Cloud Run, + then the ID token are obtained from the metadata server. 3. If metadata server doesn't exist and no valid service account credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. @@ -214,54 +215,52 @@ async def fetch_id_token(request, audience): If metadata server doesn't exist and no valid service account credentials are found. """ - # 1. First try to fetch ID token from metadata server if it exists. The code - # works for GAE and Cloud Run metadata server as well. - try: - from google.auth import compute_engine - - request_new = requests.Request() - credentials = compute_engine.IDTokenCredentials( - request_new, audience, use_metadata_identity_endpoint=True - ) - credentials.refresh(request_new) - - return credentials.token - - except (ImportError, exceptions.TransportError, exceptions.RefreshError): - pass - - # 2. Try to use service account credentials to get ID token. - - # Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment + # 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment # variable. credentials_filename = os.environ.get(environment_vars.CREDENTIALS) - if not ( - credentials_filename - and os.path.exists(credentials_filename) - and os.path.isfile(credentials_filename) - ): - raise exceptions.DefaultCredentialsError( - "Neither metadata server or valid service account credentials are found." - ) + if credentials_filename: + if not ( + os.path.exists(credentials_filename) + and os.path.isfile(credentials_filename) + ): + raise exceptions.DefaultCredentialsError( + "GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid." + ) - try: - with open(credentials_filename, "r") as f: - info = json.load(f) - credentials_content = ( - (info.get("type") == "service_account") and info or None + try: + with open(credentials_filename, "r") as f: + from google.oauth2 import _service_account_async as service_account + + info = json.load(f) + if info.get("type") == "service_account": + credentials = service_account.IDTokenCredentials.from_service_account_info( + info, target_audience=audience + ) + await credentials.refresh(request) + return credentials.token + except ValueError as caught_exc: + new_exc = exceptions.DefaultCredentialsError( + "GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.", + caught_exc, ) + six.raise_from(new_exc, caught_exc) - from google.oauth2 import _service_account_async as service_account + # 2. Try to fetch ID token from metada server if it exists. The code works for GAE and + # Cloud Run metadata server as well. + try: + from google.auth import compute_engine + from google.auth.compute_engine import _metadata - credentials = service_account.IDTokenCredentials.from_service_account_info( - credentials_content, target_audience=audience + request_new = requests.Request() + if _metadata.ping(request_new): + credentials = compute_engine.IDTokenCredentials( + request_new, audience, use_metadata_identity_endpoint=True ) - except ValueError as caught_exc: - new_exc = exceptions.DefaultCredentialsError( - "Neither metadata server or valid service account credentials are found.", - caught_exc, - ) - six.raise_from(new_exc, caught_exc) + credentials.refresh(request_new) + return credentials.token + except (ImportError, exceptions.TransportError): + pass - await credentials.refresh(request) - return credentials.token + raise exceptions.DefaultCredentialsError( + "Neither metadata server or valid service account credentials are found." + ) diff --git a/google/oauth2/id_token.py b/google/oauth2/id_token.py index 5fbb6a133..540ccd125 100644 --- a/google/oauth2/id_token.py +++ b/google/oauth2/id_token.py @@ -179,13 +179,14 @@ def verify_firebase_token(id_token, request, audience=None): def fetch_id_token(request, audience): """Fetch the ID Token from the current environment. - This function acquires ID token from the environment in the following order: + This function acquires ID token from the environment in the following order. + See https://google.aip.dev/auth/4110. - 1. If the application is running in Compute Engine, App Engine or Cloud Run, - then the ID token are obtained from the metadata server. - 2. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set + 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON file, then ID token is acquired using this service account credentials. + 2. If the application is running in Compute Engine, App Engine or Cloud Run, + then the ID token are obtained from the metadata server. 3. If metadata server doesn't exist and no valid service account credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. @@ -213,51 +214,51 @@ def fetch_id_token(request, audience): If metadata server doesn't exist and no valid service account credentials are found. """ - # 1. First try to fetch ID token from metada server if it exists. The code - # works for GAE and Cloud Run metadata server as well. - try: - from google.auth import compute_engine - - credentials = compute_engine.IDTokenCredentials( - request, audience, use_metadata_identity_endpoint=True - ) - credentials.refresh(request) - return credentials.token - except (ImportError, exceptions.TransportError, exceptions.RefreshError): - pass - - # 2. Try to use service account credentials to get ID token. - - # Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment + # 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment # variable. credentials_filename = os.environ.get(environment_vars.CREDENTIALS) - if not ( - credentials_filename - and os.path.exists(credentials_filename) - and os.path.isfile(credentials_filename) - ): - raise exceptions.DefaultCredentialsError( - "Neither metadata server or valid service account credentials are found." - ) + if credentials_filename: + if not ( + os.path.exists(credentials_filename) + and os.path.isfile(credentials_filename) + ): + raise exceptions.DefaultCredentialsError( + "GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid." + ) - try: - with open(credentials_filename, "r") as f: - info = json.load(f) - credentials_content = ( - (info.get("type") == "service_account") and info or None + try: + with open(credentials_filename, "r") as f: + from google.oauth2 import service_account + + info = json.load(f) + if info.get("type") == "service_account": + credentials = service_account.IDTokenCredentials.from_service_account_info( + info, target_audience=audience + ) + credentials.refresh(request) + return credentials.token + except ValueError as caught_exc: + new_exc = exceptions.DefaultCredentialsError( + "GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.", + caught_exc, ) + six.raise_from(new_exc, caught_exc) - from google.oauth2 import service_account + # 2. Try to fetch ID token from metada server if it exists. The code works for GAE and + # Cloud Run metadata server as well. + try: + from google.auth import compute_engine + from google.auth.compute_engine import _metadata - credentials = service_account.IDTokenCredentials.from_service_account_info( - credentials_content, target_audience=audience + if _metadata.ping(request): + credentials = compute_engine.IDTokenCredentials( + request, audience, use_metadata_identity_endpoint=True ) - except ValueError as caught_exc: - new_exc = exceptions.DefaultCredentialsError( - "Neither metadata server or valid service account credentials are found.", - caught_exc, - ) - six.raise_from(new_exc, caught_exc) + credentials.refresh(request) + return credentials.token + except (ImportError, exceptions.TransportError): + pass - credentials.refresh(request) - return credentials.token + raise exceptions.DefaultCredentialsError( + "Neither metadata server or valid service account credentials are found." + ) diff --git a/google/oauth2/service_account.py b/google/oauth2/service_account.py index dd3658994..8f18f26ea 100644 --- a/google/oauth2/service_account.py +++ b/google/oauth2/service_account.py @@ -80,6 +80,7 @@ from google.oauth2 import _client _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds +_GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" class Credentials( @@ -382,7 +383,7 @@ def _make_authorization_grant_assertion(self): # The issuer must be the service account email. "iss": self._service_account_email, # The audience must be the auth token endpoint's URI - "aud": self._token_uri, + "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT, "scope": _helpers.scopes_to_string(self._scopes or ()), } @@ -643,7 +644,7 @@ def _make_authorization_grant_assertion(self): # The issuer must be the service account email. "iss": self.service_account_email, # The audience must be the auth token endpoint's URI - "aud": self._token_uri, + "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT, # The target audience specifies which service the ID token is # intended for. "target_audience": self._target_audience, diff --git a/system_tests/noxfile.py b/system_tests/noxfile.py index f177dcd6a..11c398b97 100644 --- a/system_tests/noxfile.py +++ b/system_tests/noxfile.py @@ -188,7 +188,11 @@ def default(session, *test_paths): def service_account_sync(session): session.install(*TEST_DEPENDENCIES_SYNC) session.install(LIBRARY_DIR) - default(session, "system_tests_sync/test_service_account.py") + default( + session, + "system_tests_sync/test_service_account.py", + *session.posargs, + ) @nox.session(python=PYTHON_VERSIONS_SYNC) @@ -201,6 +205,7 @@ def default_explicit_service_account(session): session, "system_tests_sync/test_default.py", "system_tests_sync/test_id_token.py", + *session.posargs, ) @@ -210,7 +215,9 @@ def default_explicit_authorized_user(session): session.install(*TEST_DEPENDENCIES_SYNC) session.install(LIBRARY_DIR) default( - session, "system_tests_sync/test_default.py", + session, + "system_tests_sync/test_default.py", + *session.posargs, ) @@ -222,7 +229,9 @@ def default_explicit_authorized_user_explicit_project(session): session.install(*TEST_DEPENDENCIES_SYNC) session.install(LIBRARY_DIR) default( - session, "system_tests_sync/test_default.py", + session, + "system_tests_sync/test_default.py", + *session.posargs, ) @@ -233,7 +242,9 @@ def default_cloud_sdk_service_account(session): session.install(*TEST_DEPENDENCIES_SYNC) session.install(LIBRARY_DIR) default( - session, "system_tests_sync/test_default.py", + session, + "system_tests_sync/test_default.py", + *session.posargs, ) @@ -243,7 +254,9 @@ def default_cloud_sdk_authorized_user(session): session.install(*TEST_DEPENDENCIES_SYNC) session.install(LIBRARY_DIR) default( - session, "system_tests_sync/test_default.py", + session, + "system_tests_sync/test_default.py", + *session.posargs, ) @@ -254,7 +267,9 @@ def default_cloud_sdk_authorized_user_configured_project(session): session.install(*TEST_DEPENDENCIES_SYNC) session.install(LIBRARY_DIR) default( - session, "system_tests_sync/test_default.py", + session, + "system_tests_sync/test_default.py", + *session.posargs, ) @@ -266,7 +281,9 @@ def compute_engine(session): del session.virtualenv.env["GOOGLE_APPLICATION_CREDENTIALS"] session.install(LIBRARY_DIR) default( - session, "system_tests_sync/test_compute_engine.py", + session, + "system_tests_sync/test_compute_engine.py", + *session.posargs, ) @@ -320,7 +337,9 @@ def grpc(session): session.install(*TEST_DEPENDENCIES_SYNC, "google-cloud-pubsub==1.7.0") session.env[EXPLICIT_CREDENTIALS_ENV] = SERVICE_ACCOUNT_FILE default( - session, "system_tests_sync/test_grpc.py", + session, + "system_tests_sync/test_grpc.py", + *session.posargs, ) @@ -330,7 +349,9 @@ def requests(session): session.install(*TEST_DEPENDENCIES_SYNC) session.env[EXPLICIT_CREDENTIALS_ENV] = SERVICE_ACCOUNT_FILE default( - session, "system_tests_sync/test_requests.py", + session, + "system_tests_sync/test_requests.py", + *session.posargs, ) @@ -340,7 +361,9 @@ def urllib3(session): session.install(*TEST_DEPENDENCIES_SYNC) session.env[EXPLICIT_CREDENTIALS_ENV] = SERVICE_ACCOUNT_FILE default( - session, "system_tests_sync/test_urllib3.py", + session, + "system_tests_sync/test_urllib3.py", + *session.posargs, ) @@ -350,14 +373,25 @@ def mtls_http(session): session.install(*TEST_DEPENDENCIES_SYNC, "pyopenssl") session.env[EXPLICIT_CREDENTIALS_ENV] = SERVICE_ACCOUNT_FILE default( - session, "system_tests_sync/test_mtls_http.py", + session, + "system_tests_sync/test_mtls_http.py", + *session.posargs, ) @nox.session(python=PYTHON_VERSIONS_SYNC) def external_accounts(session): - session.install(*TEST_DEPENDENCIES_SYNC, "google-auth", "google-api-python-client", "enum34") - default(session, "system_tests_sync/test_external_accounts.py") + session.install( + *TEST_DEPENDENCIES_SYNC, + "google-auth", + "google-api-python-client", + "enum34", + ) + default( + session, + "system_tests_sync/test_external_accounts.py", + *session.posargs, + ) # ASYNC SYSTEM TESTS @@ -367,7 +401,9 @@ def service_account_async(session): session.install(*(TEST_DEPENDENCIES_SYNC + TEST_DEPENDENCIES_ASYNC)) session.install(LIBRARY_DIR) default( - session, "system_tests_async/test_service_account.py", + session, + "system_tests_async/test_service_account.py", + *session.posargs, ) @@ -381,6 +417,7 @@ def default_explicit_service_account_async(session): session, "system_tests_async/test_default.py", "system_tests_async/test_id_token.py", + *session.posargs, ) @@ -390,7 +427,9 @@ def default_explicit_authorized_user_async(session): session.install(*(TEST_DEPENDENCIES_SYNC + TEST_DEPENDENCIES_ASYNC)) session.install(LIBRARY_DIR) default( - session, "system_tests_async/test_default.py", + session, + "system_tests_async/test_default.py", + *session.posargs, ) @@ -402,7 +441,9 @@ def default_explicit_authorized_user_explicit_project_async(session): session.install(*(TEST_DEPENDENCIES_SYNC + TEST_DEPENDENCIES_ASYNC)) session.install(LIBRARY_DIR) default( - session, "system_tests_async/test_default.py", + session, + "system_tests_async/test_default.py", + *session.posargs, ) @@ -413,7 +454,9 @@ def default_cloud_sdk_service_account_async(session): session.install(*(TEST_DEPENDENCIES_SYNC + TEST_DEPENDENCIES_ASYNC)) session.install(LIBRARY_DIR) default( - session, "system_tests_async/test_default.py", + session, + "system_tests_async/test_default.py", + *session.posargs, ) @@ -423,7 +466,9 @@ def default_cloud_sdk_authorized_user_async(session): session.install(*(TEST_DEPENDENCIES_SYNC + TEST_DEPENDENCIES_ASYNC)) session.install(LIBRARY_DIR) default( - session, "system_tests_async/test_default.py", + session, + "system_tests_async/test_default.py", + *session.posargs, ) @@ -434,5 +479,7 @@ def default_cloud_sdk_authorized_user_configured_project_async(session): session.install(*(TEST_DEPENDENCIES_SYNC + TEST_DEPENDENCIES_ASYNC)) session.install(LIBRARY_DIR) default( - session, "system_tests_async/test_default.py", + session, + "system_tests_async/test_default.py", + *session.posargs, ) diff --git a/system_tests/secrets.tar.enc b/system_tests/secrets.tar.enc index 24d89b1bf..e416918d4 100644 Binary files a/system_tests/secrets.tar.enc and b/system_tests/secrets.tar.enc differ diff --git a/tests/oauth2/test_id_token.py b/tests/oauth2/test_id_token.py index 0c70d6891..ab6774355 100644 --- a/tests/oauth2/test_id_token.py +++ b/tests/oauth2/test_id_token.py @@ -23,6 +23,7 @@ from google.auth import transport import google.auth.compute_engine._metadata from google.oauth2 import id_token +from google.oauth2 import service_account SERVICE_ACCOUNT_FILE = os.path.join( os.path.dirname(__file__), "../data/service_account.json" @@ -134,62 +135,93 @@ def test_verify_firebase_token(verify_token): ) -def test_fetch_id_token_from_metadata_server(): +def test_fetch_id_token_from_metadata_server(monkeypatch): + monkeypatch.delenv(environment_vars.CREDENTIALS, raising=False) + def mock_init(self, request, audience, use_metadata_identity_endpoint): assert use_metadata_identity_endpoint self.token = "id_token" - with mock.patch.multiple( - google.auth.compute_engine.IDTokenCredentials, - __init__=mock_init, - refresh=mock.Mock(), - ): - request = mock.Mock() - token = id_token.fetch_id_token(request, "https://pubsub.googleapis.com") - assert token == "id_token" + with mock.patch("google.auth.compute_engine._metadata.ping", return_value=True): + with mock.patch.multiple( + google.auth.compute_engine.IDTokenCredentials, + __init__=mock_init, + refresh=mock.Mock(), + ): + request = mock.Mock() + token = id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert token == "id_token" -@mock.patch.object( - google.auth.compute_engine.IDTokenCredentials, - "__init__", - side_effect=exceptions.TransportError(), -) -def test_fetch_id_token_from_explicit_cred_json_file(mock_init, monkeypatch): +def test_fetch_id_token_from_explicit_cred_json_file(monkeypatch): monkeypatch.setenv(environment_vars.CREDENTIALS, SERVICE_ACCOUNT_FILE) def mock_refresh(self, request): self.token = "id_token" - with mock.patch.object( - google.oauth2.service_account.IDTokenCredentials, "refresh", mock_refresh - ): + with mock.patch.object(service_account.IDTokenCredentials, "refresh", mock_refresh): request = mock.Mock() token = id_token.fetch_id_token(request, "https://pubsub.googleapis.com") assert token == "id_token" -@mock.patch.object( - google.auth.compute_engine.IDTokenCredentials, - "__init__", - side_effect=exceptions.TransportError(), -) -def test_fetch_id_token_no_cred_json_file(mock_init, monkeypatch): +def test_fetch_id_token_no_cred_exists(monkeypatch): monkeypatch.delenv(environment_vars.CREDENTIALS, raising=False) - with pytest.raises(exceptions.DefaultCredentialsError): + with mock.patch( + "google.auth.compute_engine._metadata.ping", + side_effect=exceptions.TransportError(), + ): + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: + request = mock.Mock() + id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"Neither metadata server or valid service account credentials are found." + ) + + with mock.patch("google.auth.compute_engine._metadata.ping", return_value=False): + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: + request = mock.Mock() + id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"Neither metadata server or valid service account credentials are found." + ) + + +def test_fetch_id_token_invalid_cred_file_type(monkeypatch): + user_credentials_file = os.path.join( + os.path.dirname(__file__), "../data/authorized_user.json" + ) + monkeypatch.setenv(environment_vars.CREDENTIALS, user_credentials_file) + + with mock.patch("google.auth.compute_engine._metadata.ping", return_value=False): + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: + request = mock.Mock() + id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"Neither metadata server or valid service account credentials are found." + ) + + +def test_fetch_id_token_invalid_json(monkeypatch): + not_json_file = os.path.join(os.path.dirname(__file__), "../data/public_cert.pem") + monkeypatch.setenv(environment_vars.CREDENTIALS, not_json_file) + + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: request = mock.Mock() id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials." + ) -@mock.patch.object( - google.auth.compute_engine.IDTokenCredentials, - "__init__", - side_effect=exceptions.TransportError(), -) -def test_fetch_id_token_invalid_cred_file(mock_init, monkeypatch): - not_json_file = os.path.join(os.path.dirname(__file__), "../data/public_cert.pem") +def test_fetch_id_token_invalid_cred_path(monkeypatch): + not_json_file = os.path.join(os.path.dirname(__file__), "../data/not_exists.json") monkeypatch.setenv(environment_vars.CREDENTIALS, not_json_file) - with pytest.raises(exceptions.DefaultCredentialsError): + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: request = mock.Mock() id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid." + ) diff --git a/tests/oauth2/test_service_account.py b/tests/oauth2/test_service_account.py index 5852d3714..370438f48 100644 --- a/tests/oauth2/test_service_account.py +++ b/tests/oauth2/test_service_account.py @@ -167,7 +167,7 @@ def test__make_authorization_grant_assertion(self): token = credentials._make_authorization_grant_assertion() payload = jwt.decode(token, PUBLIC_CERT_BYTES) assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL - assert payload["aud"] == self.TOKEN_URI + assert payload["aud"] == service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT def test__make_authorization_grant_assertion_scoped(self): credentials = self.make_credentials() @@ -440,7 +440,7 @@ def test__make_authorization_grant_assertion(self): token = credentials._make_authorization_grant_assertion() payload = jwt.decode(token, PUBLIC_CERT_BYTES) assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL - assert payload["aud"] == self.TOKEN_URI + assert payload["aud"] == service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT assert payload["target_audience"] == self.TARGET_AUDIENCE @mock.patch("google.oauth2._client.id_token_jwt_grant", autospec=True) diff --git a/tests/test_downscoped.py b/tests/test_downscoped.py new file mode 100644 index 000000000..ac60e5b00 --- /dev/null +++ b/tests/test_downscoped.py @@ -0,0 +1,652 @@ +# Copyright 2021 Google LLC +# +# 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 json + +import mock +import pytest +from six.moves import http_client +from six.moves import urllib + +from google.auth import _helpers +from google.auth import credentials +from google.auth import downscoped +from google.auth import exceptions +from google.auth import transport + + +EXPRESSION = ( + "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a')" +) +TITLE = "customer-a-objects" +DESCRIPTION = ( + "Condition to make permissions available for objects starting with customer-a" +) +AVAILABLE_RESOURCE = "//storage.googleapis.com/projects/_/buckets/example-bucket" +AVAILABLE_PERMISSIONS = ["inRole:roles/storage.objectViewer"] + +OTHER_EXPRESSION = ( + "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-b')" +) +OTHER_TITLE = "customer-b-objects" +OTHER_DESCRIPTION = ( + "Condition to make permissions available for objects starting with customer-b" +) +OTHER_AVAILABLE_RESOURCE = "//storage.googleapis.com/projects/_/buckets/other-bucket" +OTHER_AVAILABLE_PERMISSIONS = ["inRole:roles/storage.objectCreator"] +QUOTA_PROJECT_ID = "QUOTA_PROJECT_ID" +GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" +REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" +TOKEN_EXCHANGE_ENDPOINT = "https://sts.googleapis.com/v1/token" +SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" +SUCCESS_RESPONSE = { + "access_token": "ACCESS_TOKEN", + "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", + "token_type": "Bearer", + "expires_in": 3600, +} +ERROR_RESPONSE = { + "error": "invalid_grant", + "error_description": "Subject token is invalid.", + "error_uri": "https://tools.ietf.org/html/rfc6749", +} +CREDENTIAL_ACCESS_BOUNDARY_JSON = { + "accessBoundary": { + "accessBoundaryRules": [ + { + "availablePermissions": AVAILABLE_PERMISSIONS, + "availableResource": AVAILABLE_RESOURCE, + "availabilityCondition": { + "expression": EXPRESSION, + "title": TITLE, + "description": DESCRIPTION, + }, + } + ] + } +} + + +class SourceCredentials(credentials.Credentials): + def __init__(self, raise_error=False): + super(SourceCredentials, self).__init__() + self._counter = 0 + self._raise_error = raise_error + + def refresh(self, request): + if self._raise_error: + raise exceptions.RefreshError( + "Failed to refresh access token in source credentials." + ) + now = _helpers.utcnow() + self._counter += 1 + self.token = "ACCESS_TOKEN_{}".format(self._counter) + self.expiry = now + datetime.timedelta(seconds=3600) + + +def make_availability_condition(expression, title=None, description=None): + return downscoped.AvailabilityCondition(expression, title, description) + + +def make_access_boundary_rule( + available_resource, available_permissions, availability_condition=None +): + return downscoped.AccessBoundaryRule( + available_resource, available_permissions, availability_condition + ) + + +def make_credential_access_boundary(rules): + return downscoped.CredentialAccessBoundary(rules) + + +class TestAvailabilityCondition(object): + def test_constructor(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + + assert availability_condition.expression == EXPRESSION + assert availability_condition.title == TITLE + assert availability_condition.description == DESCRIPTION + + def test_constructor_required_params_only(self): + availability_condition = make_availability_condition(EXPRESSION) + + assert availability_condition.expression == EXPRESSION + assert availability_condition.title is None + assert availability_condition.description is None + + def test_setters(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + availability_condition.expression = OTHER_EXPRESSION + availability_condition.title = OTHER_TITLE + availability_condition.description = OTHER_DESCRIPTION + + assert availability_condition.expression == OTHER_EXPRESSION + assert availability_condition.title == OTHER_TITLE + assert availability_condition.description == OTHER_DESCRIPTION + + def test_invalid_expression_type(self): + with pytest.raises(TypeError) as excinfo: + make_availability_condition([EXPRESSION], TITLE, DESCRIPTION) + + assert excinfo.match("The provided expression is not a string.") + + def test_invalid_title_type(self): + with pytest.raises(TypeError) as excinfo: + make_availability_condition(EXPRESSION, False, DESCRIPTION) + + assert excinfo.match("The provided title is not a string or None.") + + def test_invalid_description_type(self): + with pytest.raises(TypeError) as excinfo: + make_availability_condition(EXPRESSION, TITLE, False) + + assert excinfo.match("The provided description is not a string or None.") + + def test_to_json_required_params_only(self): + availability_condition = make_availability_condition(EXPRESSION) + + assert availability_condition.to_json() == {"expression": EXPRESSION} + + def test_to_json_(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + + assert availability_condition.to_json() == { + "expression": EXPRESSION, + "title": TITLE, + "description": DESCRIPTION, + } + + +class TestAccessBoundaryRule(object): + def test_constructor(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + + assert access_boundary_rule.available_resource == AVAILABLE_RESOURCE + assert access_boundary_rule.available_permissions == tuple( + AVAILABLE_PERMISSIONS + ) + assert access_boundary_rule.availability_condition == availability_condition + + def test_constructor_required_params_only(self): + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS + ) + + assert access_boundary_rule.available_resource == AVAILABLE_RESOURCE + assert access_boundary_rule.available_permissions == tuple( + AVAILABLE_PERMISSIONS + ) + assert access_boundary_rule.availability_condition is None + + def test_setters(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + other_availability_condition = make_availability_condition( + OTHER_EXPRESSION, OTHER_TITLE, OTHER_DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + access_boundary_rule.available_resource = OTHER_AVAILABLE_RESOURCE + access_boundary_rule.available_permissions = OTHER_AVAILABLE_PERMISSIONS + access_boundary_rule.availability_condition = other_availability_condition + + assert access_boundary_rule.available_resource == OTHER_AVAILABLE_RESOURCE + assert access_boundary_rule.available_permissions == tuple( + OTHER_AVAILABLE_PERMISSIONS + ) + assert ( + access_boundary_rule.availability_condition == other_availability_condition + ) + + def test_invalid_available_resource_type(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + with pytest.raises(TypeError) as excinfo: + make_access_boundary_rule( + None, AVAILABLE_PERMISSIONS, availability_condition + ) + + assert excinfo.match("The provided available_resource is not a string.") + + def test_invalid_available_permissions_type(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + with pytest.raises(TypeError) as excinfo: + make_access_boundary_rule( + AVAILABLE_RESOURCE, [0, 1, 2], availability_condition + ) + + assert excinfo.match( + "Provided available_permissions are not a list of strings." + ) + + def test_invalid_available_permissions_value(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + with pytest.raises(ValueError) as excinfo: + make_access_boundary_rule( + AVAILABLE_RESOURCE, + ["roles/storage.objectViewer"], + availability_condition, + ) + + assert excinfo.match("available_permissions must be prefixed with 'inRole:'.") + + def test_invalid_availability_condition_type(self): + with pytest.raises(TypeError) as excinfo: + make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, {"foo": "bar"} + ) + + assert excinfo.match( + "The provided availability_condition is not a 'google.auth.downscoped.AvailabilityCondition' or None." + ) + + def test_to_json(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + + assert access_boundary_rule.to_json() == { + "availablePermissions": AVAILABLE_PERMISSIONS, + "availableResource": AVAILABLE_RESOURCE, + "availabilityCondition": { + "expression": EXPRESSION, + "title": TITLE, + "description": DESCRIPTION, + }, + } + + def test_to_json_required_params_only(self): + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS + ) + + assert access_boundary_rule.to_json() == { + "availablePermissions": AVAILABLE_PERMISSIONS, + "availableResource": AVAILABLE_RESOURCE, + } + + +class TestCredentialAccessBoundary(object): + def test_constructor(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + rules = [access_boundary_rule] + credential_access_boundary = make_credential_access_boundary(rules) + + assert credential_access_boundary.rules == tuple(rules) + + def test_setters(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + rules = [access_boundary_rule] + other_availability_condition = make_availability_condition( + OTHER_EXPRESSION, OTHER_TITLE, OTHER_DESCRIPTION + ) + other_access_boundary_rule = make_access_boundary_rule( + OTHER_AVAILABLE_RESOURCE, + OTHER_AVAILABLE_PERMISSIONS, + other_availability_condition, + ) + other_rules = [other_access_boundary_rule] + credential_access_boundary = make_credential_access_boundary(rules) + credential_access_boundary.rules = other_rules + + assert credential_access_boundary.rules == tuple(other_rules) + + def test_add_rule(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + rules = [access_boundary_rule] * 9 + credential_access_boundary = make_credential_access_boundary(rules) + + # Add one more rule. This should not raise an error. + additional_access_boundary_rule = make_access_boundary_rule( + OTHER_AVAILABLE_RESOURCE, OTHER_AVAILABLE_PERMISSIONS + ) + credential_access_boundary.add_rule(additional_access_boundary_rule) + + assert len(credential_access_boundary.rules) == 10 + assert credential_access_boundary.rules[9] == additional_access_boundary_rule + + def test_add_rule_invalid_value(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + rules = [access_boundary_rule] * 10 + credential_access_boundary = make_credential_access_boundary(rules) + + # Add one more rule to exceed maximum allowed rules. + with pytest.raises(ValueError) as excinfo: + credential_access_boundary.add_rule(access_boundary_rule) + + assert excinfo.match( + "Credential access boundary rules can have a maximum of 10 rules." + ) + assert len(credential_access_boundary.rules) == 10 + + def test_add_rule_invalid_type(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + rules = [access_boundary_rule] + credential_access_boundary = make_credential_access_boundary(rules) + + # Add an invalid rule to exceed maximum allowed rules. + with pytest.raises(TypeError) as excinfo: + credential_access_boundary.add_rule("invalid") + + assert excinfo.match( + "The provided rule does not contain a valid 'google.auth.downscoped.AccessBoundaryRule'." + ) + assert len(credential_access_boundary.rules) == 1 + assert credential_access_boundary.rules[0] == access_boundary_rule + + def test_invalid_rules_type(self): + with pytest.raises(TypeError) as excinfo: + make_credential_access_boundary(["invalid"]) + + assert excinfo.match( + "List of rules provided do not contain a valid 'google.auth.downscoped.AccessBoundaryRule'." + ) + + def test_invalid_rules_value(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + too_many_rules = [access_boundary_rule] * 11 + with pytest.raises(ValueError) as excinfo: + make_credential_access_boundary(too_many_rules) + + assert excinfo.match( + "Credential access boundary rules can have a maximum of 10 rules." + ) + + def test_to_json(self): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + rules = [access_boundary_rule] + credential_access_boundary = make_credential_access_boundary(rules) + + assert credential_access_boundary.to_json() == { + "accessBoundary": { + "accessBoundaryRules": [ + { + "availablePermissions": AVAILABLE_PERMISSIONS, + "availableResource": AVAILABLE_RESOURCE, + "availabilityCondition": { + "expression": EXPRESSION, + "title": TITLE, + "description": DESCRIPTION, + }, + } + ] + } + } + + +class TestCredentials(object): + @staticmethod + def make_credentials(source_credentials=SourceCredentials(), quota_project_id=None): + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + access_boundary_rule = make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + rules = [access_boundary_rule] + credential_access_boundary = make_credential_access_boundary(rules) + + return downscoped.Credentials( + source_credentials, credential_access_boundary, quota_project_id + ) + + @staticmethod + def make_mock_request(data, status=http_client.OK): + response = mock.create_autospec(transport.Response, instance=True) + response.status = status + response.data = json.dumps(data).encode("utf-8") + + request = mock.create_autospec(transport.Request) + request.return_value = response + + return request + + @staticmethod + def assert_request_kwargs(request_kwargs, headers, request_data): + """Asserts the request was called with the expected parameters. + """ + assert request_kwargs["url"] == TOKEN_EXCHANGE_ENDPOINT + assert request_kwargs["method"] == "POST" + assert request_kwargs["headers"] == headers + assert request_kwargs["body"] is not None + body_tuples = urllib.parse.parse_qsl(request_kwargs["body"]) + for (k, v) in body_tuples: + assert v.decode("utf-8") == request_data[k.decode("utf-8")] + assert len(body_tuples) == len(request_data.keys()) + + def test_default_state(self): + credentials = self.make_credentials() + + # No token acquired yet. + assert not credentials.token + assert not credentials.valid + # Expiration hasn't been set yet. + assert not credentials.expiry + assert not credentials.expired + # No quota project ID set. + assert not credentials.quota_project_id + + def test_with_quota_project(self): + credentials = self.make_credentials() + + assert not credentials.quota_project_id + + quota_project_creds = credentials.with_quota_project("project-foo") + + assert quota_project_creds.quota_project_id == "project-foo" + + @mock.patch("google.auth._helpers.utcnow", return_value=datetime.datetime.min) + def test_refresh(self, unused_utcnow): + response = SUCCESS_RESPONSE.copy() + # Test custom expiration to confirm expiry is set correctly. + response["expires_in"] = 2800 + expected_expiry = datetime.datetime.min + datetime.timedelta( + seconds=response["expires_in"] + ) + headers = {"Content-Type": "application/x-www-form-urlencoded"} + request_data = { + "grant_type": GRANT_TYPE, + "subject_token": "ACCESS_TOKEN_1", + "subject_token_type": SUBJECT_TOKEN_TYPE, + "requested_token_type": REQUESTED_TOKEN_TYPE, + "options": urllib.parse.quote(json.dumps(CREDENTIAL_ACCESS_BOUNDARY_JSON)), + } + request = self.make_mock_request(status=http_client.OK, data=response) + source_credentials = SourceCredentials() + credentials = self.make_credentials(source_credentials=source_credentials) + + # Spy on calls to source credentials refresh to confirm the expected request + # instance is used. + with mock.patch.object( + source_credentials, "refresh", wraps=source_credentials.refresh + ) as wrapped_souce_cred_refresh: + credentials.refresh(request) + + self.assert_request_kwargs(request.call_args[1], headers, request_data) + assert credentials.valid + assert credentials.expiry == expected_expiry + assert not credentials.expired + assert credentials.token == response["access_token"] + # Confirm source credentials called with the same request instance. + wrapped_souce_cred_refresh.assert_called_with(request) + + def test_refresh_token_exchange_error(self): + request = self.make_mock_request( + status=http_client.BAD_REQUEST, data=ERROR_RESPONSE + ) + credentials = self.make_credentials() + + with pytest.raises(exceptions.OAuthError) as excinfo: + credentials.refresh(request) + + assert excinfo.match( + r"Error code invalid_grant: Subject token is invalid. - https://tools.ietf.org/html/rfc6749" + ) + assert not credentials.expired + assert credentials.token is None + + def test_refresh_source_credentials_refresh_error(self): + # Initialize downscoped credentials with source credentials that raise + # an error on refresh. + credentials = self.make_credentials( + source_credentials=SourceCredentials(raise_error=True) + ) + + with pytest.raises(exceptions.RefreshError) as excinfo: + credentials.refresh(mock.sentinel.request) + + assert excinfo.match(r"Failed to refresh access token in source credentials.") + assert not credentials.expired + assert credentials.token is None + + def test_apply_without_quota_project_id(self): + headers = {} + request = self.make_mock_request(status=http_client.OK, data=SUCCESS_RESPONSE) + credentials = self.make_credentials() + + credentials.refresh(request) + credentials.apply(headers) + + assert headers == { + "authorization": "Bearer {}".format(SUCCESS_RESPONSE["access_token"]) + } + + def test_apply_with_quota_project_id(self): + headers = {"other": "header-value"} + request = self.make_mock_request(status=http_client.OK, data=SUCCESS_RESPONSE) + credentials = self.make_credentials(quota_project_id=QUOTA_PROJECT_ID) + + credentials.refresh(request) + credentials.apply(headers) + + assert headers == { + "other": "header-value", + "authorization": "Bearer {}".format(SUCCESS_RESPONSE["access_token"]), + "x-goog-user-project": QUOTA_PROJECT_ID, + } + + def test_before_request(self): + headers = {"other": "header-value"} + request = self.make_mock_request(status=http_client.OK, data=SUCCESS_RESPONSE) + credentials = self.make_credentials() + + # First call should call refresh, setting the token. + credentials.before_request(request, "POST", "https://example.com/api", headers) + + assert headers == { + "other": "header-value", + "authorization": "Bearer {}".format(SUCCESS_RESPONSE["access_token"]), + } + + # Second call shouldn't call refresh (request should be untouched). + credentials.before_request( + mock.sentinel.request, "POST", "https://example.com/api", headers + ) + + assert headers == { + "other": "header-value", + "authorization": "Bearer {}".format(SUCCESS_RESPONSE["access_token"]), + } + + @mock.patch("google.auth._helpers.utcnow") + def test_before_request_expired(self, utcnow): + headers = {} + request = self.make_mock_request(status=http_client.OK, data=SUCCESS_RESPONSE) + credentials = self.make_credentials() + credentials.token = "token" + utcnow.return_value = datetime.datetime.min + # Set the expiration to one second more than now plus the clock skew + # accommodation. These credentials should be valid. + credentials.expiry = ( + datetime.datetime.min + _helpers.CLOCK_SKEW + datetime.timedelta(seconds=1) + ) + + assert credentials.valid + assert not credentials.expired + + credentials.before_request(request, "POST", "https://example.com/api", headers) + + # Cached token should be used. + assert headers == {"authorization": "Bearer token"} + + # Next call should simulate 1 second passed. + utcnow.return_value = datetime.datetime.min + datetime.timedelta(seconds=1) + + assert not credentials.valid + assert credentials.expired + + credentials.before_request(request, "POST", "https://example.com/api", headers) + + # New token should be retrieved. + assert headers == { + "authorization": "Bearer {}".format(SUCCESS_RESPONSE["access_token"]) + } diff --git a/tests_async/oauth2/test_id_token.py b/tests_async/oauth2/test_id_token.py index a46bd615e..1deb9efd6 100644 --- a/tests_async/oauth2/test_id_token.py +++ b/tests_async/oauth2/test_id_token.py @@ -21,6 +21,7 @@ from google.auth import exceptions import google.auth.compute_engine._metadata from google.oauth2 import _id_token_async as id_token +from google.oauth2 import _service_account_async from google.oauth2 import id_token as sync_id_token from tests.oauth2 import test_id_token @@ -139,67 +140,106 @@ async def test_verify_firebase_token(verify_token): @pytest.mark.asyncio -async def test_fetch_id_token_from_metadata_server(): +async def test_fetch_id_token_from_metadata_server(monkeypatch): + monkeypatch.delenv(environment_vars.CREDENTIALS, raising=False) + def mock_init(self, request, audience, use_metadata_identity_endpoint): assert use_metadata_identity_endpoint self.token = "id_token" - with mock.patch.multiple( - google.auth.compute_engine.IDTokenCredentials, - __init__=mock_init, - refresh=mock.Mock(), - ): - request = mock.AsyncMock() - token = await id_token.fetch_id_token(request, "https://pubsub.googleapis.com") - assert token == "id_token" + with mock.patch("google.auth.compute_engine._metadata.ping", return_value=True): + with mock.patch.multiple( + google.auth.compute_engine.IDTokenCredentials, + __init__=mock_init, + refresh=mock.Mock(), + ): + request = mock.AsyncMock() + token = await id_token.fetch_id_token( + request, "https://pubsub.googleapis.com" + ) + assert token == "id_token" -@mock.patch.object( - google.auth.compute_engine.IDTokenCredentials, - "__init__", - side_effect=exceptions.TransportError(), -) @pytest.mark.asyncio -async def test_fetch_id_token_from_explicit_cred_json_file(mock_init, monkeypatch): +async def test_fetch_id_token_from_explicit_cred_json_file(monkeypatch): monkeypatch.setenv(environment_vars.CREDENTIALS, test_id_token.SERVICE_ACCOUNT_FILE) async def mock_refresh(self, request): self.token = "id_token" with mock.patch.object( - google.oauth2._service_account_async.IDTokenCredentials, "refresh", mock_refresh + _service_account_async.IDTokenCredentials, "refresh", mock_refresh ): request = mock.AsyncMock() token = await id_token.fetch_id_token(request, "https://pubsub.googleapis.com") assert token == "id_token" -@mock.patch.object( - google.auth.compute_engine.IDTokenCredentials, - "__init__", - side_effect=exceptions.TransportError(), -) @pytest.mark.asyncio -async def test_fetch_id_token_no_cred_json_file(mock_init, monkeypatch): +async def test_fetch_id_token_no_cred_exists(monkeypatch): monkeypatch.delenv(environment_vars.CREDENTIALS, raising=False) - with pytest.raises(exceptions.DefaultCredentialsError): + with mock.patch( + "google.auth.compute_engine._metadata.ping", + side_effect=exceptions.TransportError(), + ): + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: + request = mock.AsyncMock() + await id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"Neither metadata server or valid service account credentials are found." + ) + + with mock.patch("google.auth.compute_engine._metadata.ping", return_value=False): + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: + request = mock.AsyncMock() + await id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"Neither metadata server or valid service account credentials are found." + ) + + +@pytest.mark.asyncio +async def test_fetch_id_token_invalid_cred_file(monkeypatch): + not_json_file = os.path.join( + os.path.dirname(__file__), "../../tests/data/public_cert.pem" + ) + monkeypatch.setenv(environment_vars.CREDENTIALS, not_json_file) + + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: request = mock.AsyncMock() await id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials." + ) -@mock.patch.object( - google.auth.compute_engine.IDTokenCredentials, - "__init__", - side_effect=exceptions.TransportError(), -) @pytest.mark.asyncio -async def test_fetch_id_token_invalid_cred_file(mock_init, monkeypatch): +async def test_fetch_id_token_invalid_cred_type(monkeypatch): + user_credentials_file = os.path.join( + os.path.dirname(__file__), "../../tests/data/authorized_user.json" + ) + monkeypatch.setenv(environment_vars.CREDENTIALS, user_credentials_file) + + with mock.patch("google.auth.compute_engine._metadata.ping", return_value=False): + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: + request = mock.AsyncMock() + await id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"Neither metadata server or valid service account credentials are found." + ) + + +@pytest.mark.asyncio +async def test_fetch_id_token_invalid_cred_path(monkeypatch): not_json_file = os.path.join( - os.path.dirname(__file__), "../../tests/data/public_cert.pem" + os.path.dirname(__file__), "../../tests/data/not_exists.json" ) monkeypatch.setenv(environment_vars.CREDENTIALS, not_json_file) - with pytest.raises(exceptions.DefaultCredentialsError): + with pytest.raises(exceptions.DefaultCredentialsError) as excinfo: request = mock.AsyncMock() await id_token.fetch_id_token(request, "https://pubsub.googleapis.com") + assert excinfo.match( + r"GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid." + ) diff --git a/tests_async/oauth2/test_service_account_async.py b/tests_async/oauth2/test_service_account_async.py index 40794536c..3dce13d82 100644 --- a/tests_async/oauth2/test_service_account_async.py +++ b/tests_async/oauth2/test_service_account_async.py @@ -152,7 +152,10 @@ def test__make_authorization_grant_assertion(self): token = credentials._make_authorization_grant_assertion() payload = jwt.decode(token, test_service_account.PUBLIC_CERT_BYTES) assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL - assert payload["aud"] == self.TOKEN_URI + assert ( + payload["aud"] + == service_account.service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT + ) def test__make_authorization_grant_assertion_scoped(self): credentials = self.make_credentials() @@ -311,7 +314,10 @@ def test__make_authorization_grant_assertion(self): token = credentials._make_authorization_grant_assertion() payload = jwt.decode(token, test_service_account.PUBLIC_CERT_BYTES) assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL - assert payload["aud"] == self.TOKEN_URI + assert ( + payload["aud"] + == service_account.service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT + ) assert payload["target_audience"] == self.TARGET_AUDIENCE @mock.patch("google.oauth2._client_async.id_token_jwt_grant", autospec=True)