Skip to content

Commit 1b2706e

Browse files
feat: add api_key credentials (#1184)
1 parent c63652c commit 1b2706e

4 files changed

Lines changed: 134 additions & 0 deletions

File tree

packages/google-auth/google/auth/_default.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,13 @@ def _get_gdch_service_account_credentials(filename, info):
479479
return credentials, info.get("project")
480480

481481

482+
def get_api_key_credentials(key):
483+
"""Return credentials with the given API key."""
484+
from google.auth import api_key
485+
486+
return api_key.Credentials(key)
487+
488+
482489
def _apply_quota_project_id(credentials, quota_project_id):
483490
if quota_project_id:
484491
credentials = credentials.with_quota_project(quota_project_id)
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Google API key support.
16+
This module provides authentication using the `API key`_.
17+
.. _API key:
18+
https://cloud.google.com/docs/authentication/api-keys/
19+
"""
20+
21+
from google.auth import _helpers
22+
from google.auth import credentials
23+
24+
25+
class Credentials(credentials.Credentials):
26+
"""API key credentials.
27+
These credentials use API key to provide authorization to applications.
28+
"""
29+
30+
def __init__(self, token):
31+
"""
32+
Args:
33+
token (str): API key string
34+
Raises:
35+
ValueError: If the provided API key is not a non-empty string.
36+
"""
37+
super(Credentials, self).__init__()
38+
if not token:
39+
raise ValueError("Token must be a non-empty API key string")
40+
self.token = token
41+
42+
@property
43+
def expired(self):
44+
return False
45+
46+
@property
47+
def valid(self):
48+
return True
49+
50+
@_helpers.copy_docstring(credentials.Credentials)
51+
def refresh(self, request):
52+
return
53+
54+
def apply(self, headers, token=None):
55+
"""Apply the API key token to the x-goog-api-key header.
56+
Args:
57+
headers (Mapping): The HTTP request headers.
58+
token (Optional[str]): If specified, overrides the current access
59+
token.
60+
"""
61+
headers["x-goog-api-key"] = token or self.token
62+
63+
def before_request(self, request, method, url, headers):
64+
"""Performs credential-specific before request logic.
65+
Refreshes the credentials if necessary, then calls :meth:`apply` to
66+
apply the token to the x-goog-api-key header.
67+
Args:
68+
request (google.auth.transport.Request): The object used to make
69+
HTTP requests.
70+
method (str): The request's HTTP method or the RPC method being
71+
invoked.
72+
url (str): The request's URI or the RPC service's URI.
73+
headers (Mapping): The request's headers.
74+
"""
75+
self.apply(headers)

packages/google-auth/tests/test__default.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import pytest # type: ignore
2020

2121
from google.auth import _default
22+
from google.auth import api_key
2223
from google.auth import app_engine
2324
from google.auth import aws
2425
from google.auth import compute_engine
@@ -683,6 +684,12 @@ def test__get_gdch_service_account_credentials_invalid_format_version():
683684
assert excinfo.match("Failed to load GDCH service account credentials")
684685

685686

687+
def test_get_api_key_credentials():
688+
creds = _default.get_api_key_credentials("api_key")
689+
assert isinstance(creds, api_key.Credentials)
690+
assert creds.token == "api_key"
691+
692+
686693
class _AppIdentityModule(object):
687694
"""The interface of the App Idenity app engine module.
688695
See https://cloud.google.com/appengine/docs/standard/python/refdocs\
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import pytest # type: ignore
16+
17+
from google.auth import api_key
18+
19+
20+
def test_credentials_constructor():
21+
with pytest.raises(ValueError) as excinfo:
22+
api_key.Credentials("")
23+
24+
assert excinfo.match(r"Token must be a non-empty API key string")
25+
26+
27+
def test_expired_and_valid():
28+
credentials = api_key.Credentials("api-key")
29+
30+
assert credentials.valid
31+
assert credentials.token == "api-key"
32+
assert not credentials.expired
33+
34+
credentials.refresh(None)
35+
assert credentials.valid
36+
assert credentials.token == "api-key"
37+
assert not credentials.expired
38+
39+
40+
def test_before_request():
41+
credentials = api_key.Credentials("api-key")
42+
headers = {}
43+
44+
credentials.before_request(None, "http://example.com", "GET", headers)
45+
assert headers["x-goog-api-key"] == "api-key"

0 commit comments

Comments
 (0)