diff --git a/google/auth/_default.py b/google/auth/_default.py index d4ccbc6ec..2ed4b12ff 100644 --- a/google/auth/_default.py +++ b/google/auth/_default.py @@ -289,6 +289,13 @@ def _get_gce_credentials(request=None): return None, None +def _get_api_key_credentials(api_key_string=None): + """Gets API key credentials and project ID.""" + from google.auth import api_key + + return api_key.get_api_key_credentials(api_key_string), None + + def _get_external_account_credentials( info, filename, scopes=None, default_scopes=None, request=None ): @@ -348,7 +355,9 @@ def _get_external_account_credentials( return credentials, credentials.get_project_id(request=request) -def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): +def default( + scopes=None, request=None, quota_project_id=None, default_scopes=None, api_key=None +): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain @@ -356,7 +365,12 @@ def default(scopes=None, request=None, quota_project_id=None, default_scopes=Non This function acquires credentials from the environment in the following order: - 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set + 1. If `api_key` is provided or the environment variable ``GOOGLE_API_KEY`` is + set, an `API Key`_ credentials will be returned. The provided `api_key` + takes precedence over the environment variable. + The project ID returned is the one defined by ``GOOGLE_CLOUD_PROJECT`` or + ``GCLOUD_PROJECT`` environment variables. + 2. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not @@ -370,7 +384,7 @@ def default(scopes=None, request=None, quota_project_id=None, default_scopes=Non endpoint. The project ID returned in this case is the one corresponding to the underlying workload identity pool resource if determinable. - 2. If the `Google Cloud SDK`_ is installed and has application default + 3. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: @@ -382,14 +396,14 @@ def default(scopes=None, request=None, quota_project_id=None, default_scopes=Non gcloud config set project - 3. If the application is running in the `App Engine standard environment`_ + 4. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. - 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or + 5. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. - 5. If no credentials are found, + 6. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ @@ -404,6 +418,7 @@ def default(scopes=None, request=None, quota_project_id=None, default_scopes=Non .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run + .. _API Key: https://cloud.google.com/docs/authentication/api-keys Example:: @@ -427,6 +442,7 @@ def default(scopes=None, request=None, quota_project_id=None, default_scopes=Non quota and billing. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. + api_key (Optional[str]): The API key used to create API key credentials. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID @@ -439,6 +455,7 @@ def default(scopes=None, request=None, quota_project_id=None, default_scopes=Non invalid. """ from google.auth.credentials import with_scopes_if_required + from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) @@ -449,6 +466,7 @@ def default(scopes=None, request=None, quota_project_id=None, default_scopes=Non # with_scopes_if_required() below will ensure scopes/default scopes are # safely set on the returned credentials since requires_scopes will # guard against setting scopes on user credentials. + lambda: _get_api_key_credentials(api_key), lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, @@ -472,7 +490,9 @@ def default(scopes=None, request=None, quota_project_id=None, default_scopes=Non request = google.auth.transport.requests.Request() project_id = credentials.get_project_id(request=request) - if quota_project_id: + if quota_project_id and isinstance( + credentials, CredentialsWithQuotaProject + ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id diff --git a/google/auth/_default_async.py b/google/auth/_default_async.py index 3fa125b46..0d7545675 100644 --- a/google/auth/_default_async.py +++ b/google/auth/_default_async.py @@ -159,6 +159,12 @@ def _get_gae_credentials(): return _default._get_gae_credentials() +def _get_api_key_credentials(api_key_string=None): + """Gets API key credentials and project ID.""" + + return _default._get_api_key_credentials(api_key_string) + + def _get_gce_credentials(request=None): """Gets credentials and project ID from the GCE Metadata Service.""" # Ping requires a transport, but we want application default credentials @@ -172,7 +178,7 @@ def _get_gce_credentials(request=None): return _default._get_gce_credentials(request) -def default_async(scopes=None, request=None, quota_project_id=None): +def default_async(scopes=None, request=None, quota_project_id=None, api_key=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain @@ -180,12 +186,17 @@ def default_async(scopes=None, request=None, quota_project_id=None): This function acquires credentials from the environment in the following order: - 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set + 1. If `api_key` is provided or the environment variable ``GOOGLE_API_KEY`` is + set, an `API Key`_ credentials will be returned. The provided `api_key` + takes precedence over the environment variable. + The project ID returned is the one defined by ``GOOGLE_CLOUD_PROJECT`` or + ``GCLOUD_PROJECT`` environment variables. + 2. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). - 2. If the `Google Cloud SDK`_ is installed and has application default + 3. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: @@ -197,14 +208,14 @@ def default_async(scopes=None, request=None, quota_project_id=None): gcloud config set project - 3. If the application is running in the `App Engine standard environment`_ + 4. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. - 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or + 5. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. - 5. If no credentials are found, + 6. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ @@ -219,6 +230,7 @@ def default_async(scopes=None, request=None, quota_project_id=None): .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run + .. _API Key: https://cloud.google.com/docs/authentication/api-keys Example:: @@ -248,12 +260,14 @@ def default_async(scopes=None, request=None, quota_project_id=None): invalid. """ from google.auth._credentials_async import with_scopes_if_required + from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( + lambda: _get_api_key_credentials(api_key), lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, @@ -263,9 +277,11 @@ def default_async(scopes=None, request=None, quota_project_id=None): for checker in checkers: credentials, project_id = checker() if credentials is not None: - credentials = with_scopes_if_required( - credentials, scopes - ).with_quota_project(quota_project_id) + credentials = with_scopes_if_required(credentials, scopes) + if quota_project_id and isinstance( + credentials, CredentialsWithQuotaProject + ): + credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _default._LOGGER.warning( diff --git a/google/auth/api_key.py b/google/auth/api_key.py new file mode 100644 index 000000000..c311ef63b --- /dev/null +++ b/google/auth/api_key.py @@ -0,0 +1,103 @@ +# 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. + +"""Google API key support. + +This module provides authentication using the `API key`_. + + +.. _API key: + https://cloud.google.com/docs/authentication/api-keys/ +""" + +import os + +from google.auth import _helpers +from google.auth import credentials +from google.auth import environment_vars + + +class Credentials(credentials.Credentials): + """API key credentials. + + These credentials use API key to provide authorization to applications. + """ + + def __init__(self, token): + """ + Args: + token (str): API key string + + Raises: + ValueError: If the provided API key is not a non-empty string. + """ + if not token: + raise ValueError("Token must be a non-empty API key string") + super(Credentials, self).__init__() + self.token = token + + @property + @_helpers.copy_docstring(credentials.Credentials) + def expired(self): + return False + + @property + @_helpers.copy_docstring(credentials.Credentials) + def valid(self): + return True + + @_helpers.copy_docstring(credentials.Credentials) + def refresh(self, request): + return + + def apply(self, headers, token=None): + """Apply the API key token to the x-goog-api-key header. + + Args: + headers (Mapping): The HTTP request headers. + token (Optional[str]): If specified, overrides the current access + token. + """ + headers["x-goog-api-key"] = token or self.token + + def before_request(self, request, method, url, headers): + """Performs credential-specific before request logic. + + Refreshes the credentials if necessary, then calls :meth:`apply` to + apply the token to the x-goog-api-key header. + + Args: + request (google.auth.transport.Request): The object used to make + HTTP requests. + method (str): The request's HTTP method or the RPC method being + invoked. + url (str): The request's URI or the RPC service's URI. + headers (Mapping): The request's headers. + """ + self.apply(headers) + + +def get_api_key_credentials(api_key_string=None): + """If API key is provided via api_key_string or GOOGLE_API_KEY environment + variable, return the API key credentials; other return None. + + Args: + api_key_string (str): The API key string. + + Returns: + google.auth.api_key.Credentials: The constructed API key credentials. + """ + + api_key_to_use = api_key_string or os.environ.get(environment_vars.API_KEY) + return Credentials(api_key_to_use) if api_key_to_use else None diff --git a/google/auth/environment_vars.py b/google/auth/environment_vars.py index d36d6c4af..ee5fd7bcc 100644 --- a/google/auth/environment_vars.py +++ b/google/auth/environment_vars.py @@ -33,6 +33,9 @@ """Environment variable defining the location of Google application default credentials.""" +API_KEY = "GOOGLE_API_KEY" +"""Environment variable defining the API key value.""" + # The environment variable name which can replace ~/.config if set. CLOUD_SDK_CONFIG_DIR = "CLOUDSDK_CONFIG" """Environment variable defines the location of Google Cloud SDK's config diff --git a/tests/test__default.py b/tests/test__default.py index c70ceaa57..40709ec28 100644 --- a/tests/test__default.py +++ b/tests/test__default.py @@ -19,6 +19,7 @@ import pytest from google.auth import _default +from google.auth import api_key from google.auth import app_engine from google.auth import aws from google.auth import compute_engine @@ -805,3 +806,43 @@ def test_default_no_warning_with_quota_project_id_for_user_creds(get_adc_path): get_adc_path.return_value = AUTHORIZED_USER_CLOUD_SDK_FILE credentials, project_id = _default.default(quota_project_id="project-foo") + + +def test__get_api_key_credentials(): + cred, project_id = _default._get_api_key_credentials("api-key") + assert isinstance(cred, api_key.Credentials) + assert cred.token == "api-key" + assert project_id is None + + +def test__get_api_key_credentials_from_env_var(): + with mock.patch.dict(os.environ, {environment_vars.API_KEY: "api-key"}): + cred, project_id = _default._get_api_key_credentials() + assert isinstance(cred, api_key.Credentials) + assert cred.token == "api-key" + assert project_id is None + + +@mock.patch( + "google.auth._default._get_explicit_environ_credentials", + return_value=(MOCK_CREDENTIALS, mock.sentinel.project_id), + autospec=True, +) +def test_default_api_key(unused_get): + cred, project_id = _default.default(api_key="api-key") + assert isinstance(cred, api_key.Credentials) + assert cred.token == "api-key" + assert project_id is None + + +@mock.patch( + "google.auth._default._get_explicit_environ_credentials", + return_value=(MOCK_CREDENTIALS, mock.sentinel.project_id), + autospec=True, +) +def test_default_api_key_from_env_var(unused_get): + with mock.patch.dict(os.environ, {environment_vars.API_KEY: "api-key"}): + cred, project_id = _default.default() + assert isinstance(cred, api_key.Credentials) + assert cred.token == "api-key" + assert project_id is None diff --git a/tests/test_api_key.py b/tests/test_api_key.py new file mode 100644 index 000000000..05ddd6529 --- /dev/null +++ b/tests/test_api_key.py @@ -0,0 +1,67 @@ +# 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 mock +import os +import pytest + +from google.auth import api_key +from google.auth import environment_vars + + +def test_credentials_constructor(): + with pytest.raises(ValueError) as excinfo: + api_key.Credentials("") + + assert excinfo.match(r"Token must be a non-empty API key string") + + +def test_expired_and_valid(): + credentials = api_key.Credentials("api-key") + + assert credentials.valid + assert credentials.token == "api-key" + assert not credentials.expired + + credentials.refresh(None) + assert credentials.valid + assert credentials.token == "api-key" + assert not credentials.expired + + +def test_before_request(): + credentials = api_key.Credentials("api-key") + headers = {} + + credentials.before_request(None, "http://example.com", "GET", headers) + assert headers["x-goog-api-key"] == "api-key" + + +def test_get_api_key_credentials_no_api_key(): + cred = api_key.get_api_key_credentials("api-key") + assert isinstance(cred, api_key.Credentials) + assert cred.token == "api-key" + + +def test_get_api_key_credentials(): + cred = api_key.get_api_key_credentials("api-key") + assert isinstance(cred, api_key.Credentials) + assert cred.token == "api-key" + + +def test_get_api_key_credentials_from_env_var(): + with mock.patch.dict(os.environ, {environment_vars.API_KEY: "api-key"}): + cred = api_key.get_api_key_credentials() + assert isinstance(cred, api_key.Credentials) + assert cred.token == "api-key" diff --git a/tests_async/test__default_async.py b/tests_async/test__default_async.py index 69a50d69a..dca1ae9fa 100644 --- a/tests_async/test__default_async.py +++ b/tests_async/test__default_async.py @@ -20,6 +20,7 @@ from google.auth import _credentials_async as credentials from google.auth import _default_async as _default +from google.auth import api_key from google.auth import app_engine from google.auth import compute_engine from google.auth import environment_vars @@ -561,3 +562,28 @@ def test_default_no_warning_with_quota_project_id_for_user_creds(get_adc_path): get_adc_path.return_value = test_default.AUTHORIZED_USER_CLOUD_SDK_FILE credentials, project_id = _default.default_async(quota_project_id="project-foo") + + +@mock.patch( + "google.auth._default_async._get_explicit_environ_credentials", + return_value=(MOCK_CREDENTIALS, mock.sentinel.project_id), + autospec=True, +) +def test_default_api_key(unused_get): + cred, project_id = _default.default_async(api_key="api-key") + assert isinstance(cred, api_key.Credentials) + assert cred.token == "api-key" + assert project_id is None + + +@mock.patch( + "google.auth._default_async._get_explicit_environ_credentials", + return_value=(MOCK_CREDENTIALS, mock.sentinel.project_id), + autospec=True, +) +def test_default_api_key_from_env_var(unused_get): + with mock.patch.dict(os.environ, {environment_vars.API_KEY: "api-key"}): + cred, project_id = _default.default_async() + assert isinstance(cred, api_key.Credentials) + assert cred.token == "api-key" + assert project_id is None