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

Commit ef5104e

Browse files
feat: add api key support (#135)
* 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 5a9f20c commit ef5104e

File tree

6 files changed

+498
-88
lines changed

6 files changed

+498
-88
lines changed

google/cloud/memcache_v1/services/cloud_memcache/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
@@ -130,6 +130,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
130130

131131
from_service_account_json = from_service_account_file
132132

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

google/cloud/memcache_v1/services/cloud_memcache/client.py

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

259+
@classmethod
260+
def get_mtls_endpoint_and_cert_source(
261+
cls, client_options: Optional[client_options_lib.ClientOptions] = None
262+
):
263+
"""Return the API endpoint and client cert source for mutual TLS.
264+
265+
The client cert source is determined in the following order:
266+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
267+
client cert source is None.
268+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
269+
default client cert source exists, use the default one; otherwise the client cert
270+
source is None.
271+
272+
The API endpoint is determined in the following order:
273+
(1) if `client_options.api_endpoint` if provided, use the provided one.
274+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
275+
default mTLS endpoint; if the environment variabel is "never", use the default API
276+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
277+
use the default API endpoint.
278+
279+
More details can be found at https://google.aip.dev/auth/4114.
280+
281+
Args:
282+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
283+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
284+
in this method.
285+
286+
Returns:
287+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
288+
client cert source to use.
289+
290+
Raises:
291+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
292+
"""
293+
if client_options is None:
294+
client_options = client_options_lib.ClientOptions()
295+
use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
296+
use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
297+
if use_client_cert not in ("true", "false"):
298+
raise ValueError(
299+
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
300+
)
301+
if use_mtls_endpoint not in ("auto", "never", "always"):
302+
raise MutualTLSChannelError(
303+
"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
304+
)
305+
306+
# Figure out the client cert source to use.
307+
client_cert_source = None
308+
if use_client_cert == "true":
309+
if client_options.client_cert_source:
310+
client_cert_source = client_options.client_cert_source
311+
elif mtls.has_default_client_cert_source():
312+
client_cert_source = mtls.default_client_cert_source()
313+
314+
# Figure out which api endpoint to use.
315+
if client_options.api_endpoint is not None:
316+
api_endpoint = client_options.api_endpoint
317+
elif use_mtls_endpoint == "always" or (
318+
use_mtls_endpoint == "auto" and client_cert_source
319+
):
320+
api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
321+
else:
322+
api_endpoint = cls.DEFAULT_ENDPOINT
323+
324+
return api_endpoint, client_cert_source
325+
259326
def __init__(
260327
self,
261328
*,
@@ -306,57 +373,22 @@ def __init__(
306373
if client_options is None:
307374
client_options = client_options_lib.ClientOptions()
308375

309-
# Create SSL credentials for mutual TLS if needed.
310-
if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in (
311-
"true",
312-
"false",
313-
):
314-
raise ValueError(
315-
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
316-
)
317-
use_client_cert = (
318-
os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true"
376+
api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
377+
client_options
319378
)
320379

321-
client_cert_source_func = None
322-
is_mtls = False
323-
if use_client_cert:
324-
if client_options.client_cert_source:
325-
is_mtls = True
326-
client_cert_source_func = client_options.client_cert_source
327-
else:
328-
is_mtls = mtls.has_default_client_cert_source()
329-
if is_mtls:
330-
client_cert_source_func = mtls.default_client_cert_source()
331-
else:
332-
client_cert_source_func = None
333-
334-
# Figure out which api endpoint to use.
335-
if client_options.api_endpoint is not None:
336-
api_endpoint = client_options.api_endpoint
337-
else:
338-
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
339-
if use_mtls_env == "never":
340-
api_endpoint = self.DEFAULT_ENDPOINT
341-
elif use_mtls_env == "always":
342-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
343-
elif use_mtls_env == "auto":
344-
if is_mtls:
345-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
346-
else:
347-
api_endpoint = self.DEFAULT_ENDPOINT
348-
else:
349-
raise MutualTLSChannelError(
350-
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
351-
"values: never, auto, always"
352-
)
380+
api_key_value = getattr(client_options, "api_key", None)
381+
if api_key_value and credentials:
382+
raise ValueError(
383+
"client_options.api_key and credentials are mutually exclusive"
384+
)
353385

354386
# Save or instantiate the transport.
355387
# Ordinarily, we provide the transport, but allowing a custom transport
356388
# instance provides an extensibility point for unusual situations.
357389
if isinstance(transport, CloudMemcacheTransport):
358390
# transport is a CloudMemcacheTransport instance.
359-
if credentials or client_options.credentials_file:
391+
if credentials or client_options.credentials_file or api_key_value:
360392
raise ValueError(
361393
"When providing a transport instance, "
362394
"provide its credentials directly."
@@ -368,6 +400,15 @@ def __init__(
368400
)
369401
self._transport = transport
370402
else:
403+
import google.auth._default # type: ignore
404+
405+
if api_key_value and hasattr(
406+
google.auth._default, "get_api_key_credentials"
407+
):
408+
credentials = google.auth._default.get_api_key_credentials(
409+
api_key_value
410+
)
411+
371412
Transport = type(self).get_transport_class(transport)
372413
self._transport = Transport(
373414
credentials=credentials,

google/cloud/memcache_v1beta2/services/cloud_memcache/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
@@ -130,6 +130,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
130130

131131
from_service_account_json = from_service_account_file
132132

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

0 commit comments

Comments
 (0)