Skip to content

Commit

Permalink
feat: add api key support (#826)
Browse files Browse the repository at this point in the history
* feat: add api key support

* chore: update

* Update google/auth/_default.py

Co-authored-by: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com>

Co-authored-by: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com>
  • Loading branch information
arithmetic1728 and busunkim96 authored Jan 19, 2022
1 parent a60b97e commit 3b15092
Show file tree
Hide file tree
Showing 7 changed files with 299 additions and 6 deletions.
41 changes: 39 additions & 2 deletions google/auth/_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,24 @@ def _get_external_account_credentials(
return credentials, credentials.get_project_id(request=request)


def _get_api_key_credentials(quota_project_id=None):
"""Gets API key credentials and project ID."""
from google.auth import api_key

api_key_value = os.environ.get(environment_vars.API_KEY)
if api_key_value:
return api_key.Credentials(api_key_value), quota_project_id
else:
return None, None


def get_api_key_credentials(api_key_value):
"""Gets API key credentials using the given api key value."""
from google.auth import api_key

return api_key.Credentials(api_key_value)


def default(scopes=None, request=None, quota_project_id=None, default_scopes=None):
"""Gets the default credentials for the current environment.
Expand All @@ -361,7 +379,14 @@ 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 both ``GOOGLE_API_KEY`` and ``GOOGLE_APPLICATION_CREDENTIALS``
environment variables are set, throw an exception.
If ``GOOGLE_API_KEY`` is set, an `API Key`_ credentials will be returned.
The project ID returned is the one defined by ``GOOGLE_CLOUD_PROJECT`` or
``GCLOUD_PROJECT`` environment variables.
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
Expand Down Expand Up @@ -409,6 +434,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::
Expand Down Expand Up @@ -444,16 +470,25 @@ 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)
)

if os.environ.get(environment_vars.API_KEY) and os.environ.get(
environment_vars.CREDENTIALS
):
raise exceptions.DefaultCredentialsError(
"Environment variables GOOGLE_API_KEY and GOOGLE_APPLICATION_CREDENTIALS are mutually exclusive"
)

checkers = (
# Avoid passing scopes here to prevent passing scopes to user credentials.
# 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(quota_project_id=quota_project_id),
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,
Expand All @@ -477,7 +512,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
Expand Down
45 changes: 41 additions & 4 deletions google/auth/_default_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,24 @@ def _get_gae_credentials():
return _default._get_gae_credentials()


def _get_api_key_credentials(quota_project_id=None):
"""Gets API key credentials and project ID."""
from google.auth import api_key

api_key_value = os.environ.get(environment_vars.API_KEY)
if api_key_value:
return api_key.Credentials(api_key_value), quota_project_id
else:
return None, None


def get_api_key_credentials(api_key_value):
"""Gets API key credentials using the given api key value."""
from google.auth import api_key

return api_key.Credentials(api_key_value)


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
Expand All @@ -182,7 +200,14 @@ 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 both ``GOOGLE_API_KEY`` and ``GOOGLE_APPLICATION_CREDENTIALS``
environment variables are set, throw an exception.
If ``GOOGLE_API_KEY`` is set, an `API Key`_ credentials will be returned.
The project ID returned is the one defined by ``GOOGLE_CLOUD_PROJECT`` or
``GCLOUD_PROJECT`` environment variables.
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
Expand Down Expand Up @@ -221,6 +246,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::
Expand Down Expand Up @@ -250,12 +276,21 @@ 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)
)

if os.environ.get(environment_vars.API_KEY) and os.environ.get(
environment_vars.CREDENTIALS
):
raise exceptions.DefaultCredentialsError(
"GOOGLE_API_KEY and GOOGLE_APPLICATION_CREDENTIALS are mutually exclusive"
)

checkers = (
lambda: _get_api_key_credentials(quota_project_id=quota_project_id),
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,
Expand All @@ -265,9 +300,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(
Expand Down
83 changes: 83 additions & 0 deletions google/auth/api_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# 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/
"""

from google.auth import _helpers
from google.auth import credentials


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
def expired(self):
return False

@property
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)
3 changes: 3 additions & 0 deletions google/auth/environment_vars.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 44 additions & 0 deletions tests/test__default.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import pytest # type: ignore

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
Expand Down Expand Up @@ -994,3 +995,46 @@ 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_no_env_var():
cred, project_id = _default._get_api_key_credentials(quota_project_id="project-foo")
assert cred is None
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(
quota_project_id="project-foo"
)
assert isinstance(cred, api_key.Credentials)
assert cred.token == "api-key"
assert project_id == "project-foo"


def test_exception_with_api_key_and_adc_env_var():
with mock.patch.dict(os.environ, {environment_vars.API_KEY: "api-key"}):
with mock.patch.dict(
os.environ, {environment_vars.CREDENTIALS: "/path/to/json"}
):
with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
_default.default()

assert excinfo.match(
r"GOOGLE_API_KEY and GOOGLE_APPLICATION_CREDENTIALS are mutually exclusive"
)


def test_default_api_key_from_env_var():
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


def test_get_api_key_credentials():
cred = _default.get_api_key_credentials("api-key")
assert isinstance(cred, api_key.Credentials)
assert cred.token == "api-key"
45 changes: 45 additions & 0 deletions tests/test_api_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# 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 pytest # type: ignore

from google.auth import api_key


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"
Loading

0 comments on commit 3b15092

Please sign in to comment.