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

Commit 72925ba

Browse files
feat: add api key support (#125)
* 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 db4eabc commit 72925ba

File tree

9 files changed

+754
-132
lines changed

9 files changed

+754
-132
lines changed

google/cloud/notebooks_v1/services/managed_notebook_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
@@ -115,6 +115,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
115115

116116
from_service_account_json = from_service_account_file
117117

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

google/cloud/notebooks_v1/services/managed_notebook_service/client.py

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

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

296-
# Create SSL credentials for mutual TLS if needed.
297-
if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in (
298-
"true",
299-
"false",
300-
):
301-
raise ValueError(
302-
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
303-
)
304-
use_client_cert = (
305-
os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true"
363+
api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
364+
client_options
306365
)
307366

308-
client_cert_source_func = None
309-
is_mtls = False
310-
if use_client_cert:
311-
if client_options.client_cert_source:
312-
is_mtls = True
313-
client_cert_source_func = client_options.client_cert_source
314-
else:
315-
is_mtls = mtls.has_default_client_cert_source()
316-
if is_mtls:
317-
client_cert_source_func = mtls.default_client_cert_source()
318-
else:
319-
client_cert_source_func = None
320-
321-
# Figure out which api endpoint to use.
322-
if client_options.api_endpoint is not None:
323-
api_endpoint = client_options.api_endpoint
324-
else:
325-
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
326-
if use_mtls_env == "never":
327-
api_endpoint = self.DEFAULT_ENDPOINT
328-
elif use_mtls_env == "always":
329-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
330-
elif use_mtls_env == "auto":
331-
if is_mtls:
332-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
333-
else:
334-
api_endpoint = self.DEFAULT_ENDPOINT
335-
else:
336-
raise MutualTLSChannelError(
337-
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
338-
"values: never, auto, always"
339-
)
367+
api_key_value = getattr(client_options, "api_key", None)
368+
if api_key_value and credentials:
369+
raise ValueError(
370+
"client_options.api_key and credentials are mutually exclusive"
371+
)
340372

341373
# Save or instantiate the transport.
342374
# Ordinarily, we provide the transport, but allowing a custom transport
343375
# instance provides an extensibility point for unusual situations.
344376
if isinstance(transport, ManagedNotebookServiceTransport):
345377
# transport is a ManagedNotebookServiceTransport instance.
346-
if credentials or client_options.credentials_file:
378+
if credentials or client_options.credentials_file or api_key_value:
347379
raise ValueError(
348380
"When providing a transport instance, "
349381
"provide its credentials directly."
@@ -355,6 +387,15 @@ def __init__(
355387
)
356388
self._transport = transport
357389
else:
390+
import google.auth._default # type: ignore
391+
392+
if api_key_value and hasattr(
393+
google.auth._default, "get_api_key_credentials"
394+
):
395+
credentials = google.auth._default.get_api_key_credentials(
396+
api_key_value
397+
)
398+
358399
Transport = type(self).get_transport_class(transport)
359400
self._transport = Transport(
360401
credentials=credentials,

google/cloud/notebooks_v1/services/notebook_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
@@ -124,6 +124,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
124124

125125
from_service_account_json = from_service_account_file
126126

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

0 commit comments

Comments
 (0)