Skip to content
This repository was archived by the owner on Sep 5, 2023. It is now read-only.

Commit 4056e97

Browse files
feat: add api key support (#240)
* chore: upgrade gapic-generator-java, gax-java and gapic-generator-python PiperOrigin-RevId: 423842556 Source-Link: googleapis/googleapis@a616ca0 Source-Link: https://github.com/googleapis/googleapis-gen/commit/29b938c58c1e51d019f2ee539d55dc0a3c86a905 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMjliOTM4YzU4YzFlNTFkMDE5ZjJlZTUzOWQ1NWRjMGEzYzg2YTkwNSJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 5575226 commit 4056e97

File tree

3 files changed

+254
-44
lines changed

3 files changed

+254
-44
lines changed

google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from collections import OrderedDict
1717
import functools
1818
import re
19-
from typing import Dict, Sequence, Tuple, Type, Union
19+
from typing import Dict, Optional, Sequence, Tuple, Type, Union
2020
import pkg_resources
2121

2222
from google.api_core.client_options import ClientOptions
@@ -125,6 +125,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
125125

126126
from_service_account_json = from_service_account_file
127127

128+
@classmethod
129+
def get_mtls_endpoint_and_cert_source(
130+
cls, client_options: Optional[ClientOptions] = None
131+
):
132+
"""Return the API endpoint and client cert source for mutual TLS.
133+
134+
The client cert source is determined in the following order:
135+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
136+
client cert source is None.
137+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
138+
default client cert source exists, use the default one; otherwise the client cert
139+
source is None.
140+
141+
The API endpoint is determined in the following order:
142+
(1) if `client_options.api_endpoint` if provided, use the provided one.
143+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
144+
default mTLS endpoint; if the environment variabel is "never", use the default API
145+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
146+
use the default API endpoint.
147+
148+
More details can be found at https://google.aip.dev/auth/4114.
149+
150+
Args:
151+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
152+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
153+
in this method.
154+
155+
Returns:
156+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
157+
client cert source to use.
158+
159+
Raises:
160+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
161+
"""
162+
return SecretManagerServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
163+
128164
@property
129165
def transport(self) -> SecretManagerServiceTransport:
130166
"""Returns the transport used by the client instance.

google/cloud/secretmanager_v1/services/secret_manager_service/client.py

Lines changed: 84 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
273273
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
274274
return m.groupdict() if m else {}
275275

276+
@classmethod
277+
def get_mtls_endpoint_and_cert_source(
278+
cls, client_options: Optional[client_options_lib.ClientOptions] = None
279+
):
280+
"""Return the API endpoint and client cert source for mutual TLS.
281+
282+
The client cert source is determined in the following order:
283+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
284+
client cert source is None.
285+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
286+
default client cert source exists, use the default one; otherwise the client cert
287+
source is None.
288+
289+
The API endpoint is determined in the following order:
290+
(1) if `client_options.api_endpoint` if provided, use the provided one.
291+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
292+
default mTLS endpoint; if the environment variabel is "never", use the default API
293+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
294+
use the default API endpoint.
295+
296+
More details can be found at https://google.aip.dev/auth/4114.
297+
298+
Args:
299+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
300+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
301+
in this method.
302+
303+
Returns:
304+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
305+
client cert source to use.
306+
307+
Raises:
308+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
309+
"""
310+
if client_options is None:
311+
client_options = client_options_lib.ClientOptions()
312+
use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
313+
use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
314+
if use_client_cert not in ("true", "false"):
315+
raise ValueError(
316+
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
317+
)
318+
if use_mtls_endpoint not in ("auto", "never", "always"):
319+
raise MutualTLSChannelError(
320+
"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
321+
)
322+
323+
# Figure out the client cert source to use.
324+
client_cert_source = None
325+
if use_client_cert == "true":
326+
if client_options.client_cert_source:
327+
client_cert_source = client_options.client_cert_source
328+
elif mtls.has_default_client_cert_source():
329+
client_cert_source = mtls.default_client_cert_source()
330+
331+
# Figure out which api endpoint to use.
332+
if client_options.api_endpoint is not None:
333+
api_endpoint = client_options.api_endpoint
334+
elif use_mtls_endpoint == "always" or (
335+
use_mtls_endpoint == "auto" and client_cert_source
336+
):
337+
api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
338+
else:
339+
api_endpoint = cls.DEFAULT_ENDPOINT
340+
341+
return api_endpoint, client_cert_source
342+
276343
def __init__(
277344
self,
278345
*,
@@ -323,57 +390,22 @@ def __init__(
323390
if client_options is None:
324391
client_options = client_options_lib.ClientOptions()
325392

326-
# Create SSL credentials for mutual TLS if needed.
327-
if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in (
328-
"true",
329-
"false",
330-
):
331-
raise ValueError(
332-
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
333-
)
334-
use_client_cert = (
335-
os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true"
393+
api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
394+
client_options
336395
)
337396

338-
client_cert_source_func = None
339-
is_mtls = False
340-
if use_client_cert:
341-
if client_options.client_cert_source:
342-
is_mtls = True
343-
client_cert_source_func = client_options.client_cert_source
344-
else:
345-
is_mtls = mtls.has_default_client_cert_source()
346-
if is_mtls:
347-
client_cert_source_func = mtls.default_client_cert_source()
348-
else:
349-
client_cert_source_func = None
350-
351-
# Figure out which api endpoint to use.
352-
if client_options.api_endpoint is not None:
353-
api_endpoint = client_options.api_endpoint
354-
else:
355-
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
356-
if use_mtls_env == "never":
357-
api_endpoint = self.DEFAULT_ENDPOINT
358-
elif use_mtls_env == "always":
359-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
360-
elif use_mtls_env == "auto":
361-
if is_mtls:
362-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
363-
else:
364-
api_endpoint = self.DEFAULT_ENDPOINT
365-
else:
366-
raise MutualTLSChannelError(
367-
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
368-
"values: never, auto, always"
369-
)
397+
api_key_value = getattr(client_options, "api_key", None)
398+
if api_key_value and credentials:
399+
raise ValueError(
400+
"client_options.api_key and credentials are mutually exclusive"
401+
)
370402

371403
# Save or instantiate the transport.
372404
# Ordinarily, we provide the transport, but allowing a custom transport
373405
# instance provides an extensibility point for unusual situations.
374406
if isinstance(transport, SecretManagerServiceTransport):
375407
# transport is a SecretManagerServiceTransport instance.
376-
if credentials or client_options.credentials_file:
408+
if credentials or client_options.credentials_file or api_key_value:
377409
raise ValueError(
378410
"When providing a transport instance, "
379411
"provide its credentials directly."
@@ -385,6 +417,15 @@ def __init__(
385417
)
386418
self._transport = transport
387419
else:
420+
import google.auth._default # type: ignore
421+
422+
if api_key_value and hasattr(
423+
google.auth._default, "get_api_key_credentials"
424+
):
425+
credentials = google.auth._default.get_api_key_credentials(
426+
api_key_value
427+
)
428+
388429
Transport = type(self).get_transport_class(transport)
389430
self._transport = Transport(
390431
credentials=credentials,

tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,87 @@ def test_secret_manager_service_client_mtls_env_auto(
422422
)
423423

424424

425+
@pytest.mark.parametrize(
426+
"client_class", [SecretManagerServiceClient, SecretManagerServiceAsyncClient]
427+
)
428+
@mock.patch.object(
429+
SecretManagerServiceClient,
430+
"DEFAULT_ENDPOINT",
431+
modify_default_endpoint(SecretManagerServiceClient),
432+
)
433+
@mock.patch.object(
434+
SecretManagerServiceAsyncClient,
435+
"DEFAULT_ENDPOINT",
436+
modify_default_endpoint(SecretManagerServiceAsyncClient),
437+
)
438+
def test_secret_manager_service_client_get_mtls_endpoint_and_cert_source(client_class):
439+
mock_client_cert_source = mock.Mock()
440+
441+
# Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true".
442+
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
443+
mock_api_endpoint = "foo"
444+
options = client_options.ClientOptions(
445+
client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
446+
)
447+
api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
448+
options
449+
)
450+
assert api_endpoint == mock_api_endpoint
451+
assert cert_source == mock_client_cert_source
452+
453+
# Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false".
454+
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
455+
mock_client_cert_source = mock.Mock()
456+
mock_api_endpoint = "foo"
457+
options = client_options.ClientOptions(
458+
client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
459+
)
460+
api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
461+
options
462+
)
463+
assert api_endpoint == mock_api_endpoint
464+
assert cert_source is None
465+
466+
# Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never".
467+
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
468+
api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
469+
assert api_endpoint == client_class.DEFAULT_ENDPOINT
470+
assert cert_source is None
471+
472+
# Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always".
473+
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
474+
api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
475+
assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
476+
assert cert_source is None
477+
478+
# Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist.
479+
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
480+
with mock.patch(
481+
"google.auth.transport.mtls.has_default_client_cert_source",
482+
return_value=False,
483+
):
484+
api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
485+
assert api_endpoint == client_class.DEFAULT_ENDPOINT
486+
assert cert_source is None
487+
488+
# Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists.
489+
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
490+
with mock.patch(
491+
"google.auth.transport.mtls.has_default_client_cert_source",
492+
return_value=True,
493+
):
494+
with mock.patch(
495+
"google.auth.transport.mtls.default_client_cert_source",
496+
return_value=mock_client_cert_source,
497+
):
498+
(
499+
api_endpoint,
500+
cert_source,
501+
) = client_class.get_mtls_endpoint_and_cert_source()
502+
assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
503+
assert cert_source == mock_client_cert_source
504+
505+
425506
@pytest.mark.parametrize(
426507
"client_class,transport_class,transport_name",
427508
[
@@ -3987,6 +4068,25 @@ def test_credentials_transport_error():
39874068
transport=transport,
39884069
)
39894070

4071+
# It is an error to provide an api_key and a transport instance.
4072+
transport = transports.SecretManagerServiceGrpcTransport(
4073+
credentials=ga_credentials.AnonymousCredentials(),
4074+
)
4075+
options = client_options.ClientOptions()
4076+
options.api_key = "api_key"
4077+
with pytest.raises(ValueError):
4078+
client = SecretManagerServiceClient(
4079+
client_options=options, transport=transport,
4080+
)
4081+
4082+
# It is an error to provide an api_key and a credential.
4083+
options = mock.Mock()
4084+
options.api_key = "api_key"
4085+
with pytest.raises(ValueError):
4086+
client = SecretManagerServiceClient(
4087+
client_options=options, credentials=ga_credentials.AnonymousCredentials()
4088+
)
4089+
39904090
# It is an error to provide scopes and a transport instance.
39914091
transport = transports.SecretManagerServiceGrpcTransport(
39924092
credentials=ga_credentials.AnonymousCredentials(),
@@ -4608,3 +4708,36 @@ def test_client_ctx():
46084708
with client:
46094709
pass
46104710
close.assert_called()
4711+
4712+
4713+
@pytest.mark.parametrize(
4714+
"client_class,transport_class",
4715+
[
4716+
(SecretManagerServiceClient, transports.SecretManagerServiceGrpcTransport),
4717+
(
4718+
SecretManagerServiceAsyncClient,
4719+
transports.SecretManagerServiceGrpcAsyncIOTransport,
4720+
),
4721+
],
4722+
)
4723+
def test_api_key_credentials(client_class, transport_class):
4724+
with mock.patch.object(
4725+
google.auth._default, "get_api_key_credentials", create=True
4726+
) as get_api_key_credentials:
4727+
mock_cred = mock.Mock()
4728+
get_api_key_credentials.return_value = mock_cred
4729+
options = client_options.ClientOptions()
4730+
options.api_key = "api_key"
4731+
with mock.patch.object(transport_class, "__init__") as patched:
4732+
patched.return_value = None
4733+
client = client_class(client_options=options)
4734+
patched.assert_called_once_with(
4735+
credentials=mock_cred,
4736+
credentials_file=None,
4737+
host=client.DEFAULT_ENDPOINT,
4738+
scopes=None,
4739+
client_cert_source_for_mtls=None,
4740+
quota_project_id=None,
4741+
client_info=transports.base.DEFAULT_CLIENT_INFO,
4742+
always_use_jwt_access=True,
4743+
)

0 commit comments

Comments
 (0)