Skip to content

Commit f7fe0fb

Browse files
feat: add api key support (#270)
* chore: upgrade gapic-generator-java, gax-java and gapic-generator-python PiperOrigin-RevId: 423842556 Source-Link: googleapis/googleapis@a616ca0 Source-Link: googleapis/googleapis-gen@29b938c 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 94aefee commit f7fe0fb

File tree

21 files changed

+1763
-308
lines changed

21 files changed

+1763
-308
lines changed

packages/google-cloud-monitoring/google/cloud/monitoring_v3/services/alert_policy_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
@@ -128,6 +128,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
128128

129129
from_service_account_json = from_service_account_file
130130

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

packages/google-cloud-monitoring/google/cloud/monitoring_v3/services/alert_policy_service/client.py

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

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

320-
# Create SSL credentials for mutual TLS if needed.
321-
if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in (
322-
"true",
323-
"false",
324-
):
325-
raise ValueError(
326-
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
327-
)
328-
use_client_cert = (
329-
os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true"
387+
api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
388+
client_options
330389
)
331390

332-
client_cert_source_func = None
333-
is_mtls = False
334-
if use_client_cert:
335-
if client_options.client_cert_source:
336-
is_mtls = True
337-
client_cert_source_func = client_options.client_cert_source
338-
else:
339-
is_mtls = mtls.has_default_client_cert_source()
340-
if is_mtls:
341-
client_cert_source_func = mtls.default_client_cert_source()
342-
else:
343-
client_cert_source_func = None
344-
345-
# Figure out which api endpoint to use.
346-
if client_options.api_endpoint is not None:
347-
api_endpoint = client_options.api_endpoint
348-
else:
349-
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
350-
if use_mtls_env == "never":
351-
api_endpoint = self.DEFAULT_ENDPOINT
352-
elif use_mtls_env == "always":
353-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
354-
elif use_mtls_env == "auto":
355-
if is_mtls:
356-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
357-
else:
358-
api_endpoint = self.DEFAULT_ENDPOINT
359-
else:
360-
raise MutualTLSChannelError(
361-
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
362-
"values: never, auto, always"
363-
)
391+
api_key_value = getattr(client_options, "api_key", None)
392+
if api_key_value and credentials:
393+
raise ValueError(
394+
"client_options.api_key and credentials are mutually exclusive"
395+
)
364396

365397
# Save or instantiate the transport.
366398
# Ordinarily, we provide the transport, but allowing a custom transport
367399
# instance provides an extensibility point for unusual situations.
368400
if isinstance(transport, AlertPolicyServiceTransport):
369401
# transport is a AlertPolicyServiceTransport instance.
370-
if credentials or client_options.credentials_file:
402+
if credentials or client_options.credentials_file or api_key_value:
371403
raise ValueError(
372404
"When providing a transport instance, "
373405
"provide its credentials directly."
@@ -379,6 +411,15 @@ def __init__(
379411
)
380412
self._transport = transport
381413
else:
414+
import google.auth._default # type: ignore
415+
416+
if api_key_value and hasattr(
417+
google.auth._default, "get_api_key_credentials"
418+
):
419+
credentials = google.auth._default.get_api_key_credentials(
420+
api_key_value
421+
)
422+
382423
Transport = type(self).get_transport_class(transport)
383424
self._transport = Transport(
384425
credentials=credentials,

packages/google-cloud-monitoring/google/cloud/monitoring_v3/services/group_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
@@ -117,6 +117,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
117117

118118
from_service_account_json = from_service_account_file
119119

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

0 commit comments

Comments
 (0)