diff --git a/ChangeLog b/ChangeLog index 8733cf717..5c277801f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,12 @@ +* 29.2.0 +- Google Ads API v23_1 release. +- Update Google Ads API v20, v21, and v22 to include EU political advertising changes. +- Add upload_video example. +- Add text guidelines to performance max example. + +* 29.1.0 +- Add configurable metadata header for ads api assistant. + * 29.1.0 - Add configurable metadata header for ads api assistant. diff --git a/examples/advanced_operations/add_performance_max_campaign.py b/examples/advanced_operations/add_performance_max_campaign.py index 8753ce203..3bf6fde72 100644 --- a/examples/advanced_operations/add_performance_max_campaign.py +++ b/examples/advanced_operations/add_performance_max_campaign.py @@ -27,7 +27,6 @@ shopping_ads/add_performance_max_retail_campaign.py """ - import argparse from datetime import datetime, timedelta import sys @@ -83,7 +82,6 @@ MutateOperationResponse, ) - # We specify temporary IDs that are specific to a single mutate request. # Temporary IDs are always negative and unique within one mutate request. # @@ -318,8 +316,24 @@ def create_performance_max_campaign_operation( ) # Optional fields - campaign.start_date_time = (datetime.now() + timedelta(1)).strftime("%Y%m%d 00:00:00") - campaign.end_date_time = (datetime.now() + timedelta(365)).strftime("%Y%m%d 23:59:59") + campaign.start_date_time = (datetime.now() + timedelta(1)).strftime( + "%Y%m%d 00:00:00" + ) + campaign.end_date_time = (datetime.now() + timedelta(365)).strftime( + "%Y%m%d 23:59:59" + ) + + # [START add_performance_max_text_guidelines] + campaign.text_guidelines.term_exclusions = ["cheap", "free"] + messaging_restriction = campaign.MessagingRestriction() + messaging_restriction.restriction_text = "Don't mention competitor names" + messaging_restriction.restriction_type = ( + client.enums.MessagingRestrictionTypeEnum.RESTRICTION_BASED_EXCLUSION + ) + campaign.text_guidelines.messaging_restrictions.append( + messaging_restriction + ) + # [END add_performance_max_text_guidelines] # [START add_pmax_asset_automation_settings] # Configures the optional opt-in/out status for asset automation settings. @@ -328,11 +342,17 @@ def create_performance_max_campaign_operation( client.enums.AssetAutomationTypeEnum.FINAL_URL_EXPANSION_TEXT_ASSET_AUTOMATION, client.enums.AssetAutomationTypeEnum.TEXT_ASSET_AUTOMATION, client.enums.AssetAutomationTypeEnum.GENERATE_ENHANCED_YOUTUBE_VIDEOS, - client.enums.AssetAutomationTypeEnum.GENERATE_IMAGE_ENHANCEMENT + client.enums.AssetAutomationTypeEnum.GENERATE_IMAGE_ENHANCEMENT, ]: - asset_automattion_setting: Campaign.AssetAutomationSetting = client.get_type("Campaign").AssetAutomationSetting() - asset_automattion_setting.asset_automation_type = asset_automation_type_enum - asset_automattion_setting.asset_automation_status = client.enums.AssetAutomationStatusEnum.OPTED_IN + asset_automattion_setting: Campaign.AssetAutomationSetting = ( + client.get_type("Campaign").AssetAutomationSetting() + ) + asset_automattion_setting.asset_automation_type = ( + asset_automation_type_enum + ) + asset_automattion_setting.asset_automation_status = ( + client.enums.AssetAutomationStatusEnum.OPTED_IN + ) campaign.asset_automation_settings.append(asset_automattion_setting) # [END add_pmax_asset_automation_settings] @@ -712,6 +732,7 @@ def create_and_link_image_asset( return operations # [END add_performance_max_campaign_8] + # [START create_and_link_brand_assets] def create_and_link_brand_assets( client: GoogleAdsClient, diff --git a/examples/advanced_operations/upload_video.py b/examples/advanced_operations/upload_video.py new file mode 100644 index 000000000..02ea87391 --- /dev/null +++ b/examples/advanced_operations/upload_video.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python +# Copyright 2026s Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""This example illustrates how to upload videos to YouTube.""" + +import argparse +import itertools +import os +import sys +import logging +from typing import Iterator, Iterable, List, MutableSequence + +import google.auth +from google.auth.credentials import Credentials +from google.auth import impersonated_credentials + +from google.ads.googleads.client import GoogleAdsClient +from google.ads.googleads.errors import GoogleAdsException +from google.ads.googleads.v23.services.services.google_ads_service import ( + GoogleAdsServiceClient, +) +from google.ads.googleads.v23.services.types.google_ads_service import ( + SearchGoogleAdsStreamResponse, + GoogleAdsRow, +) + +from google.ads.googleads.v23.services.services.you_tube_video_upload_service.client import ( + YouTubeVideoUploadServiceClient, +) +from google.ads.googleads.v23.services.types import youtube_video_upload_service +from google.ads.googleads.v23.services.types.youtube_video_upload_service import ( + CreateYouTubeVideoUploadRequest, + CreateYouTubeVideoUploadResponse, + UpdateYouTubeVideoUploadRequest, + UpdateYouTubeVideoUploadResponse, + RemoveYouTubeVideoUploadRequest, + RemoveYouTubeVideoUploadResponse, +) + +from google.protobuf import field_mask_pb2 +from google.ads.googleads.v23.resources.types import youtube_video_upload + + +def main(client: GoogleAdsClient, customer_id: str, video_file_path: str) -> None: + """The main method that uploads a video and retrieves its state. + + Args: + client: an initialized GoogleAdsClient instance. + customer_id: a client customer ID. + video_file_path: the absolute path to a video file on your machine. + """ + + # [START upload_video_1] + yt_service: YouTubeVideoUploadServiceClient = client.get_service( + "YouTubeVideoUploadService" + ) + + create_upload_request: CreateYouTubeVideoUploadRequest = ( + youtube_video_upload_service.CreateYouTubeVideoUploadRequest() + ) + create_upload_request.customer_id = customer_id + create_upload_request.you_tube_video_upload.video_title = "Test Video" + create_upload_request.you_tube_video_upload.video_description = ( + "Test Video Description" + ) + create_upload_request.you_tube_video_upload.video_privacy = ( + client.enums.YouTubeVideoPrivacyEnum.UNLISTED + ) + + video_upload_resource_name: str + with open(video_file_path, "rb") as stream: + response: CreateYouTubeVideoUploadResponse = ( + yt_service.create_you_tube_video_upload( + stream=stream, + request=create_upload_request, + retry=None, + ) + ) + print(f"Created YouTube video upload: {response.resource_name}") + # [END upload_video_1] + + # [START upload_video_3] + # Retrieve the metadata of the newly uploaded video. + query: str = f""" + SELECT + you_tube_video_upload.resource_name, + you_tube_video_upload.video_id, + you_tube_video_upload.state + FROM you_tube_video_upload + WHERE you_tube_video_upload.resource_name = '{video_upload_resource_name}'""" + + ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService") + stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream( + customer_id=customer_id, query=query + ) + + for row in itertools.chain.from_iterable(batch.results for batch in stream): + video = row.you_tube_video_upload + print( + f"Video with ID {row.you_tube_video_upload.video_id} was found in state {row.you_tube_video_upload.state}." + ) + # [END upload_video_3] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Lists all campaigns for specified customer." + ) + # The following argument(s) should be provided to run the example. + parser.add_argument( + "-c", + "--customer_id", + type=str, + required=True, + help="The Google Ads customer ID.", + ) + parser.add_argument( + "-v", + "--video_file_path", + type=str, + required=True, + help="The path to a video file to upload to YouTube.", + ) + args: argparse.Namespace = parser.parse_args() + + # GoogleAdsClient will read the google-ads.yaml configuration file in the + # home directory if none is specified. + googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(version="v23") + try: + main( + googleads_client, + customer_id=args.customer_id, + video_file_path=args.video_file_path, + ) + except GoogleAdsException as ex: + print( + f'Request with ID "{ex.request_id}" failed with status ' + f'"{ex.error.code().name}" and includes the following errors:' + ) + if hasattr(ex.error, "_response"): + raw_res = getattr(ex.error, "_response") + print(f"\n--- Full Response (Reflected from Proxy) ---") + print(f"Status Code: {raw_res.status_code}") + print(f"Headers: {raw_res.headers}") + print(f"Body: {raw_res.text}") + print(f"-------------------------------------------\n") + + for error in ex.failure.errors: + print(f'\tError with message "{error.message}".') + if hasattr(error, "location") and error.location: + for field_path_element in error.location.field_path_elements: + print(f"\t\tOn field: {field_path_element.field_name}") + sys.exit(1) diff --git a/google/ads/googleads/__init__.py b/google/ads/googleads/__init__.py index 45b8bfa1d..675d2512d 100644 --- a/google/ads/googleads/__init__.py +++ b/google/ads/googleads/__init__.py @@ -19,7 +19,7 @@ import google.ads.googleads.errors import google.ads.googleads.util -VERSION = "29.1.0" +VERSION = "29.2.0" # Checks if the current runtime is Python 3.9. if sys.version_info.major == 3 and sys.version_info.minor <= 9: diff --git a/google/ads/googleads/client.py b/google/ads/googleads/client.py index 18d3a8cf1..0f150fd7d 100644 --- a/google/ads/googleads/client.py +++ b/google/ads/googleads/client.py @@ -476,6 +476,18 @@ def get_service( channel=channel, client_info=_CLIENT_INFO ) + if name == "YouTubeVideoUploadService": + # YouTubeVideoUploadService uses REST, so we cannot pass the credentials inside the gRPC + # channel; we need to pass them explicitly. + return service_client_class( + transport=service_transport, + credentials=self.credentials, + developer_token=self.developer_token, + login_customer_id=self.login_customer_id, + linked_customer_id=self.linked_customer_id, + use_cloud_org_for_api_access=self.use_cloud_org_for_api_access + ) + return service_client_class(transport=service_transport) channel: grpc.Channel = service_transport_class.create_channel( @@ -504,6 +516,18 @@ def get_service( channel=channel, client_info=_CLIENT_INFO ) + if name == "YouTubeVideoUploadService": + # YouTubeVideoUploadService uses REST, so we cannot pass the credentials inside the gRPC + # channel; we need to pass them explicitly. + return service_client_class( + transport=service_transport, + credentials=self.credentials, + developer_token=self.developer_token, + login_customer_id=self.login_customer_id, + linked_customer_id=self.linked_customer_id, + use_cloud_org_for_api_access=self.use_cloud_org_for_api_access + ) + return service_client_class(transport=service_transport) def get_type(self, name: str, version: str = _DEFAULT_VERSION) -> Union[ProtoPlusMessageType, ProtobufMessageType]: diff --git a/google/ads/googleads/v20/__init__.py b/google/ads/googleads/v20/__init__.py index ede107e9a..6289b57a4 100644 --- a/google/ads/googleads/v20/__init__.py +++ b/google/ads/googleads/v20/__init__.py @@ -15,14 +15,117 @@ # from google.ads.googleads.v20 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from . import common from . import enums from . import errors from . import resources from . import services +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v20") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v20") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v20" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( "common", diff --git a/google/ads/googleads/v20/common/__init__.py b/google/ads/googleads/v20/common/__init__.py index 80eeb41cc..aa11c1634 100644 --- a/google/ads/googleads/v20/common/__init__.py +++ b/google/ads/googleads/v20/common/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v20 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.ad_asset import AdAppDeepLinkAsset from .types.ad_asset import AdCallToActionAsset @@ -333,6 +343,100 @@ from .types.user_lists import UserListStringRuleItemInfo from .types.value import Value +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v20") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v20") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v20" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "ActivityCityInfo", "ActivityCountryInfo", diff --git a/google/ads/googleads/v20/common/types/additional_application_info.py b/google/ads/googleads/v20/common/types/additional_application_info.py index 860fdc758..6e1c60438 100644 --- a/google/ads/googleads/v20/common/types/additional_application_info.py +++ b/google/ads/googleads/v20/common/types/additional_application_info.py @@ -22,7 +22,6 @@ application_instance as gage_application_instance, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.common", marshal="google.ads.googleads.v20", @@ -34,8 +33,12 @@ class AdditionalApplicationInfo(proto.Message): r"""Additional information about the application/tool issuing the - request. This field is only used by [ContentCreatorInsightsService], - [AudienceInsightsService], and [ReachPlanService] APIs. + request. This field is only used by + [ContentCreatorInsightsService][google.ads.googleads.v20.services.ContentCreatorInsightsService], + [AudienceInsightsService][google.ads.googleads.v20.services.AudienceInsightsService], + and + [ReachPlanService][google.ads.googleads.v20.services.ReachPlanService] + APIs. Attributes: application_id (str): diff --git a/google/ads/googleads/v20/common/types/asset_types.py b/google/ads/googleads/v20/common/types/asset_types.py index 23c289da4..a65f54a24 100644 --- a/google/ads/googleads/v20/common/types/asset_types.py +++ b/google/ads/googleads/v20/common/types/asset_types.py @@ -50,7 +50,6 @@ ) from google.ads.googleads.v20.enums.types import promotion_extension_occasion - __protobuf__ = proto.module( package="google.ads.googleads.v20.common", marshal="google.ads.googleads.v20", @@ -1700,7 +1699,7 @@ class DynamicFlightsAsset(proto.Message): PAR,LON. custom_mapping (str): A custom field which can be multiple key to values mapping - separated by delimiters (",", "|" and ":"), in the forms of + separated by delimiters (",", "\|" and ":"), in the forms of ": , , ... , \| : , ... , \| ... \| : , ... ," for example, wifi: most \| aircraft: 320, 77W \| diff --git a/google/ads/googleads/v20/common/types/audience_insights_attribute.py b/google/ads/googleads/v20/common/types/audience_insights_attribute.py index 1ef40b5e7..8e227b9a9 100644 --- a/google/ads/googleads/v20/common/types/audience_insights_attribute.py +++ b/google/ads/googleads/v20/common/types/audience_insights_attribute.py @@ -25,7 +25,6 @@ insights_knowledge_graph_entity_capabilities, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.common", marshal="google.ads.googleads.v20", @@ -568,7 +567,7 @@ class KnowledgeGraphAttributeMetadata(proto.Message): Attributes: entity_capabilities (MutableSequence[google.ads.googleads.v20.enums.types.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities]): The capabilities of the entity used in - [ContentCreatorInsightsService][]. + [ContentCreatorInsightsService][google.ads.googleads.v20.services.ContentCreatorInsightsService]. """ entity_capabilities: MutableSequence[ diff --git a/google/ads/googleads/v20/common/types/criteria.py b/google/ads/googleads/v20/common/types/criteria.py index b0459af29..779a183af 100644 --- a/google/ads/googleads/v20/common/types/criteria.py +++ b/google/ads/googleads/v20/common/types/criteria.py @@ -51,7 +51,6 @@ from google.ads.googleads.v20.enums.types import webpage_condition_operand from google.ads.googleads.v20.enums.types import webpage_condition_operator - __protobuf__ = proto.module( package="google.ads.googleads.v20.common", marshal="google.ads.googleads.v20", @@ -1644,19 +1643,37 @@ class LanguageInfo(proto.Message): class IpBlockInfo(proto.Message): - r"""An IpBlock criterion used for IP exclusions. We allow: + r"""An IpBlock criterion used for excluding IP addresses. + + We support excluding individual IP addresses or CIDR blocks. Create + one IpBlockInfo criterion for each individual IP address or CIDR + block you want to exclude. You can exclude up to 500 IP addresses + per campaign. For more details, see `Exclude IP + addresses `__. + + IPv4 examples: + + - Individual address: 192.168.0.1 + + - Individual address as CIDR block: 192.168.0.1/32 + + - CIDR block: 192.168.0.0/24 + + IPv6 examples: + + - Individual address: 2001:db8:a0b:12f0::1 + + - Individual address as CIDR block: 2001:db8:a0b:12f0::1/128 - - IPv4 and IPv6 addresses - - individual addresses (192.168.0.1) - - masks for individual addresses (192.168.0.1/32) - - masks for Class C networks (192.168.0.1/24) + - CIDR block: 2001:db8::/48 .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: ip_address (str): - The IP address of this IP block. + The IP address or the CIDR block to be + excluded. This field is a member of `oneof`_ ``_ip_address``. """ diff --git a/google/ads/googleads/v20/common/types/metrics.py b/google/ads/googleads/v20/common/types/metrics.py index 34ae3f37d..0d80f9000 100644 --- a/google/ads/googleads/v20/common/types/metrics.py +++ b/google/ads/googleads/v20/common/types/metrics.py @@ -22,7 +22,6 @@ from google.ads.googleads.v20.enums.types import interaction_event_type from google.ads.googleads.v20.enums.types import quality_score_bucket - __protobuf__ = proto.module( package="google.ads.googleads.v20.common", marshal="google.ads.googleads.v20", @@ -140,18 +139,18 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_value_per_cost``. all_conversions_from_click_to_call (float): The number of times people clicked the "Call" - button to call a store during or after clicking - an ad. This number doesn't include whether or - not calls were connected, or the duration of any - calls. + button to call a business during or after + clicking an ad. This number doesn't include + whether or not calls were connected, or the + duration of any calls. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_click_to_call``. all_conversions_from_directions (float): The number of times people clicked a "Get - directions" button to navigate to a store after - clicking an ad. + directions" button to navigate to a business + after clicking an ad. This metric applies to feed items only. @@ -164,34 +163,36 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_from_interactions_value_per_interaction``. all_conversions_from_menu (float): The number of times people clicked a link to - view a store's menu after clicking an ad. + view a business's menu after clicking an ad. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_menu``. all_conversions_from_order (float): The number of times people placed an order at - a store after clicking an ad. + a business after clicking an ad. + This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_order``. all_conversions_from_other_engagement (float): The number of other conversions (for example, posting a review or saving a location for a - store) that occurred after people clicked an ad. + business) that occurred after people clicked an + ad. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_other_engagement``. all_conversions_from_store_visit (float): Estimated number of times people visited a - store after clicking an ad. + business after clicking an ad. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_store_visit``. all_conversions_from_store_website (float): The number of times that people were taken to - a store's URL after clicking an ad. + a business's URL after clicking an ad. This metric applies to feed items only. @@ -633,8 +634,8 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_gmail_secondary_clicks``. impressions_from_store_reach (int): - The number of times a store's location-based - ad was shown. + The number of times a business's + location-based ad was shown. This metric applies to feed items only. This field is a member of `oneof`_ ``_impressions_from_store_reach``. @@ -1086,10 +1087,10 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_from_location_asset_other_engagement``. all_conversions_from_location_asset_store_visits (float): - Estimated number of visits to the store after - a chargeable ad event (click or impression). - This measure is coming from Asset based - location. + Estimated number of visits to the business + after a chargeable ad event (click or + impression). This measure is coming from Asset + based location. This field is a member of `oneof`_ ``_all_conversions_from_location_asset_store_visits``. all_conversions_from_location_asset_website (float): @@ -1100,7 +1101,7 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_from_location_asset_website``. eligible_impressions_from_location_asset_store_reach (int): - Number of impressions in which the store + Number of impressions in which the business location was shown or the location was used for targeting. This measure is coming from Asset based location. @@ -1138,9 +1139,9 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_view_through_conversions_from_location_asset_other_engagement``. view_through_conversions_from_location_asset_store_visits (float): - Estimated number of visits to the store after - an impression. This measure is coming from Asset - based location. + Estimated number of visits to the business + after an impression. This measure is coming from + Asset based location. This field is a member of `oneof`_ ``_view_through_conversions_from_location_asset_store_visits``. view_through_conversions_from_location_asset_website (float): @@ -1679,8 +1680,8 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_asset_unrated_performance_cost_percentage``. store_visits_last_click_model_attributed_conversions (float): - The amount of store visits attributed by the - last click model. + The amount of business visits attributed by + the last click model. This field is a member of `oneof`_ ``_store_visits_last_click_model_attributed_conversions``. results_conversions_purchase (float): diff --git a/google/ads/googleads/v20/common/types/policy.py b/google/ads/googleads/v20/common/types/policy.py index 775cd7de4..a38e259c5 100644 --- a/google/ads/googleads/v20/common/types/policy.py +++ b/google/ads/googleads/v20/common/types/policy.py @@ -30,7 +30,6 @@ policy_topic_evidence_destination_not_working_dns_error_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.common", marshal="google.ads.googleads.v20", @@ -84,27 +83,32 @@ class PolicyValidationParameter(proto.Message): Attributes: ignorable_policy_topics (MutableSequence[str]): - The list of policy topics that should not - cause a PolicyFindingError to be reported. This - field is currently only compatible with Enhanced - Text Ad. It corresponds to the - PolicyTopicEntry.topic field. - - Resources violating these policies will be - saved, but will not be eligible to serve. They - may begin serving at a later time due to a - change in policies, re-review of the resource, - or a change in advertiser certificates. + The list of policy topics that should not cause a + ``PolicyFindingError`` to be reported. This field is used + for ad policy exemptions. It corresponds to the + ``PolicyTopicEntry.topic`` field. + + If this field is populated, then + ``exempt_policy_violation_keys`` must be empty. + + Resources that violate these policies will be saved, but + will not be eligible to serve. They may begin serving at a + later time due to a change in policies, re-review of the + resource, or a change in advertiser certificates. exempt_policy_violation_keys (MutableSequence[google.ads.googleads.v20.common.types.PolicyViolationKey]): The list of policy violation keys that should not cause a - PolicyViolationError to be reported. Not all policy - violations are exemptable, refer to the is_exemptible field - in the returned PolicyViolationError. - - Resources violating these polices will be saved, but will - not be eligible to serve. They may begin serving at a later - time due to a change in policies, re-review of the resource, - or a change in advertiser certificates. + ``PolicyViolationError`` to be reported. Not all policy + violations are exemptable. Refer to the ``is_exemptible`` + field in the returned ``PolicyViolationError``. This field + is used for keyword policy exemptions. + + If this field is populated, then ``ignorable_policy_topics`` + must be empty. + + Resources that violate these policies will be saved, but + will not be eligible to serve. They may begin serving at a + later time due to a change in policies, re-review of the + resource, or a change in advertiser certificates. """ ignorable_policy_topics: MutableSequence[str] = proto.RepeatedField( diff --git a/google/ads/googleads/v20/common/types/user_lists.py b/google/ads/googleads/v20/common/types/user_lists.py index 7a15b24fc..e8ea59799 100644 --- a/google/ads/googleads/v20/common/types/user_lists.py +++ b/google/ads/googleads/v20/common/types/user_lists.py @@ -38,7 +38,6 @@ user_list_string_rule_item_operator, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.common", marshal="google.ads.googleads.v20", @@ -243,9 +242,9 @@ class UserListRuleItemInfo(proto.Message): letters or underscore or UTF8 code that is greater than 127 and consist of US-ascii letters or digits or underscore or UTF8 code that is greater than 127. For websites, there are - two built-in variable URL (name = 'url__') and referrer URL - (name = 'ref_url__'). This field must be populated when - creating a new rule item. + two built-in variable URL (name = 'url\_\_') and referrer + URL (name = 'ref_url\_\_'). This field must be populated + when creating a new rule item. This field is a member of `oneof`_ ``_name``. number_rule_item (google.ads.googleads.v20.common.types.UserListNumberRuleItemInfo): diff --git a/google/ads/googleads/v20/enums/__init__.py b/google/ads/googleads/v20/enums/__init__.py index 08f12f048..2b5477caf 100644 --- a/google/ads/googleads/v20/enums/__init__.py +++ b/google/ads/googleads/v20/enums/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v20 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.access_invitation_status import AccessInvitationStatusEnum from .types.access_reason import AccessReasonEnum @@ -549,6 +559,100 @@ from .types.webpage_condition_operand import WebpageConditionOperandEnum from .types.webpage_condition_operator import WebpageConditionOperatorEnum +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v20") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v20") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v20" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "AccessInvitationStatusEnum", "AccessReasonEnum", diff --git a/google/ads/googleads/v20/enums/types/ad_type.py b/google/ads/googleads/v20/enums/types/ad_type.py index 88210f6e3..5001cc96a 100644 --- a/google/ads/googleads/v20/enums/types/ad_type.py +++ b/google/ads/googleads/v20/enums/types/ad_type.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.enums", marshal="google.ads.googleads.v20", @@ -74,7 +73,7 @@ class AdType(proto.Enum): product type. DYNAMIC_HTML5_AD (22): The ad is a display upload ad with one of the - DYNAMIC_HTML5_\* product types. + DYNAMIC_HTML5\_\* product types. APP_ENGAGEMENT_AD (23): The ad is an app engagement ad. SHOPPING_COMPARISON_LISTING_AD (24): diff --git a/google/ads/googleads/v20/enums/types/bidding_strategy_system_status.py b/google/ads/googleads/v20/enums/types/bidding_strategy_system_status.py index 676470c38..dfe58205d 100644 --- a/google/ads/googleads/v20/enums/types/bidding_strategy_system_status.py +++ b/google/ads/googleads/v20/enums/types/bidding_strategy_system_status.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.enums", marshal="google.ads.googleads.v20", @@ -117,13 +116,13 @@ class BiddingStrategySystemStatus(proto.Enum): This bid strategy currently does not support status reporting. MULTIPLE_LEARNING (23): - There were multiple LEARNING_\* system statuses for this bid - strategy during the time in question. + There were multiple LEARNING\_\* system statuses for this + bid strategy during the time in question. MULTIPLE_LIMITED (24): - There were multiple LIMITED_\* system statuses for this bid + There were multiple LIMITED\_\* system statuses for this bid strategy during the time in question. MULTIPLE_MISCONFIGURED (25): - There were multiple MISCONFIGURED_\* system statuses for + There were multiple MISCONFIGURED\_\* system statuses for this bid strategy during the time in question. MULTIPLE (26): There were multiple system statuses for this diff --git a/google/ads/googleads/v20/enums/types/insights_knowledge_graph_entity_capabilities.py b/google/ads/googleads/v20/enums/types/insights_knowledge_graph_entity_capabilities.py index 36ef53fb9..d8798b701 100644 --- a/google/ads/googleads/v20/enums/types/insights_knowledge_graph_entity_capabilities.py +++ b/google/ads/googleads/v20/enums/types/insights_knowledge_graph_entity_capabilities.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.enums", marshal="google.ads.googleads.v20", @@ -44,10 +43,10 @@ class InsightsKnowledgeGraphEntityCapabilities(proto.Enum): The value is unknown in this version. CONTENT_TRENDING_INSIGHTS (2): An entity that is supported to use as a trending topic in - [ContentCreatorInsightsService.GenerateTrendingInsights]. + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v20.services.ContentCreatorInsightsService.GenerateTrendingInsights]. CREATOR_ATTRIBUTE (3): An entity that is supported to use as a creator attribute in - [ContentCreatorInsightsService.GenerateCreatorInsights]. + [ContentCreatorInsightsService.GenerateCreatorInsights][google.ads.googleads.v20.services.ContentCreatorInsightsService.GenerateCreatorInsights]. """ UNSPECIFIED = 0 diff --git a/google/ads/googleads/v20/enums/types/offline_user_data_job_status.py b/google/ads/googleads/v20/enums/types/offline_user_data_job_status.py index f90dfde25..911e88d98 100644 --- a/google/ads/googleads/v20/enums/types/offline_user_data_job_status.py +++ b/google/ads/googleads/v20/enums/types/offline_user_data_job_status.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.enums", marshal="google.ads.googleads.v20", @@ -51,9 +50,15 @@ class OfflineUserDataJobStatus(proto.Enum): being processed. SUCCESS (4): Uploaded data has been successfully - processed. + processed. The job might have no operations, + which can happen if the job was run without any + operations added, or if all operations failed + validation individually when attempting to add + them to the job. FAILED (5): Uploaded data has failed to be processed. + Some operations may have been successfully + processed. """ UNSPECIFIED = 0 diff --git a/google/ads/googleads/v20/enums/types/served_asset_field_type.py b/google/ads/googleads/v20/enums/types/served_asset_field_type.py index cbc14edae..bee269c6b 100644 --- a/google/ads/googleads/v20/enums/types/served_asset_field_type.py +++ b/google/ads/googleads/v20/enums/types/served_asset_field_type.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.enums", marshal="google.ads.googleads.v20", @@ -64,7 +63,7 @@ class ServedAssetFieldType(proto.Enum): DESCRIPTION (10): The asset was used in a description. Use this only if there is only one description in the ad. Otherwise, use the - DESCRIPTION_1 or DESCRIPTION_@ enums + DESCRIPTION_1 or DESCRIPTION\_@ enums DESCRIPTION_IN_PORTRAIT (11): The asset was used as description in portrait image. diff --git a/google/ads/googleads/v20/errors/__init__.py b/google/ads/googleads/v20/errors/__init__.py index a173b4a6c..1ee2e11c3 100644 --- a/google/ads/googleads/v20/errors/__init__.py +++ b/google/ads/googleads/v20/errors/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v20 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.access_invitation_error import AccessInvitationErrorEnum from .types.account_budget_proposal_error import AccountBudgetProposalErrorEnum @@ -225,6 +235,100 @@ YoutubeVideoRegistrationErrorEnum, ) +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v20") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v20") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v20" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "AccessInvitationErrorEnum", "AccountBudgetProposalErrorEnum", diff --git a/google/ads/googleads/v20/errors/types/date_error.py b/google/ads/googleads/v20/errors/types/date_error.py index cbeebc193..2e82f36c0 100644 --- a/google/ads/googleads/v20/errors/types/date_error.py +++ b/google/ads/googleads/v20/errors/types/date_error.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.errors", marshal="google.ads.googleads.v20", @@ -57,7 +56,7 @@ class DateError(proto.Enum): yyyy-mm-dd hh:mm:ss. INVALID_STRING_DATE_TIME_SECONDS_WITH_OFFSET (12): The string date time's format should be yyyy-mm-dd - hh:mm:ss+|-hh:mm. + hh:mm:ss+\|-hh:mm. EARLIER_THAN_MINIMUM_DATE (7): Date is before allowed minimum. LATER_THAN_MAXIMUM_DATE (8): diff --git a/google/ads/googleads/v20/errors/types/errors.py b/google/ads/googleads/v20/errors/types/errors.py index fbd19e37a..26054c926 100644 --- a/google/ads/googleads/v20/errors/types/errors.py +++ b/google/ads/googleads/v20/errors/types/errors.py @@ -485,8 +485,7 @@ from google.ads.googleads.v20.errors.types import ( youtube_video_registration_error as gage_youtube_video_registration_error, ) -from google.protobuf import duration_pb2 # type: ignore - +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.errors", diff --git a/google/ads/googleads/v20/errors/types/image_error.py b/google/ads/googleads/v20/errors/types/image_error.py index edb0511da..ae38b44bc 100644 --- a/google/ads/googleads/v20/errors/types/image_error.py +++ b/google/ads/googleads/v20/errors/types/image_error.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.errors", marshal="google.ads.googleads.v20", @@ -86,9 +85,9 @@ class ImageError(proto.Enum): FLASH_HAS_RANDOM_NUM (23): Flash cannot have a random number. FLASH_SELF_TARGETS (24): - Ad click target cannot be '_self'. + Ad click target cannot be '\_self'. FLASH_BAD_GETURL_TARGET (25): - GetUrl method should only use '_blank'. + GetUrl method should only use '\_blank'. FLASH_VERSION_NOT_SUPPORTED (26): Flash version is not supported. FLASH_WITHOUT_HARD_CODED_CLICK_URL (27): diff --git a/google/ads/googleads/v20/errors/types/mutate_error.py b/google/ads/googleads/v20/errors/types/mutate_error.py index 24265cff0..d4be865a6 100644 --- a/google/ads/googleads/v20/errors/types/mutate_error.py +++ b/google/ads/googleads/v20/errors/types/mutate_error.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.errors", marshal="google.ads.googleads.v20", @@ -62,6 +61,10 @@ class MutateError(proto.Enum): This operation cannot be used with "partial_failure". RESOURCE_READ_ONLY (13): Attempt to write to read-only fields. + EU_POLITICAL_ADVERTISING_DECLARATION_REQUIRED (17): + Mutates are generally not allowed if the + customer contains non-exempt campaigns without + the EU political advertising declaration. """ UNSPECIFIED = 0 @@ -75,6 +78,7 @@ class MutateError(proto.Enum): RESOURCE_DOES_NOT_SUPPORT_VALIDATE_ONLY = 12 OPERATION_DOES_NOT_SUPPORT_PARTIAL_FAILURE = 16 RESOURCE_READ_ONLY = 13 + EU_POLITICAL_ADVERTISING_DECLARATION_REQUIRED = 17 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v20/resources/__init__.py b/google/ads/googleads/v20/resources/__init__.py index 1a6f65ac4..bcd19aefc 100644 --- a/google/ads/googleads/v20/resources/__init__.py +++ b/google/ads/googleads/v20/resources/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v20 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.accessible_bidding_strategy import AccessibleBiddingStrategy from .types.account_budget import AccountBudget @@ -295,6 +305,100 @@ from .types.video import Video from .types.webpage_view import WebpageView +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v20") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v20") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v20" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "AccessibleBiddingStrategy", "AccountBudget", diff --git a/google/ads/googleads/v20/resources/types/account_budget.py b/google/ads/googleads/v20/resources/types/account_budget.py index 04f17f4cd..ef25de604 100644 --- a/google/ads/googleads/v20/resources/types/account_budget.py +++ b/google/ads/googleads/v20/resources/types/account_budget.py @@ -25,7 +25,6 @@ ) from google.ads.googleads.v20.enums.types import time_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -41,11 +40,11 @@ class AccountBudget(proto.Message): and proposed changes that are pending approval. The proposed changes that are pending approval, if any, are found in 'pending_proposal'. Effective details about the budget are found in fields prefixed - 'approved_', 'adjusted_' and those without a prefix. Since some + 'approved\_', 'adjusted\_' and those without a prefix. Since some effective details may differ from what the user had originally requested (for example, spending limit), these differences are - juxtaposed through 'proposed_', 'approved_', and possibly - 'adjusted_' fields. + juxtaposed through 'proposed\_', 'approved\_', and possibly + 'adjusted\_' fields. This resource is mutated using AccountBudgetProposal and cannot be mutated directly. A budget may have at most one pending proposal at diff --git a/google/ads/googleads/v20/resources/types/ad_group.py b/google/ads/googleads/v20/resources/types/ad_group.py index b0ec49000..a6ee6eb3a 100644 --- a/google/ads/googleads/v20/resources/types/ad_group.py +++ b/google/ads/googleads/v20/resources/types/ad_group.py @@ -35,7 +35,6 @@ from google.ads.googleads.v20.enums.types import demand_gen_channel_strategy from google.ads.googleads.v20.enums.types import targeting_dimension - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -109,7 +108,12 @@ class AdGroup(proto.Message): This field is a member of `oneof`_ ``_campaign``. cpc_bid_micros (int): - The maximum CPC (cost-per-click) bid. + The maximum CPC (cost-per-click) bid. This + field is used when the ad group's effective + bidding strategy is Manual CPC. This field is + not applicable and will be ignored if the ad + group's campaign is using a portfolio bidding + strategy. This field is a member of `oneof`_ ``_cpc_bid_micros``. effective_cpc_bid_micros (int): @@ -145,12 +149,24 @@ class AdGroup(proto.Message): This field is a member of `oneof`_ ``_target_cpm_micros``. target_roas (float): - The target ROAS (return-on-ad-spend) override. If the ad - group's campaign bidding strategy is TargetRoas or - MaximizeConversionValue (with its target_roas field set), - then this field overrides the target ROAS specified in the - campaign's bidding strategy. Otherwise, this value is - ignored. + The target ROAS (return-on-ad-spend) for this ad group. + + This field lets you override the target ROAS specified in + the campaign's bidding strategy, but only if the campaign is + using a standard (not portfolio) ``TargetRoas`` strategy or + a standard ``MaximizeConversionValue`` strategy with its + ``target_roas`` field set. + + If the campaign is using a portfolio bidding strategy, this + field cannot be set and attempting to do so will result in + an error. + + For any other bidding strategies, this value is ignored. + + To see the actual target ROAS being used by the ad group, + considering potential overrides, query the + ``effective_target_roas`` and + ``effective_target_roas_source`` fields. This field is a member of `oneof`_ ``_target_roas``. percent_cpc_bid_micros (int): @@ -182,7 +198,7 @@ class AdGroup(proto.Message): optimized_targeting_enabled is false, this field is ignored. Default is false. display_custom_bid_dimension (google.ads.googleads.v20.enums.types.TargetingDimensionEnum.TargetingDimension): - Allows advertisers to specify a targeting + Lets advertisers specify a targeting dimension on which to place absolute bids. This is only applicable for campaigns that target only the display network and not search. diff --git a/google/ads/googleads/v20/resources/types/ad_group_ad_asset_view.py b/google/ads/googleads/v20/resources/types/ad_group_ad_asset_view.py index 34efed366..bf60451db 100644 --- a/google/ads/googleads/v20/resources/types/ad_group_ad_asset_view.py +++ b/google/ads/googleads/v20/resources/types/ad_group_ad_asset_view.py @@ -27,7 +27,6 @@ from google.ads.googleads.v20.enums.types import policy_review_status from google.ads.googleads.v20.enums.types import served_asset_field_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -39,9 +38,17 @@ class AdGroupAdAssetView(proto.Message): - r"""A link between an AdGroupAd and an Asset. AdGroupAdAssetView - supports AppAds, Demand Gen campaigns, and Responsive Search - Ads. + r"""Represents a link between an AdGroupAd and an Asset. This view + provides insights into the performance of assets within specific + ads. + + AdGroupAdAssetView supports the following ad types: + + - App Ads + - Demand Gen campaigns + - Responsive Search Ads + + It does not support Responsive Display Ads. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v20/resources/types/ad_group_bid_modifier.py b/google/ads/googleads/v20/resources/types/ad_group_bid_modifier.py index 6d0b89454..473db9bf1 100644 --- a/google/ads/googleads/v20/resources/types/ad_group_bid_modifier.py +++ b/google/ads/googleads/v20/resources/types/ad_group_bid_modifier.py @@ -23,7 +23,6 @@ bid_modifier_source as gage_bid_modifier_source, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -63,9 +62,7 @@ class AdGroupBidModifier(proto.Message): bid_modifier (float): The modifier for the bid when the criterion matches. The modifier must be in the range: 0.1 - - 10.0. The range is 1.0 - 6.0 for - PreferredContent. Use 0 to opt out of a Device - type. + - 10.0. Use 0 to opt out of a Device type. This field is a member of `oneof`_ ``_bid_modifier``. base_ad_group (str): diff --git a/google/ads/googleads/v20/resources/types/ad_group_simulation.py b/google/ads/googleads/v20/resources/types/ad_group_simulation.py index f1f8553fc..f96827401 100644 --- a/google/ads/googleads/v20/resources/types/ad_group_simulation.py +++ b/google/ads/googleads/v20/resources/types/ad_group_simulation.py @@ -22,7 +22,6 @@ from google.ads.googleads.v20.enums.types import simulation_modification_method from google.ads.googleads.v20.enums.types import simulation_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -38,11 +37,17 @@ class AdGroupSimulation(proto.Message): detailed below respectively. 1. SEARCH - CPC_BID - DEFAULT + 2. SEARCH - CPC_BID - UNIFORM + 3. SEARCH - TARGET_CPA - UNIFORM + 4. SEARCH - TARGET_ROAS - UNIFORM + 5. DISPLAY - CPC_BID - DEFAULT + 6. DISPLAY - CPC_BID - UNIFORM + 7. DISPLAY - TARGET_CPA - UNIFORM This message has `oneof`_ fields (mutually exclusive fields). diff --git a/google/ads/googleads/v20/resources/types/asset_set.py b/google/ads/googleads/v20/resources/types/asset_set.py index 67b109497..c77725425 100644 --- a/google/ads/googleads/v20/resources/types/asset_set.py +++ b/google/ads/googleads/v20/resources/types/asset_set.py @@ -22,7 +22,6 @@ from google.ads.googleads.v20.enums.types import asset_set_status from google.ads.googleads.v20.enums.types import asset_set_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -65,13 +64,13 @@ class AssetSet(proto.Message): Merchant ID and Feed Label from Google Merchant Center. location_group_parent_asset_set_id (int): - Immutable. Parent asset set id for the asset + Immutable. Parent asset set ID for the asset set where the elements of this asset set come from. For example: the sync level location - AssetSet id where the the elements in - LocationGroup AssetSet come from. This field is - required and only applicable for Location Group - typed AssetSet. + AssetSet id where the elements in LocationGroup + AssetSet come from. This field is required and + only applicable for Location Group typed + AssetSet. hotel_property_data (google.ads.googleads.v20.resources.types.AssetSet.HotelPropertyData): Output only. For Performance Max for travel goals campaigns with a Hotel Center account diff --git a/google/ads/googleads/v20/resources/types/campaign.py b/google/ads/googleads/v20/resources/types/campaign.py index 0239f9ca1..679ec5ef4 100644 --- a/google/ads/googleads/v20/resources/types/campaign.py +++ b/google/ads/googleads/v20/resources/types/campaign.py @@ -90,7 +90,6 @@ ) from google.ads.googleads.v20.enums.types import video_ad_format_restriction - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -423,6 +422,15 @@ class Campaign(proto.Message): The advertiser should self-declare whether this campaign contains political advertising content targeted towards the European Union. + missing_eu_political_advertising_declaration (bool): + Output only. Indicates whether this campaign is missing a + declaration about whether it contains political advertising + targeted towards the EU and is ineligible for any + exemptions. If this field is true, use the + contains_eu_political_advertising field to add the required + declaration. + + This field is read-only. bidding_strategy (str): The resource name of the portfolio bidding strategy used by the campaign. @@ -691,11 +699,15 @@ class ShoppingSetting(proto.Message): This field is a member of `oneof`_ ``_merchant_id``. feed_label (str): - Feed label of products to include in the campaign. Only one - of feed_label or sales_country can be set. If used instead - of sales_country, the feed_label field accepts country codes - in the same format for example: 'XX'. Otherwise can be any - string used for feed label in Google Merchant Center. + Feed label of products to include in the campaign. Valid + feed labels may contain a maximum of 20 characters including + uppercase letters, numbers, hyphens, and underscores. If you + previously used the deprecated ``sales_country`` in the + two-letter country code (``XX``) format, the ``feed_label`` + field should be used instead. For more information see the + `feed + label `__ + support article. campaign_priority (int): Priority of the campaign. Campaigns with numerically higher priorities take precedence @@ -1620,6 +1632,10 @@ class BrandGuidelines(proto.Message): number=102, enum=eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus, ) + missing_eu_political_advertising_declaration: bool = proto.Field( + proto.BOOL, + number=108, + ) bidding_strategy: str = proto.Field( proto.STRING, number=67, diff --git a/google/ads/googleads/v20/resources/types/campaign_budget.py b/google/ads/googleads/v20/resources/types/campaign_budget.py index 8d045ff15..50d3f310c 100644 --- a/google/ads/googleads/v20/resources/types/campaign_budget.py +++ b/google/ads/googleads/v20/resources/types/campaign_budget.py @@ -23,7 +23,6 @@ from google.ads.googleads.v20.enums.types import budget_status from google.ads.googleads.v20.enums.types import budget_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -70,18 +69,32 @@ class CampaignBudget(proto.Message): This field is a member of `oneof`_ ``_name``. amount_micros (int): - The amount of the budget, in the local - currency for the account. Amount is specified in - micros, where one million is equivalent to one - currency unit. Monthly spend is capped at 30.4 - times this amount. + The average daily amount to be spent by the campaign. This + field is used when the CampaignBudget ``period`` is set to + ``DAILY``, which is the default. + + Amount is specified in micros in the account's local + currency. One million micros is equivalent to one currency + unit. The effective monthly spend is capped at 30.4 times + this daily amount. + + This field is mutually exclusive with 'total_amount_micros'. + Only one of 'amount_micros' or 'total_amount_micros' should + be set. This field is a member of `oneof`_ ``_amount_micros``. total_amount_micros (int): - The lifetime amount of the budget, in the - local currency for the account. Amount is - specified in micros, where one million is - equivalent to one currency unit. + The total amount to be spent by the campaign over its entire + duration. This field is used *only* when the CampaignBudget + ``period`` is set to ``CUSTOM_PERIOD``. It represents the + budget cap for the campaign's lifetime, rather than a daily + limit. The amount is specified in micros in the account's + local currency. One million micros is equivalent to one + currency unit. + + This field is mutually exclusive with 'amount_micros'. Only + one of 'total_amount_micros' or 'amount_micros' should be + set. This field is a member of `oneof`_ ``_total_amount_micros``. status (google.ads.googleads.v20.enums.types.BudgetStatusEnum.BudgetStatus): diff --git a/google/ads/googleads/v20/resources/types/campaign_criterion.py b/google/ads/googleads/v20/resources/types/campaign_criterion.py index 3c70bdd0d..33a172dba 100644 --- a/google/ads/googleads/v20/resources/types/campaign_criterion.py +++ b/google/ads/googleads/v20/resources/types/campaign_criterion.py @@ -22,7 +22,6 @@ from google.ads.googleads.v20.enums.types import campaign_criterion_status from google.ads.googleads.v20.enums.types import criterion_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -154,6 +153,9 @@ class CampaignCriterion(proto.Message): ip_block (google.ads.googleads.v20.common.types.IpBlockInfo): Immutable. IpBlock. + You can exclude up to 500 IP addresses per + campaign. + This field is a member of `oneof`_ ``criterion``. content_label (google.ads.googleads.v20.common.types.ContentLabelInfo): Immutable. ContentLabel. diff --git a/google/ads/googleads/v20/resources/types/campaign_simulation.py b/google/ads/googleads/v20/resources/types/campaign_simulation.py index c729030b0..64cf86a56 100644 --- a/google/ads/googleads/v20/resources/types/campaign_simulation.py +++ b/google/ads/googleads/v20/resources/types/campaign_simulation.py @@ -22,7 +22,6 @@ from google.ads.googleads.v20.enums.types import simulation_modification_method from google.ads.googleads.v20.enums.types import simulation_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -37,22 +36,22 @@ class CampaignSimulation(proto.Message): type, simulation type and simulation modification method is detailed below respectively. - - SEARCH - CPC_BID - UNIFORM - - SEARCH - CPC_BID - SCALING - - SEARCH - TARGET_CPA - UNIFORM - - SEARCH - TARGET_CPA - SCALING - - SEARCH - TARGET_ROAS - UNIFORM - - SEARCH - TARGET_IMPRESSION_SHARE - UNIFORM - - SEARCH - BUDGET - UNIFORM - - SHOPPING - BUDGET - UNIFORM - - SHOPPING - TARGET_ROAS - UNIFORM - - MULTI_CHANNEL - TARGET_CPA - UNIFORM - - MULTI_CHANNEL - TARGET_ROAS - UNIFORM - - DEMAND_GEN - TARGET_CPA - DEFAULT - - DISPLAY - TARGET_CPA - UNIFORM - - PERFORMANCE_MAX - TARGET_CPA - UNIFORM - - PERFORMANCE_MAX - TARGET_ROAS - UNIFORM - - PERFORMANCE_MAX - BUDGET - UNIFORM + - SEARCH - CPC_BID - UNIFORM + - SEARCH - CPC_BID - SCALING + - SEARCH - TARGET_CPA - UNIFORM + - SEARCH - TARGET_CPA - SCALING + - SEARCH - TARGET_ROAS - UNIFORM + - SEARCH - TARGET_IMPRESSION_SHARE - UNIFORM + - SEARCH - BUDGET - UNIFORM + - SHOPPING - BUDGET - UNIFORM + - SHOPPING - TARGET_ROAS - UNIFORM + - MULTI_CHANNEL - TARGET_CPA - UNIFORM + - MULTI_CHANNEL - TARGET_ROAS - UNIFORM + - DEMAND_GEN - TARGET_CPA - DEFAULT + - DISPLAY - TARGET_CPA - UNIFORM + - PERFORMANCE_MAX - TARGET_CPA - UNIFORM + - PERFORMANCE_MAX - TARGET_ROAS - UNIFORM + - PERFORMANCE_MAX - BUDGET - UNIFORM This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. diff --git a/google/ads/googleads/v20/resources/types/change_event.py b/google/ads/googleads/v20/resources/types/change_event.py index b158ed03e..36d0088f6 100644 --- a/google/ads/googleads/v20/resources/types/change_event.py +++ b/google/ads/googleads/v20/resources/types/change_event.py @@ -58,8 +58,7 @@ from google.ads.googleads.v20.resources.types import ( customer_asset as gagr_customer_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", diff --git a/google/ads/googleads/v20/resources/types/click_view.py b/google/ads/googleads/v20/resources/types/click_view.py index 67149b4b2..3338469ef 100644 --- a/google/ads/googleads/v20/resources/types/click_view.py +++ b/google/ads/googleads/v20/resources/types/click_view.py @@ -21,7 +21,6 @@ from google.ads.googleads.v20.common.types import click_location from google.ads.googleads.v20.common.types import criteria - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -39,6 +38,9 @@ class ClickView(proto.Message): filter limiting the results to one day and can be requested for dates back to 90 days before the time of the request. + GCLIDs are not available in this report for App Campaigns for + Installs (ACi) and App Campaigns for Pre-registration (ACpre). + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v20/resources/types/conversion_value_rule_set.py b/google/ads/googleads/v20/resources/types/conversion_value_rule_set.py index 4cdc4e2a0..0f81f5099 100644 --- a/google/ads/googleads/v20/resources/types/conversion_value_rule_set.py +++ b/google/ads/googleads/v20/resources/types/conversion_value_rule_set.py @@ -26,7 +26,6 @@ from google.ads.googleads.v20.enums.types import value_rule_set_attachment_type from google.ads.googleads.v20.enums.types import value_rule_set_dimension - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -37,7 +36,9 @@ class ConversionValueRuleSet(proto.Message): - r"""A conversion value rule set + r"""A conversion value rule set is a collection of conversion value + rules that lets you adjust conversion values based on the dimensions + specified in the ``dimensions`` field. Attributes: resource_name (str): diff --git a/google/ads/googleads/v20/resources/types/customer.py b/google/ads/googleads/v20/resources/types/customer.py index 99f257c52..7ba674db3 100644 --- a/google/ads/googleads/v20/resources/types/customer.py +++ b/google/ads/googleads/v20/resources/types/customer.py @@ -25,11 +25,11 @@ customer_pay_per_conversion_eligibility_failure_reason, ) from google.ads.googleads.v20.enums.types import customer_status +from google.ads.googleads.v20.enums.types import eu_political_advertising_status from google.ads.googleads.v20.enums.types import ( local_services_verification_status, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -186,6 +186,14 @@ class Customer(proto.Message): type to show your ads on content that is the right fit for your brand. See https://support.google.com/google-ads/answer/7515513. + contains_eu_political_advertising (google.ads.googleads.v20.enums.types.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus): + Output only. Returns the advertiser + self-declaration status of whether this customer + contains political advertising content targeted + towards the European Union. You can use the + Google Ads UI to update this account-level + declaration, or use the API to update the + self-declaration status of individual campaigns. """ resource_name: str = proto.Field( @@ -315,6 +323,13 @@ class Customer(proto.Message): number=46, enum=brand_safety_suitability.BrandSafetySuitabilityEnum.BrandSafetySuitability, ) + contains_eu_political_advertising: ( + eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus + ) = proto.Field( + proto.ENUM, + number=55, + enum=eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus, + ) class CallReportingSetting(proto.Message): diff --git a/google/ads/googleads/v20/resources/types/customer_negative_criterion.py b/google/ads/googleads/v20/resources/types/customer_negative_criterion.py index 219710f11..e9100b74c 100644 --- a/google/ads/googleads/v20/resources/types/customer_negative_criterion.py +++ b/google/ads/googleads/v20/resources/types/customer_negative_criterion.py @@ -21,7 +21,6 @@ from google.ads.googleads.v20.common.types import criteria from google.ads.googleads.v20.enums.types import criterion_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -83,7 +82,10 @@ class CustomerNegativeCriterion(proto.Message): This field is a member of `oneof`_ ``criterion``. ip_block (google.ads.googleads.v20.common.types.IpBlockInfo): - Immutable. IPBLock + Immutable. IpBlock. + + You can exclude up to 500 IP addresses per + account. This field is a member of `oneof`_ ``criterion``. """ diff --git a/google/ads/googleads/v20/resources/types/detail_placement_view.py b/google/ads/googleads/v20/resources/types/detail_placement_view.py index b168fb9d0..90dda0b86 100644 --- a/google/ads/googleads/v20/resources/types/detail_placement_view.py +++ b/google/ads/googleads/v20/resources/types/detail_placement_view.py @@ -22,7 +22,6 @@ placement_type as gage_placement_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -33,8 +32,14 @@ class DetailPlacementView(proto.Message): - r"""A view with metrics aggregated by ad group and URL or YouTube - video. + r"""A view with metrics aggregated by ad group and URL or YouTube video. + + This view primarily surfaces placement data from the Google Display + Network. While you can select segments like + ``segments.ad_network_type``, this view generally does not include + placement data from other networks, such as the Search Partners + network. To understand performance on Search Partners, consider + other reports and segmentations. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v20/resources/types/display_keyword_view.py b/google/ads/googleads/v20/resources/types/display_keyword_view.py index f681c876b..0a143905f 100644 --- a/google/ads/googleads/v20/resources/types/display_keyword_view.py +++ b/google/ads/googleads/v20/resources/types/display_keyword_view.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -31,6 +30,22 @@ class DisplayKeywordView(proto.Message): r"""A display keyword view. + Provides performance data for keywords used in Display Network + campaigns. This view lets you analyze how your display keywords are + performing across various segments. + + This view is primarily used to track the effectiveness of keyword + targeting within your Display campaigns. To understand which network + the metrics apply to, you can select the + ``segments.ad_network_type`` field in your query. This field will + segment the data by networks such as the Google Display Network, + YouTube, Gmail, and so on. + + You can select fields from this resource along with metrics like + impressions, clicks, and conversions to gauge performance. + Attributed resources like ``ad_group`` and ``campaign`` can also be + selected without segmenting metrics. + Attributes: resource_name (str): Output only. The resource name of the display keyword view. diff --git a/google/ads/googleads/v20/resources/types/lead_form_submission_data.py b/google/ads/googleads/v20/resources/types/lead_form_submission_data.py index cced0a637..9a2bb456a 100644 --- a/google/ads/googleads/v20/resources/types/lead_form_submission_data.py +++ b/google/ads/googleads/v20/resources/types/lead_form_submission_data.py @@ -21,7 +21,6 @@ from google.ads.googleads.v20.enums.types import lead_form_field_user_input_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -68,7 +67,7 @@ class LeadFormSubmissionData(proto.Message): the submissed lead form. submission_date_time (str): Output only. The date and time at which the lead form was - submitted. The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for + submitted. The format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". """ diff --git a/google/ads/googleads/v20/resources/types/local_services_lead.py b/google/ads/googleads/v20/resources/types/local_services_lead.py index 19614411d..f04cb907e 100644 --- a/google/ads/googleads/v20/resources/types/local_services_lead.py +++ b/google/ads/googleads/v20/resources/types/local_services_lead.py @@ -24,7 +24,6 @@ from google.ads.googleads.v20.enums.types import local_services_lead_status from google.ads.googleads.v20.enums.types import local_services_lead_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -48,7 +47,7 @@ class LocalServicesLead(proto.Message): Attributes: resource_name (str): - Output only. The resource name of the local services lead + Immutable. The resource name of the local services lead data. Local Services Lead resource name have the form ``customers/{customer_id}/localServicesLead/{local_services_lead_id}`` @@ -168,8 +167,12 @@ class ContactDetails(proto.Message): Attributes: phone_number (str): - Output only. Consumer phone number in E164 - format. + Output only. Phone number of the consumer for + the lead. This can be a real phone number or a + tracking number. The phone number is returned in + E164 format. See + https://support.google.com/google-ads/answer/16355235?hl=en + to learn more. Example: +16504519489. email (str): Output only. Consumer email address. consumer_name (str): diff --git a/google/ads/googleads/v20/resources/types/shopping_performance_view.py b/google/ads/googleads/v20/resources/types/shopping_performance_view.py index f5c039664..8471481ab 100644 --- a/google/ads/googleads/v20/resources/types/shopping_performance_view.py +++ b/google/ads/googleads/v20/resources/types/shopping_performance_view.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -30,12 +29,26 @@ class ShoppingPerformanceView(proto.Message): r"""Shopping performance view. - Provides Shopping campaign statistics aggregated at several - product dimension levels. Product dimension values from Merchant - Center such as brand, category, custom attributes, product - condition and product type will reflect the state of each - dimension as of the date and time when the corresponding event - was recorded. + + Provides Shopping campaign and Performance Max campaign statistics + aggregated at several product dimension levels. Product dimension + values from Merchant Center such as brand, category, custom + attributes, product condition, and product type will reflect the + state of each dimension as of the date and time when the + corresponding event was recorded. + + The number of impressions and clicks that + ``shopping_performance_view`` returns stats for may be different + from campaign reports. ``shopping_performance_view`` shows + impressions and clicks on products appearing in ads, while campaign + reports show impressions and clicks on the ads themselves. Depending + on the format, an ad can show from zero to several products, so the + numbers may not match. + + In Google Ads UI, you can query impressions and clicks of products + appearing in ads by selecting a column from "Product attributes" in + the report editor. For example, selecting the "Brand" column is + equivalent to selecting ``segments.product_brand``. Attributes: resource_name (str): diff --git a/google/ads/googleads/v20/resources/types/shopping_product.py b/google/ads/googleads/v20/resources/types/shopping_product.py index 3e3c3a15b..2b02293a8 100644 --- a/google/ads/googleads/v20/resources/types/shopping_product.py +++ b/google/ads/googleads/v20/resources/types/shopping_product.py @@ -26,7 +26,6 @@ from google.ads.googleads.v20.enums.types import product_issue_severity from google.ads.googleads.v20.enums.types import product_status - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -50,27 +49,31 @@ class ShoppingProduct(proto.Message): Queries to this resource specify a scope: Account: - - Filters on campaigns or ad groups are not specified. - - All products from the linked Google Merchant Center accounts are - returned. - - Metrics and some fields (see the per-field documentation) are - aggregated across all Shopping and Performance Max campaigns that - include a product. Campaign: - - An equality filter on ``campaign`` is specified. Supported - campaign types are Shopping, Performance Max, Demand Gen, Video. - - Only products that are included by the specified campaign are - returned. - - Metrics and some fields (see the per-field documentation) are - restricted to the specified campaign. Ad group: - - An equality filter on ``ad group`` and ``campaign`` is specified. - Supported campaign types are Shopping, Demand Gen, Video. - - Only products that are included by the specified campaign are - returned. - - Metrics and some fields (see the per-field documentation) are - restricted to the specified ad group. Note that segmentation by - date segments is not permitted and will return - UNSUPPORTED_DATE_SEGMENTATION error. On the other hand, filtering - on date segments is allowed. + - Filters on campaigns or ad groups are not specified. + - All products from the linked Google Merchant Center accounts are + returned. + - Metrics and some fields (see the per-field documentation) are + aggregated across all Shopping and Performance Max campaigns that + include a product. Campaign: + - An equality filter on ``campaign`` is specified. Supported + campaign types are Shopping, Performance Max, Demand Gen, Video. + - Only products that are included by the specified campaign are + returned. + - Metrics and some fields (see the per-field documentation) are + restricted to the specified campaign. + - Only the following metrics are supported for Demand Gen and Video + campaigns: impressions, clicks, ctr. Ad group: + - An equality filter on ``ad group`` and ``campaign`` is specified. + Supported campaign types are Shopping, Demand Gen, Video. + - Only products that are included by the specified campaign are + returned. + - Metrics and some fields (see the per-field documentation) are + restricted to the specified ad group. + - Only the following metrics are supported for Demand Gen and Video + campaigns: impressions, clicks, ctr. Note that segmentation by + date segments is not permitted and will return + UNSUPPORTED_DATE_SEGMENTATION error. On the other hand, filtering + on date segments is allowed. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v20/resources/types/user_list.py b/google/ads/googleads/v20/resources/types/user_list.py index 615042936..4a3760d5b 100644 --- a/google/ads/googleads/v20/resources/types/user_list.py +++ b/google/ads/googleads/v20/resources/types/user_list.py @@ -28,7 +28,6 @@ from google.ads.googleads.v20.enums.types import user_list_size_range from google.ads.googleads.v20.enums.types import user_list_type - __protobuf__ = proto.module( package="google.ads.googleads.v20.resources", marshal="google.ads.googleads.v20", @@ -39,7 +38,12 @@ class UserList(proto.Message): - r"""A user list. This is a list of users a customer may target. + r"""A user list. This is a list of users a customer may target. The + unique key of a user list consists of the following fields: ``id``. + Note that the ``name`` must also be unique for user lists owned by a + given customer, except in some cases where ``access_reason`` is set + to ``SHARED``. Violating the unique name constraint produces error: + ``UserListError.INVALID_NAME``. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -68,9 +72,9 @@ class UserList(proto.Message): This field is a member of `oneof`_ ``_read_only``. name (str): - Name of this user list. Depending on its access_reason, the - user list name may not be unique (for example, if - access_reason=SHARED) + Name of this user list. Unique per user list, except in some + cases where a user list of the same name has + ``access_reason`` set to ``SHARED``. This field is a member of `oneof`_ ``_name``. description (str): diff --git a/google/ads/googleads/v20/services/services/account_budget_proposal_service/async_client.py b/google/ads/googleads/v20/services/services/account_budget_proposal_service/async_client.py index d7c51ed01..b90027cf3 100644 --- a/google/ads/googleads/v20/services/services/account_budget_proposal_service/async_client.py +++ b/google/ads/googleads/v20/services/services/account_budget_proposal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -140,7 +139,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AccountBudgetProposalServiceAsyncClient: The constructed client. """ - return AccountBudgetProposalServiceClient.from_service_account_info.__func__(AccountBudgetProposalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AccountBudgetProposalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AccountBudgetProposalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -156,7 +160,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountBudgetProposalServiceAsyncClient: The constructed client. """ - return AccountBudgetProposalServiceClient.from_service_account_file.__func__(AccountBudgetProposalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AccountBudgetProposalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AccountBudgetProposalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/account_budget_proposal_service/client.py b/google/ads/googleads/v20/services/services/account_budget_proposal_service/client.py index 786631ec9..2e3c6b48e 100644 --- a/google/ads/googleads/v20/services/services/account_budget_proposal_service/client.py +++ b/google/ads/googleads/v20/services/services/account_budget_proposal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -389,14 +417,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AccountBudgetProposalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -404,7 +428,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -436,22 +460,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AccountBudgetProposalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/base.py b/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/base.py index 95cf3f872..c550003d5 100644 --- a/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/grpc.py b/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/grpc.py index 7c61a2783..b10a1f43f 100644 --- a/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/grpc.py @@ -175,9 +175,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -318,9 +319,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/grpc_asyncio.py index 6e66c3bc2..3a1d6364e 100644 --- a/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/account_budget_proposal_service/transports/grpc_asyncio.py @@ -165,8 +165,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -221,9 +222,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/account_link_service/async_client.py b/google/ads/googleads/v20/services/services/account_link_service/async_client.py index 1d79e8d75..f7d2fa268 100644 --- a/google/ads/googleads/v20/services/services/account_link_service/async_client.py +++ b/google/ads/googleads/v20/services/services/account_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,7 +36,7 @@ account_link as gagr_account_link, ) from google.ads.googleads.v20.services.types import account_link_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AccountLinkServiceTransport, DEFAULT_CLIENT_INFO from .client import AccountLinkServiceClient @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AccountLinkServiceAsyncClient: The constructed client. """ - return AccountLinkServiceClient.from_service_account_info.__func__(AccountLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AccountLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AccountLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountLinkServiceAsyncClient: The constructed client. """ - return AccountLinkServiceClient.from_service_account_file.__func__(AccountLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AccountLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AccountLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/account_link_service/client.py b/google/ads/googleads/v20/services/services/account_link_service/client.py index 5f66511ea..308b2823c 100644 --- a/google/ads/googleads/v20/services/services/account_link_service/client.py +++ b/google/ads/googleads/v20/services/services/account_link_service/client.py @@ -53,7 +53,7 @@ account_link as gagr_account_link, ) from google.ads.googleads.v20.services.types import account_link_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AccountLinkServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AccountLinkServiceGrpcTransport from .transports.grpc_asyncio import AccountLinkServiceGrpcAsyncIOTransport @@ -139,6 +139,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -330,14 +358,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AccountLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -345,7 +367,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -377,22 +399,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AccountLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/account_link_service/transports/base.py b/google/ads/googleads/v20/services/services/account_link_service/transports/base.py index b78420a2e..238d9bb2a 100644 --- a/google/ads/googleads/v20/services/services/account_link_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/account_link_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/account_link_service/transports/grpc.py b/google/ads/googleads/v20/services/services/account_link_service/transports/grpc.py index 62dabf15f..a2acf2a9b 100644 --- a/google/ads/googleads/v20/services/services/account_link_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/account_link_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/account_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/account_link_service/transports/grpc_asyncio.py index 3d6fe459f..08a9173ac 100644 --- a/google/ads/googleads/v20/services/services/account_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/account_link_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/async_client.py index d4bd05857..7cae363b5 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_group_ad_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupAdLabelServiceClient @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAdLabelServiceAsyncClient: The constructed client. """ - return AdGroupAdLabelServiceClient.from_service_account_info.__func__(AdGroupAdLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAdLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupAdLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAdLabelServiceAsyncClient: The constructed client. """ - return AdGroupAdLabelServiceClient.from_service_account_file.__func__(AdGroupAdLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAdLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAdLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/client.py b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/client.py index a724e65bd..3aac9a4a5 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_group_ad_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupAdLabelServiceGrpcTransport from .transports.grpc_asyncio import AdGroupAdLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -384,14 +412,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupAdLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -399,7 +423,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -431,22 +455,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupAdLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/base.py index 8c4d617c3..3acac8c67 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/grpc.py index ce49ba143..60aa24391 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/grpc_asyncio.py index 4dfeca89a..92168a1df 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_ad_service/async_client.py index 175a94c79..db19a9130 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_group_ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupAdServiceClient @@ -122,7 +121,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAdServiceAsyncClient: The constructed client. """ - return AdGroupAdServiceClient.from_service_account_info.__func__(AdGroupAdServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAdServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdGroupAdServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAdServiceAsyncClient: The constructed client. """ - return AdGroupAdServiceClient.from_service_account_file.__func__(AdGroupAdServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAdServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAdServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -456,7 +463,7 @@ async def remove_automatically_created_assets( Args: request (Optional[Union[google.ads.googleads.v20.services.types.RemoveAutomaticallyCreatedAssetsRequest, dict]]): The request object. Request message for - [AdGroupAdService.RemoveAutomaticallyCreatedAssetsRequest][]. + [AdGroupAdService.RemoveAutomaticallyCreatedAssets][google.ads.googleads.v20.services.AdGroupAdService.RemoveAutomaticallyCreatedAssets]. ad_group_ad (:class:`str`): Required. The resource name of the AdGroupAd from which to remove diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_service/client.py b/google/ads/googleads/v20/services/services/ad_group_ad_service/client.py index 9cb6609da..c3774383d 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_group_ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupAdServiceGrpcTransport from .transports.grpc_asyncio import AdGroupAdServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -421,14 +449,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupAdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -436,7 +458,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -468,22 +490,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupAdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -974,7 +990,7 @@ def remove_automatically_created_assets( Args: request (Union[google.ads.googleads.v20.services.types.RemoveAutomaticallyCreatedAssetsRequest, dict]): The request object. Request message for - [AdGroupAdService.RemoveAutomaticallyCreatedAssetsRequest][]. + [AdGroupAdService.RemoveAutomaticallyCreatedAssets][google.ads.googleads.v20.services.AdGroupAdService.RemoveAutomaticallyCreatedAssets]. ad_group_ad (str): Required. The resource name of the AdGroupAd from which to remove diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/base.py index 4ba545ce7..67a829e8c 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/base.py @@ -27,7 +27,7 @@ import google.protobuf from google.ads.googleads.v20.services.types import ad_group_ad_service -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -67,9 +67,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -82,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/grpc.py index a69b38bf7..52287f08c 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/grpc.py @@ -30,7 +30,7 @@ import proto # type: ignore from google.ads.googleads.v20.services.types import ad_group_ad_service -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO try: @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/grpc_asyncio.py index 2a9eb6d94..690d2ed16 100644 --- a/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_ad_service/transports/grpc_asyncio.py @@ -31,7 +31,7 @@ from grpc.experimental import aio # type: ignore from google.ads.googleads.v20.services.types import ad_group_ad_service -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO try: @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_asset_service/async_client.py index dc11fd180..1f5758950 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupAssetServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAssetServiceAsyncClient: The constructed client. """ - return AdGroupAssetServiceClient.from_service_account_info.__func__(AdGroupAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAssetServiceAsyncClient: The constructed client. """ - return AdGroupAssetServiceClient.from_service_account_file.__func__(AdGroupAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_service/client.py b/google/ads/googleads/v20/services/services/ad_group_asset_service/client.py index fb0b720e5..55b78b5c7 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupAssetServiceGrpcTransport from .transports.grpc_asyncio import AdGroupAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -380,14 +408,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupAssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -395,7 +417,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -427,22 +449,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupAssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/base.py index 95466f84e..5787220c8 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/grpc.py index 06ea1ddad..7b2a5415e 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/grpc_asyncio.py index 01318f62b..5c0ff5f77 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/async_client.py index 4df9a53af..42c73ce35 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_group_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAssetSetServiceAsyncClient: The constructed client. """ - return AdGroupAssetSetServiceClient.from_service_account_info.__func__(AdGroupAssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupAssetSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAssetSetServiceAsyncClient: The constructed client. """ - return AdGroupAssetSetServiceClient.from_service_account_file.__func__(AdGroupAssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/client.py b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/client.py index 47bbb9cd1..3958a0d70 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_group_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -382,14 +410,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupAssetSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -397,7 +421,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -429,22 +453,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupAssetSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/base.py index 154117a81..f2cdbf438 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/grpc.py index 28bb888bc..3f08cb262 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/grpc_asyncio.py index bd3736e41..6e5659517 100644 --- a/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_asset_set_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/async_client.py index 80641f732..9353747c6 100644 --- a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( ad_group_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupBidModifierServiceAsyncClient: The constructed client. """ - return AdGroupBidModifierServiceClient.from_service_account_info.__func__(AdGroupBidModifierServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupBidModifierServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupBidModifierServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupBidModifierServiceAsyncClient: The constructed client. """ - return AdGroupBidModifierServiceClient.from_service_account_file.__func__(AdGroupBidModifierServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupBidModifierServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupBidModifierServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/client.py b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/client.py index 576c1963f..f519ffb6f 100644 --- a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( ad_group_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupBidModifierServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupBidModifierServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/base.py index a430c264c..1621cc0be 100644 --- a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/grpc.py index e51bd43af..ec93ebb24 100644 --- a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/grpc_asyncio.py index d6f05d917..2024fe5b5 100644 --- a/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_bid_modifier_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/async_client.py index 48448a218..65fe7090e 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( ad_group_criterion_customizer_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -133,7 +132,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCriterionCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCriterionCustomizerServiceClient.from_service_account_info.__func__(AdGroupCriterionCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCriterionCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCriterionCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -149,7 +153,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCriterionCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCriterionCustomizerServiceClient.from_service_account_file.__func__(AdGroupCriterionCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCriterionCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCriterionCustomizerServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/client.py b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/client.py index bff9d682a..ae3aabf36 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( ad_group_criterion_customizer_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -392,14 +420,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCriterionCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -407,7 +431,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -439,22 +463,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCriterionCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/base.py index 5de512305..854f41566 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/grpc.py index 3a2b9d0f6..39f03af1e 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/grpc_asyncio.py index 019afd0a3..394105f4e 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_customizer_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/async_client.py index 5f23223eb..e6e3acc69 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( ad_group_criterion_label_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionLabelServiceTransport, DEFAULT_CLIENT_INFO, @@ -129,7 +128,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCriterionLabelServiceAsyncClient: The constructed client. """ - return AdGroupCriterionLabelServiceClient.from_service_account_info.__func__(AdGroupCriterionLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCriterionLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCriterionLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -145,7 +149,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCriterionLabelServiceAsyncClient: The constructed client. """ - return AdGroupCriterionLabelServiceClient.from_service_account_file.__func__(AdGroupCriterionLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCriterionLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCriterionLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/client.py b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/client.py index deeaf0af2..42cf2d5d3 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( ad_group_criterion_label_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionLabelServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -391,14 +419,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCriterionLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -406,7 +430,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -438,22 +462,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCriterionLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/base.py index 9a167768b..7f10f51f6 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/grpc.py index 642f81962..4d1852458 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/grpc_asyncio.py index 5558d4ecd..a9510b7a9 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_label_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_criterion_service/async_client.py index b40a7e8ec..dbe2c1b22 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_group_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -143,7 +142,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCriterionServiceAsyncClient: The constructed client. """ - return AdGroupCriterionServiceClient.from_service_account_info.__func__(AdGroupCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -159,7 +163,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCriterionServiceAsyncClient: The constructed client. """ - return AdGroupCriterionServiceClient.from_service_account_file.__func__(AdGroupCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCriterionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_service/client.py b/google/ads/googleads/v20/services/services/ad_group_criterion_service/client.py index 69202ce50..c738a3c64 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_group_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -441,14 +469,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -456,7 +480,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -488,22 +512,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/base.py index d97856328..f32796754 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/grpc.py index cd6f710d1..610990a69 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/grpc_asyncio.py index c44f1f0a2..5f875c942 100644 --- a/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_criterion_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_customizer_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_customizer_service/async_client.py index d63e5577d..ee977f6c6 100644 --- a/google/ads/googleads/v20/services/services/ad_group_customizer_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_group_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCustomizerServiceClient.from_service_account_info.__func__(AdGroupCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCustomizerServiceClient.from_service_account_file.__func__(AdGroupCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCustomizerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_customizer_service/client.py b/google/ads/googleads/v20/services/services/ad_group_customizer_service/client.py index d84a739e9..548078120 100644 --- a/google/ads/googleads/v20/services/services/ad_group_customizer_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_customizer_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_group_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/base.py index 06efb3a01..9724ac9bb 100644 --- a/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/grpc.py index 0648e3243..5777db197 100644 --- a/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/grpc_asyncio.py index 040649daf..cbae94c03 100644 --- a/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_customizer_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_label_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_label_service/async_client.py index a48872a58..428a3e829 100644 --- a/google/ads/googleads/v20/services/services/ad_group_label_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_group_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupLabelServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupLabelServiceAsyncClient: The constructed client. """ - return AdGroupLabelServiceClient.from_service_account_info.__func__(AdGroupLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupLabelServiceAsyncClient: The constructed client. """ - return AdGroupLabelServiceClient.from_service_account_file.__func__(AdGroupLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_label_service/client.py b/google/ads/googleads/v20/services/services/ad_group_label_service/client.py index b35f9a7f7..444cd5e83 100644 --- a/google/ads/googleads/v20/services/services/ad_group_label_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_group_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupLabelServiceGrpcTransport from .transports.grpc_asyncio import AdGroupLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -378,14 +406,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupLabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -393,7 +415,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -425,22 +447,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupLabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_label_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_label_service/transports/base.py index d7944b02f..57a05449a 100644 --- a/google/ads/googleads/v20/services/services/ad_group_label_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_label_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_label_service/transports/grpc.py index 6dede3d5f..cfd910023 100644 --- a/google/ads/googleads/v20/services/services/ad_group_label_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_label_service/transports/grpc_asyncio.py index a56fd1879..3eaf72c9d 100644 --- a/google/ads/googleads/v20/services/services/ad_group_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_service/async_client.py b/google/ads/googleads/v20/services/services/ad_group_service/async_client.py index fb4c4d24c..0cdf8bdf7 100644 --- a/google/ads/googleads/v20/services/services/ad_group_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupServiceAsyncClient: The constructed client. """ - return AdGroupServiceClient.from_service_account_info.__func__(AdGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdGroupServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupServiceAsyncClient: The constructed client. """ - return AdGroupServiceClient.from_service_account_file.__func__(AdGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_group_service/client.py b/google/ads/googleads/v20/services/services/ad_group_service/client.py index 24469fc63..8bb7c5dcc 100644 --- a/google/ads/googleads/v20/services/services/ad_group_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_group_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupServiceGrpcTransport from .transports.grpc_asyncio import AdGroupServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -377,14 +405,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -392,7 +414,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -424,22 +446,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_group_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_group_service/transports/base.py index 353720e6f..2e1f2373c 100644 --- a/google/ads/googleads/v20/services/services/ad_group_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_group_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_group_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_group_service/transports/grpc.py index cacf51343..0efb5444a 100644 --- a/google/ads/googleads/v20/services/services/ad_group_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_group_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_group_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_group_service/transports/grpc_asyncio.py index 79f3d3d2b..a56bb681c 100644 --- a/google/ads/googleads/v20/services/services/ad_group_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_group_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_parameter_service/async_client.py b/google/ads/googleads/v20/services/services/ad_parameter_service/async_client.py index 2d21f9e74..cb7bc9245 100644 --- a/google/ads/googleads/v20/services/services/ad_parameter_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_parameter_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_parameter_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdParameterServiceTransport, DEFAULT_CLIENT_INFO from .client import AdParameterServiceClient @@ -116,7 +115,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdParameterServiceAsyncClient: The constructed client. """ - return AdParameterServiceClient.from_service_account_info.__func__(AdParameterServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdParameterServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdParameterServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,7 +136,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdParameterServiceAsyncClient: The constructed client. """ - return AdParameterServiceClient.from_service_account_file.__func__(AdParameterServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdParameterServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdParameterServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_parameter_service/client.py b/google/ads/googleads/v20/services/services/ad_parameter_service/client.py index 598af578d..d5a94bddd 100644 --- a/google/ads/googleads/v20/services/services/ad_parameter_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_parameter_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_parameter_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdParameterServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdParameterServiceGrpcTransport from .transports.grpc_asyncio import AdParameterServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -361,14 +389,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdParameterServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -376,7 +398,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -408,22 +430,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdParameterServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_parameter_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_parameter_service/transports/base.py index 1cc70cf94..d8787a055 100644 --- a/google/ads/googleads/v20/services/services/ad_parameter_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_parameter_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_parameter_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_parameter_service/transports/grpc.py index d6c008213..1de44bb52 100644 --- a/google/ads/googleads/v20/services/services/ad_parameter_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_parameter_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_parameter_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_parameter_service/transports/grpc_asyncio.py index 6730c41f6..6fe9fcb6f 100644 --- a/google/ads/googleads/v20/services/services/ad_parameter_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_parameter_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_service/async_client.py b/google/ads/googleads/v20/services/services/ad_service/async_client.py index 82419e536..64967fa0c 100644 --- a/google/ads/googleads/v20/services/services/ad_service/async_client.py +++ b/google/ads/googleads/v20/services/services/ad_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdServiceTransport, DEFAULT_CLIENT_INFO from .client import AdServiceClient @@ -100,7 +99,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdServiceAsyncClient: The constructed client. """ - return AdServiceClient.from_service_account_info.__func__(AdServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -116,7 +118,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdServiceAsyncClient: The constructed client. """ - return AdServiceClient.from_service_account_file.__func__(AdServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AdServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/ad_service/client.py b/google/ads/googleads/v20/services/services/ad_service/client.py index 38c9505bd..b332e5512 100644 --- a/google/ads/googleads/v20/services/services/ad_service/client.py +++ b/google/ads/googleads/v20/services/services/ad_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdServiceGrpcTransport from .transports.grpc_asyncio import AdServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -334,14 +362,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -349,7 +371,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -381,22 +403,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/ad_service/transports/base.py b/google/ads/googleads/v20/services/services/ad_service/transports/base.py index f9ada1a1d..7020266ca 100644 --- a/google/ads/googleads/v20/services/services/ad_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/ad_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/ad_service/transports/grpc.py b/google/ads/googleads/v20/services/services/ad_service/transports/grpc.py index f8ea5697f..3e855c196 100644 --- a/google/ads/googleads/v20/services/services/ad_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/ad_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/ad_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/ad_service/transports/grpc_asyncio.py index a0dcd3ce5..d97b55ba1 100644 --- a/google/ads/googleads/v20/services/services/ad_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/ad_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_group_asset_service/async_client.py b/google/ads/googleads/v20/services/services/asset_group_asset_service/async_client.py index 526b587ea..85454b8ae 100644 --- a/google/ads/googleads/v20/services/services/asset_group_asset_service/async_client.py +++ b/google/ads/googleads/v20/services/services/asset_group_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import asset_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupAssetServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupAssetServiceAsyncClient: The constructed client. """ - return AssetGroupAssetServiceClient.from_service_account_info.__func__(AssetGroupAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGroupAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupAssetServiceAsyncClient: The constructed client. """ - return AssetGroupAssetServiceClient.from_service_account_file.__func__(AssetGroupAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/asset_group_asset_service/client.py b/google/ads/googleads/v20/services/services/asset_group_asset_service/client.py index 12d568e95..745f3259d 100644 --- a/google/ads/googleads/v20/services/services/asset_group_asset_service/client.py +++ b/google/ads/googleads/v20/services/services/asset_group_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import asset_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupAssetServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -383,14 +411,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGroupAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -398,7 +422,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -430,22 +454,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGroupAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/base.py b/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/base.py index 14c3d77d7..22d34909f 100644 --- a/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/grpc.py b/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/grpc.py index 2798f8635..ac40aa901 100644 --- a/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/grpc_asyncio.py index f0a7e4fae..469719604 100644 --- a/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/asset_group_asset_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/async_client.py b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/async_client.py index 7b01e9cce..424efc7be 100644 --- a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/async_client.py +++ b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -128,7 +127,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupListingGroupFilterServiceAsyncClient: The constructed client. """ - return AssetGroupListingGroupFilterServiceClient.from_service_account_info.__func__(AssetGroupListingGroupFilterServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupListingGroupFilterServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGroupListingGroupFilterServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -144,7 +151,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupListingGroupFilterServiceAsyncClient: The constructed client. """ - return AssetGroupListingGroupFilterServiceClient.from_service_account_file.__func__(AssetGroupListingGroupFilterServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupListingGroupFilterServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupListingGroupFilterServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/client.py b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/client.py index 558314794..97d721b5f 100644 --- a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/client.py +++ b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/client.py @@ -156,6 +156,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -371,14 +399,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGroupListingGroupFilterServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -386,7 +410,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -418,22 +442,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGroupListingGroupFilterServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/base.py b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/base.py index 1dd015d75..a6031fcfc 100644 --- a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/grpc.py b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/grpc.py index d800c62a2..9d2650071 100644 --- a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/grpc_asyncio.py index ee55d2719..7f581eacb 100644 --- a/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/asset_group_listing_group_filter_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_group_service/async_client.py b/google/ads/googleads/v20/services/services/asset_group_service/async_client.py index 03d143389..177662f1b 100644 --- a/google/ads/googleads/v20/services/services/asset_group_service/async_client.py +++ b/google/ads/googleads/v20/services/services/asset_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import asset_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetGroupServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetGroupServiceClient @@ -114,7 +113,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupServiceAsyncClient: The constructed client. """ - return AssetGroupServiceClient.from_service_account_info.__func__(AssetGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssetGroupServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupServiceAsyncClient: The constructed client. """ - return AssetGroupServiceClient.from_service_account_file.__func__(AssetGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/asset_group_service/client.py b/google/ads/googleads/v20/services/services/asset_group_service/client.py index df4255fb1..97eb88238 100644 --- a/google/ads/googleads/v20/services/services/asset_group_service/client.py +++ b/google/ads/googleads/v20/services/services/asset_group_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import asset_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetGroupServiceGrpcTransport from .transports.grpc_asyncio import AssetGroupServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -355,14 +383,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AssetGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -370,7 +392,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -402,22 +424,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AssetGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/asset_group_service/transports/base.py b/google/ads/googleads/v20/services/services/asset_group_service/transports/base.py index bfdbfe8a1..c600b1430 100644 --- a/google/ads/googleads/v20/services/services/asset_group_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/asset_group_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/asset_group_service/transports/grpc.py b/google/ads/googleads/v20/services/services/asset_group_service/transports/grpc.py index a7b7be070..1ee7a478d 100644 --- a/google/ads/googleads/v20/services/services/asset_group_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/asset_group_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_group_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/asset_group_service/transports/grpc_asyncio.py index e0ce8ecaf..35cd0e022 100644 --- a/google/ads/googleads/v20/services/services/asset_group_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/asset_group_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_group_signal_service/async_client.py b/google/ads/googleads/v20/services/services/asset_group_signal_service/async_client.py index f61bc565f..7a8686975 100644 --- a/google/ads/googleads/v20/services/services/asset_group_signal_service/async_client.py +++ b/google/ads/googleads/v20/services/services/asset_group_signal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import asset_group_signal_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupSignalServiceTransport, DEFAULT_CLIENT_INFO, @@ -121,7 +120,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupSignalServiceAsyncClient: The constructed client. """ - return AssetGroupSignalServiceClient.from_service_account_info.__func__(AssetGroupSignalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupSignalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGroupSignalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -137,7 +141,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupSignalServiceAsyncClient: The constructed client. """ - return AssetGroupSignalServiceClient.from_service_account_file.__func__(AssetGroupSignalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupSignalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupSignalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/asset_group_signal_service/client.py b/google/ads/googleads/v20/services/services/asset_group_signal_service/client.py index c1627a1c1..9dad1bf60 100644 --- a/google/ads/googleads/v20/services/services/asset_group_signal_service/client.py +++ b/google/ads/googleads/v20/services/services/asset_group_signal_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import asset_group_signal_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupSignalServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -364,14 +392,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGroupSignalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -379,7 +403,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -411,22 +435,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGroupSignalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/base.py b/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/base.py index bd4deeb2d..ce383090c 100644 --- a/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/grpc.py b/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/grpc.py index 3fbb87921..5c541973b 100644 --- a/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/grpc_asyncio.py index 1f3d41444..b619e4af5 100644 --- a/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/asset_group_signal_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_service/async_client.py b/google/ads/googleads/v20/services/services/asset_service/async_client.py index 33f1e91d9..721d01323 100644 --- a/google/ads/googleads/v20/services/services/asset_service/async_client.py +++ b/google/ads/googleads/v20/services/services/asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetServiceClient @@ -109,7 +108,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetServiceAsyncClient: The constructed client. """ - return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssetServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -125,7 +127,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetServiceAsyncClient: The constructed client. """ - return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AssetServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/asset_service/client.py b/google/ads/googleads/v20/services/services/asset_service/client.py index ce42fcf7f..dca9e69cc 100644 --- a/google/ads/googleads/v20/services/services/asset_service/client.py +++ b/google/ads/googleads/v20/services/services/asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport @@ -147,6 +147,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -357,14 +385,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -372,7 +394,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -404,22 +426,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/asset_service/transports/base.py b/google/ads/googleads/v20/services/services/asset_service/transports/base.py index b422c6ffd..b487b235a 100644 --- a/google/ads/googleads/v20/services/services/asset_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/asset_service/transports/grpc.py b/google/ads/googleads/v20/services/services/asset_service/transports/grpc.py index 800c1df74..bb8f6a8d7 100644 --- a/google/ads/googleads/v20/services/services/asset_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/asset_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/asset_service/transports/grpc_asyncio.py index a9a77a405..9423a3f9d 100644 --- a/google/ads/googleads/v20/services/services/asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/asset_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_set_asset_service/async_client.py b/google/ads/googleads/v20/services/services/asset_set_asset_service/async_client.py index ba8165fd9..a84f5d391 100644 --- a/google/ads/googleads/v20/services/services/asset_set_asset_service/async_client.py +++ b/google/ads/googleads/v20/services/services/asset_set_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import asset_set_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetSetAssetServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetSetAssetServiceAsyncClient: The constructed client. """ - return AssetSetAssetServiceClient.from_service_account_info.__func__(AssetSetAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetSetAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetSetAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetSetAssetServiceAsyncClient: The constructed client. """ - return AssetSetAssetServiceClient.from_service_account_file.__func__(AssetSetAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetSetAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetSetAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/asset_set_asset_service/client.py b/google/ads/googleads/v20/services/services/asset_set_asset_service/client.py index c06900a8d..0eee99cec 100644 --- a/google/ads/googleads/v20/services/services/asset_set_asset_service/client.py +++ b/google/ads/googleads/v20/services/services/asset_set_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import asset_set_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetSetAssetServiceGrpcTransport from .transports.grpc_asyncio import AssetSetAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -378,14 +406,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetSetAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -393,7 +417,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -425,22 +449,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetSetAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/base.py b/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/base.py index f71497677..ef670c913 100644 --- a/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/grpc.py b/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/grpc.py index d6d77a56f..5c1748b12 100644 --- a/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/grpc_asyncio.py index 2a2224abf..3f3129c0e 100644 --- a/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/asset_set_asset_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_set_service/async_client.py b/google/ads/googleads/v20/services/services/asset_set_service/async_client.py index f667dd46c..2daba00a4 100644 --- a/google/ads/googleads/v20/services/services/asset_set_service/async_client.py +++ b/google/ads/googleads/v20/services/services/asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetSetServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetSetServiceAsyncClient: The constructed client. """ - return AssetSetServiceClient.from_service_account_info.__func__(AssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssetSetServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetSetServiceAsyncClient: The constructed client. """ - return AssetSetServiceClient.from_service_account_file.__func__(AssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/asset_set_service/client.py b/google/ads/googleads/v20/services/services/asset_set_service/client.py index ce9088932..8f773dbc6 100644 --- a/google/ads/googleads/v20/services/services/asset_set_service/client.py +++ b/google/ads/googleads/v20/services/services/asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetSetServiceGrpcTransport from .transports.grpc_asyncio import AssetSetServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AssetSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AssetSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/asset_set_service/transports/base.py b/google/ads/googleads/v20/services/services/asset_set_service/transports/base.py index 721181703..417d5e0ab 100644 --- a/google/ads/googleads/v20/services/services/asset_set_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/asset_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/asset_set_service/transports/grpc.py b/google/ads/googleads/v20/services/services/asset_set_service/transports/grpc.py index 057f82867..71d84e4ac 100644 --- a/google/ads/googleads/v20/services/services/asset_set_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/asset_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/asset_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/asset_set_service/transports/grpc_asyncio.py index e88d02e73..755282169 100644 --- a/google/ads/googleads/v20/services/services/asset_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/asset_set_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/audience_insights_service/async_client.py b/google/ads/googleads/v20/services/services/audience_insights_service/async_client.py index 0409b4f35..f4a666a8d 100644 --- a/google/ads/googleads/v20/services/services/audience_insights_service/async_client.py +++ b/google/ads/googleads/v20/services/services/audience_insights_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -114,7 +113,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AudienceInsightsServiceAsyncClient: The constructed client. """ - return AudienceInsightsServiceClient.from_service_account_info.__func__(AudienceInsightsServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AudienceInsightsServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AudienceInsightsServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +134,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AudienceInsightsServiceAsyncClient: The constructed client. """ - return AudienceInsightsServiceClient.from_service_account_file.__func__(AudienceInsightsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AudienceInsightsServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AudienceInsightsServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/audience_insights_service/client.py b/google/ads/googleads/v20/services/services/audience_insights_service/client.py index 19022e688..f94e54c1f 100644 --- a/google/ads/googleads/v20/services/services/audience_insights_service/client.py +++ b/google/ads/googleads/v20/services/services/audience_insights_service/client.py @@ -156,6 +156,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -327,14 +355,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AudienceInsightsServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -342,7 +366,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -374,22 +398,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AudienceInsightsServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/audience_insights_service/transports/base.py b/google/ads/googleads/v20/services/services/audience_insights_service/transports/base.py index 0e39442e1..c98556c91 100644 --- a/google/ads/googleads/v20/services/services/audience_insights_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/audience_insights_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/audience_insights_service/transports/grpc.py b/google/ads/googleads/v20/services/services/audience_insights_service/transports/grpc.py index ce7981277..1c4e42803 100644 --- a/google/ads/googleads/v20/services/services/audience_insights_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/audience_insights_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/audience_insights_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/audience_insights_service/transports/grpc_asyncio.py index 5d71079de..eaac79e36 100644 --- a/google/ads/googleads/v20/services/services/audience_insights_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/audience_insights_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/audience_service/async_client.py b/google/ads/googleads/v20/services/services/audience_service/async_client.py index 4a4199f0a..176dc95b9 100644 --- a/google/ads/googleads/v20/services/services/audience_service/async_client.py +++ b/google/ads/googleads/v20/services/services/audience_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import audience_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AudienceServiceTransport, DEFAULT_CLIENT_INFO from .client import AudienceServiceClient @@ -122,7 +121,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AudienceServiceAsyncClient: The constructed client. """ - return AudienceServiceClient.from_service_account_info.__func__(AudienceServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AudienceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AudienceServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AudienceServiceAsyncClient: The constructed client. """ - return AudienceServiceClient.from_service_account_file.__func__(AudienceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AudienceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AudienceServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/audience_service/client.py b/google/ads/googleads/v20/services/services/audience_service/client.py index 988f78aa1..a8d825026 100644 --- a/google/ads/googleads/v20/services/services/audience_service/client.py +++ b/google/ads/googleads/v20/services/services/audience_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import audience_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AudienceServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AudienceServiceGrpcTransport from .transports.grpc_asyncio import AudienceServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -395,14 +423,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AudienceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -410,7 +432,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -442,22 +464,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AudienceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/audience_service/transports/base.py b/google/ads/googleads/v20/services/services/audience_service/transports/base.py index ad30abba0..53045d590 100644 --- a/google/ads/googleads/v20/services/services/audience_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/audience_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/audience_service/transports/grpc.py b/google/ads/googleads/v20/services/services/audience_service/transports/grpc.py index b832f1ede..a422774d2 100644 --- a/google/ads/googleads/v20/services/services/audience_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/audience_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/audience_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/audience_service/transports/grpc_asyncio.py index 2e0a61f3f..dde4c2e5d 100644 --- a/google/ads/googleads/v20/services/services/audience_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/audience_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/batch_job_service/async_client.py b/google/ads/googleads/v20/services/services/batch_job_service/async_client.py index bc670ca35..1b429b459 100644 --- a/google/ads/googleads/v20/services/services/batch_job_service/async_client.py +++ b/google/ads/googleads/v20/services/services/batch_job_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,9 +36,9 @@ from google.ads.googleads.v20.services.services.batch_job_service import pagers from google.ads.googleads.v20.services.types import batch_job_service from google.ads.googleads.v20.services.types import google_ads_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .transports.base import BatchJobServiceTransport, DEFAULT_CLIENT_INFO from .client import BatchJobServiceClient @@ -523,7 +522,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BatchJobServiceAsyncClient: The constructed client. """ - return BatchJobServiceClient.from_service_account_info.__func__(BatchJobServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BatchJobServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(BatchJobServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -539,7 +541,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BatchJobServiceAsyncClient: The constructed client. """ - return BatchJobServiceClient.from_service_account_file.__func__(BatchJobServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BatchJobServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BatchJobServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/batch_job_service/client.py b/google/ads/googleads/v20/services/services/batch_job_service/client.py index 82e1417d8..d787973ae 100644 --- a/google/ads/googleads/v20/services/services/batch_job_service/client.py +++ b/google/ads/googleads/v20/services/services/batch_job_service/client.py @@ -63,9 +63,9 @@ from google.ads.googleads.v20.services.services.batch_job_service import pagers from google.ads.googleads.v20.services.types import batch_job_service from google.ads.googleads.v20.services.types import google_ads_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .transports.base import BatchJobServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import BatchJobServiceGrpcTransport from .transports.grpc_asyncio import BatchJobServiceGrpcAsyncIOTransport @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -1882,14 +1910,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = BatchJobServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -1897,7 +1919,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -1929,22 +1951,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = BatchJobServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/batch_job_service/transports/base.py b/google/ads/googleads/v20/services/services/batch_job_service/transports/base.py index e137c20bd..c1133cd6e 100644 --- a/google/ads/googleads/v20/services/services/batch_job_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/batch_job_service/transports/base.py @@ -67,9 +67,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -82,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/batch_job_service/transports/grpc.py b/google/ads/googleads/v20/services/services/batch_job_service/transports/grpc.py index 9e5705082..0fdbe4841 100644 --- a/google/ads/googleads/v20/services/services/batch_job_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/batch_job_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -308,9 +309,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/batch_job_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/batch_job_service/transports/grpc_asyncio.py index 7753be1bc..e2fef27b9 100644 --- a/google/ads/googleads/v20/services/services/batch_job_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/batch_job_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/async_client.py b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/async_client.py index cfd4b967f..0925e012a 100644 --- a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/async_client.py +++ b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( bidding_data_exclusion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingDataExclusionServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BiddingDataExclusionServiceAsyncClient: The constructed client. """ - return BiddingDataExclusionServiceClient.from_service_account_info.__func__(BiddingDataExclusionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BiddingDataExclusionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BiddingDataExclusionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BiddingDataExclusionServiceAsyncClient: The constructed client. """ - return BiddingDataExclusionServiceClient.from_service_account_file.__func__(BiddingDataExclusionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BiddingDataExclusionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BiddingDataExclusionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/client.py b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/client.py index 89226398b..c56c5b898 100644 --- a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/client.py +++ b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( bidding_data_exclusion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingDataExclusionServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -366,14 +394,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BiddingDataExclusionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -381,7 +405,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -413,22 +437,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BiddingDataExclusionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/base.py b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/base.py index 0d8d3d6c8..8b22423b1 100644 --- a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/grpc.py b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/grpc.py index 3ccc9d6ff..c98ffd797 100644 --- a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/grpc_asyncio.py index 411a3ac45..b27df4e73 100644 --- a/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/bidding_data_exclusion_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/async_client.py b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/async_client.py index a35b30179..524389fdd 100644 --- a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/async_client.py +++ b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( bidding_seasonality_adjustment_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingSeasonalityAdjustmentServiceTransport, DEFAULT_CLIENT_INFO, @@ -129,7 +128,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BiddingSeasonalityAdjustmentServiceAsyncClient: The constructed client. """ - return BiddingSeasonalityAdjustmentServiceClient.from_service_account_info.__func__(BiddingSeasonalityAdjustmentServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BiddingSeasonalityAdjustmentServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BiddingSeasonalityAdjustmentServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -145,7 +152,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BiddingSeasonalityAdjustmentServiceAsyncClient: The constructed client. """ - return BiddingSeasonalityAdjustmentServiceClient.from_service_account_file.__func__(BiddingSeasonalityAdjustmentServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BiddingSeasonalityAdjustmentServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BiddingSeasonalityAdjustmentServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/client.py b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/client.py index fc0a94db6..5240800bb 100644 --- a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/client.py +++ b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( bidding_seasonality_adjustment_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingSeasonalityAdjustmentServiceTransport, DEFAULT_CLIENT_INFO, @@ -157,6 +157,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BiddingSeasonalityAdjustmentServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BiddingSeasonalityAdjustmentServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/base.py b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/base.py index c4a902ef2..bdd2be01b 100644 --- a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/grpc.py b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/grpc.py index bc5841449..bf5725661 100644 --- a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/grpc_asyncio.py index 271234d57..e7cc74669 100644 --- a/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/bidding_seasonality_adjustment_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/bidding_strategy_service/async_client.py b/google/ads/googleads/v20/services/services/bidding_strategy_service/async_client.py index 214b36ec7..a6781dd83 100644 --- a/google/ads/googleads/v20/services/services/bidding_strategy_service/async_client.py +++ b/google/ads/googleads/v20/services/services/bidding_strategy_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import bidding_strategy_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingStrategyServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BiddingStrategyServiceAsyncClient: The constructed client. """ - return BiddingStrategyServiceClient.from_service_account_info.__func__(BiddingStrategyServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BiddingStrategyServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BiddingStrategyServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BiddingStrategyServiceAsyncClient: The constructed client. """ - return BiddingStrategyServiceClient.from_service_account_file.__func__(BiddingStrategyServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BiddingStrategyServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BiddingStrategyServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/bidding_strategy_service/client.py b/google/ads/googleads/v20/services/services/bidding_strategy_service/client.py index 42736d304..e70b6c36d 100644 --- a/google/ads/googleads/v20/services/services/bidding_strategy_service/client.py +++ b/google/ads/googleads/v20/services/services/bidding_strategy_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import bidding_strategy_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingStrategyServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -340,14 +368,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BiddingStrategyServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -355,7 +379,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -387,22 +411,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BiddingStrategyServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/base.py b/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/base.py index bae224b16..1506c09cb 100644 --- a/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/grpc.py b/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/grpc.py index 261cf8abc..da103c679 100644 --- a/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/grpc_asyncio.py index b03b1708c..b27288d6b 100644 --- a/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/bidding_strategy_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/billing_setup_service/async_client.py b/google/ads/googleads/v20/services/services/billing_setup_service/async_client.py index 752953ec6..aadf91a35 100644 --- a/google/ads/googleads/v20/services/services/billing_setup_service/async_client.py +++ b/google/ads/googleads/v20/services/services/billing_setup_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -128,7 +127,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BillingSetupServiceAsyncClient: The constructed client. """ - return BillingSetupServiceClient.from_service_account_info.__func__(BillingSetupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BillingSetupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BillingSetupServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -144,7 +148,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BillingSetupServiceAsyncClient: The constructed client. """ - return BillingSetupServiceClient.from_service_account_file.__func__(BillingSetupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BillingSetupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BillingSetupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/billing_setup_service/client.py b/google/ads/googleads/v20/services/services/billing_setup_service/client.py index 12725fc73..63c7f793c 100644 --- a/google/ads/googleads/v20/services/services/billing_setup_service/client.py +++ b/google/ads/googleads/v20/services/services/billing_setup_service/client.py @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -359,14 +387,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = BillingSetupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -374,7 +396,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -406,22 +428,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = BillingSetupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/billing_setup_service/transports/base.py b/google/ads/googleads/v20/services/services/billing_setup_service/transports/base.py index d512ae2af..18aa5a167 100644 --- a/google/ads/googleads/v20/services/services/billing_setup_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/billing_setup_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/billing_setup_service/transports/grpc.py b/google/ads/googleads/v20/services/services/billing_setup_service/transports/grpc.py index 864031af2..0035a5900 100644 --- a/google/ads/googleads/v20/services/services/billing_setup_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/billing_setup_service/transports/grpc.py @@ -172,9 +172,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -315,9 +316,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/billing_setup_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/billing_setup_service/transports/grpc_asyncio.py index c7115d58b..6c4c0ee1f 100644 --- a/google/ads/googleads/v20/services/services/billing_setup_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/billing_setup_service/transports/grpc_asyncio.py @@ -162,8 +162,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -218,9 +219,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/brand_suggestion_service/async_client.py b/google/ads/googleads/v20/services/services/brand_suggestion_service/async_client.py index c2c789d7c..d5904b4b7 100644 --- a/google/ads/googleads/v20/services/services/brand_suggestion_service/async_client.py +++ b/google/ads/googleads/v20/services/services/brand_suggestion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -108,7 +107,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BrandSuggestionServiceAsyncClient: The constructed client. """ - return BrandSuggestionServiceClient.from_service_account_info.__func__(BrandSuggestionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BrandSuggestionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BrandSuggestionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +128,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BrandSuggestionServiceAsyncClient: The constructed client. """ - return BrandSuggestionServiceClient.from_service_account_file.__func__(BrandSuggestionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BrandSuggestionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BrandSuggestionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/brand_suggestion_service/client.py b/google/ads/googleads/v20/services/services/brand_suggestion_service/client.py index d070072f0..c8b5231f3 100644 --- a/google/ads/googleads/v20/services/services/brand_suggestion_service/client.py +++ b/google/ads/googleads/v20/services/services/brand_suggestion_service/client.py @@ -138,6 +138,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -309,14 +337,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BrandSuggestionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -324,7 +348,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -356,22 +380,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BrandSuggestionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/base.py b/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/base.py index c15d05989..e98dda5ba 100644 --- a/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/grpc.py b/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/grpc.py index 21aa57666..30d3814bd 100644 --- a/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/grpc_asyncio.py index 4e3ab238c..cbae15f74 100644 --- a/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/brand_suggestion_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_asset_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_asset_service/async_client.py index 23aed46a6..a44fd569b 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignAssetServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignAssetServiceAsyncClient: The constructed client. """ - return CampaignAssetServiceClient.from_service_account_info.__func__(CampaignAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignAssetServiceAsyncClient: The constructed client. """ - return CampaignAssetServiceClient.from_service_account_file.__func__(CampaignAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_asset_service/client.py b/google/ads/googleads/v20/services/services/campaign_asset_service/client.py index 305ca942e..46f71dff6 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import campaign_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignAssetServiceGrpcTransport from .transports.grpc_asyncio import CampaignAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -380,14 +408,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -395,7 +419,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -427,22 +451,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_asset_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_asset_service/transports/base.py index eed6cc061..4e4b125a8 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_asset_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_asset_service/transports/grpc.py index de52fd795..a2ead2f6a 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_asset_service/transports/grpc_asyncio.py index ff8aca3b6..cb8c15aee 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_asset_set_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_asset_set_service/async_client.py index f41eba376..f9ce9706a 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_set_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignAssetSetServiceAsyncClient: The constructed client. """ - return CampaignAssetSetServiceClient.from_service_account_info.__func__(CampaignAssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignAssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignAssetSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignAssetSetServiceAsyncClient: The constructed client. """ - return CampaignAssetSetServiceClient.from_service_account_file.__func__(CampaignAssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignAssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignAssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_asset_set_service/client.py b/google/ads/googleads/v20/services/services/campaign_asset_set_service/client.py index 06418aafc..387634935 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_set_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import campaign_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -384,14 +412,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignAssetSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -399,7 +423,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -431,22 +455,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignAssetSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/base.py index dbb1341ca..16576ba82 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/grpc.py index 293595f87..356ba9c53 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/grpc_asyncio.py index cc38ad68d..96992c99f 100644 --- a/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_asset_set_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/async_client.py index 97ad2e538..be7b613c8 100644 --- a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( campaign_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignBidModifierServiceAsyncClient: The constructed client. """ - return CampaignBidModifierServiceClient.from_service_account_info.__func__(CampaignBidModifierServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignBidModifierServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignBidModifierServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignBidModifierServiceAsyncClient: The constructed client. """ - return CampaignBidModifierServiceClient.from_service_account_file.__func__(CampaignBidModifierServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignBidModifierServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignBidModifierServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/client.py b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/client.py index 972efc854..0fc1a29af 100644 --- a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( campaign_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignBidModifierServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignBidModifierServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/base.py index 49e206ecd..b6ed0da81 100644 --- a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/grpc.py index 04faaa227..be51d2310 100644 --- a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/grpc_asyncio.py index 3b94a9a35..3a3582abb 100644 --- a/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_bid_modifier_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_budget_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_budget_service/async_client.py index 80e3ef372..1ee0fc0eb 100644 --- a/google/ads/googleads/v20/services/services/campaign_budget_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_budget_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_budget_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignBudgetServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignBudgetServiceClient @@ -112,7 +111,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignBudgetServiceAsyncClient: The constructed client. """ - return CampaignBudgetServiceClient.from_service_account_info.__func__(CampaignBudgetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignBudgetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignBudgetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -128,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignBudgetServiceAsyncClient: The constructed client. """ - return CampaignBudgetServiceClient.from_service_account_file.__func__(CampaignBudgetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignBudgetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignBudgetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_budget_service/client.py b/google/ads/googleads/v20/services/services/campaign_budget_service/client.py index 31149874c..e41a2a7f4 100644 --- a/google/ads/googleads/v20/services/services/campaign_budget_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_budget_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import campaign_budget_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignBudgetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignBudgetServiceGrpcTransport from .transports.grpc_asyncio import CampaignBudgetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -337,14 +365,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignBudgetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -352,7 +376,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -384,22 +408,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignBudgetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_budget_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_budget_service/transports/base.py index 0f8290531..3d6f2147c 100644 --- a/google/ads/googleads/v20/services/services/campaign_budget_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_budget_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_budget_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_budget_service/transports/grpc.py index c02522376..150082652 100644 --- a/google/ads/googleads/v20/services/services/campaign_budget_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_budget_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_budget_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_budget_service/transports/grpc_asyncio.py index c669f40aa..ae193e4af 100644 --- a/google/ads/googleads/v20/services/services/campaign_budget_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_budget_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/async_client.py index 4de4d7179..dbe41be2a 100644 --- a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignConversionGoalServiceAsyncClient: The constructed client. """ - return CampaignConversionGoalServiceClient.from_service_account_info.__func__(CampaignConversionGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignConversionGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignConversionGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignConversionGoalServiceAsyncClient: The constructed client. """ - return CampaignConversionGoalServiceClient.from_service_account_file.__func__(CampaignConversionGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignConversionGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignConversionGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/client.py b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/client.py index d1d62fd11..f74e41001 100644 --- a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -369,14 +397,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignConversionGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -384,7 +408,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -416,22 +440,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignConversionGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/base.py index 22be82268..9b8c4b4f4 100644 --- a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/grpc.py index cf87b43f1..55de8dfe7 100644 --- a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/grpc_asyncio.py index d4cefbefe..639536851 100644 --- a/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_conversion_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_criterion_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_criterion_service/async_client.py index 5b841e5d9..057579c7a 100644 --- a/google/ads/googleads/v20/services/services/campaign_criterion_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -161,7 +160,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignCriterionServiceAsyncClient: The constructed client. """ - return CampaignCriterionServiceClient.from_service_account_info.__func__(CampaignCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -177,7 +181,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignCriterionServiceAsyncClient: The constructed client. """ - return CampaignCriterionServiceClient.from_service_account_file.__func__(CampaignCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignCriterionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_criterion_service/client.py b/google/ads/googleads/v20/services/services/campaign_criterion_service/client.py index 50223e48e..6f38f2540 100644 --- a/google/ads/googleads/v20/services/services/campaign_criterion_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_criterion_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import campaign_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -488,14 +516,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -503,7 +527,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -535,22 +559,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/base.py index 6e6cb9a66..e1cbb7178 100644 --- a/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/grpc.py index c17ec704e..c4918ddd9 100644 --- a/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/grpc_asyncio.py index 037852fab..89fdec814 100644 --- a/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_criterion_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_customizer_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_customizer_service/async_client.py index 5f70a7486..5c0b5f54b 100644 --- a/google/ads/googleads/v20/services/services/campaign_customizer_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -127,7 +126,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignCustomizerServiceAsyncClient: The constructed client. """ - return CampaignCustomizerServiceClient.from_service_account_info.__func__(CampaignCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -143,7 +147,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignCustomizerServiceAsyncClient: The constructed client. """ - return CampaignCustomizerServiceClient.from_service_account_file.__func__(CampaignCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignCustomizerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_customizer_service/client.py b/google/ads/googleads/v20/services/services/campaign_customizer_service/client.py index d80908831..d96f02473 100644 --- a/google/ads/googleads/v20/services/services/campaign_customizer_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_customizer_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import campaign_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/base.py index 58d00d3d8..8ea27c594 100644 --- a/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/grpc.py index 9cb42d5e6..f600bcb1e 100644 --- a/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/grpc_asyncio.py index 27a99aaa1..3fd0ff12a 100644 --- a/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_customizer_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_draft_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_draft_service/async_client.py index 81bdb8f90..e930284a3 100644 --- a/google/ads/googleads/v20/services/services/campaign_draft_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_draft_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,10 +36,10 @@ pagers, ) from google.ads.googleads.v20.services.types import campaign_draft_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignDraftServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignDraftServiceClient @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignDraftServiceAsyncClient: The constructed client. """ - return CampaignDraftServiceClient.from_service_account_info.__func__(CampaignDraftServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignDraftServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignDraftServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignDraftServiceAsyncClient: The constructed client. """ - return CampaignDraftServiceClient.from_service_account_file.__func__(CampaignDraftServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignDraftServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignDraftServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -433,10 +442,11 @@ async def promote_campaign_draft( r"""Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v20.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v20/services/services/campaign_draft_service/client.py b/google/ads/googleads/v20/services/services/campaign_draft_service/client.py index 45f147db2..8a8b14643 100644 --- a/google/ads/googleads/v20/services/services/campaign_draft_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_draft_service/client.py @@ -63,10 +63,10 @@ pagers, ) from google.ads.googleads.v20.services.types import campaign_draft_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignDraftServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignDraftServiceGrpcTransport from .transports.grpc_asyncio import CampaignDraftServiceGrpcAsyncIOTransport @@ -152,6 +152,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -365,14 +393,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignDraftServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -380,7 +404,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -412,22 +436,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignDraftServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -899,10 +919,11 @@ def promote_campaign_draft( r"""Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v20.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v20/services/services/campaign_draft_service/pagers.py b/google/ads/googleads/v20/services/services/campaign_draft_service/pagers.py index bd1cad82c..2f47167f7 100644 --- a/google/ads/googleads/v20/services/services/campaign_draft_service/pagers.py +++ b/google/ads/googleads/v20/services/services/campaign_draft_service/pagers.py @@ -37,7 +37,7 @@ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_draft_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore class ListCampaignDraftAsyncErrorsPager: diff --git a/google/ads/googleads/v20/services/services/campaign_draft_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_draft_service/transports/base.py index f50e520c4..ce26bb7cc 100644 --- a/google/ads/googleads/v20/services/services/campaign_draft_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_draft_service/transports/base.py @@ -67,9 +67,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -82,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_draft_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_draft_service/transports/grpc.py index 51043422a..78cb5bf32 100644 --- a/google/ads/googleads/v20/services/services/campaign_draft_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_draft_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -308,9 +309,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -408,10 +410,11 @@ def promote_campaign_draft( Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v20.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v20/services/services/campaign_draft_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_draft_service/transports/grpc_asyncio.py index e6c3e042f..590f66af2 100644 --- a/google/ads/googleads/v20/services/services/campaign_draft_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_draft_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -416,10 +418,11 @@ def promote_campaign_draft( Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v20.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v20/services/services/campaign_group_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_group_service/async_client.py index 99bb77f91..480adbc85 100644 --- a/google/ads/googleads/v20/services/services/campaign_group_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignGroupServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignGroupServiceClient @@ -112,7 +111,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignGroupServiceAsyncClient: The constructed client. """ - return CampaignGroupServiceClient.from_service_account_info.__func__(CampaignGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignGroupServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -128,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignGroupServiceAsyncClient: The constructed client. """ - return CampaignGroupServiceClient.from_service_account_file.__func__(CampaignGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_group_service/client.py b/google/ads/googleads/v20/services/services/campaign_group_service/client.py index 1df34efeb..8dbafb036 100644 --- a/google/ads/googleads/v20/services/services/campaign_group_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_group_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import campaign_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignGroupServiceGrpcTransport from .transports.grpc_asyncio import CampaignGroupServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -339,14 +367,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignGroupServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -354,7 +378,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -386,22 +410,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignGroupServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_group_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_group_service/transports/base.py index 045ea6d2a..9e83a65a8 100644 --- a/google/ads/googleads/v20/services/services/campaign_group_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_group_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_group_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_group_service/transports/grpc.py index d6e100541..56490d171 100644 --- a/google/ads/googleads/v20/services/services/campaign_group_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_group_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_group_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_group_service/transports/grpc_asyncio.py index 7fecbfed5..c78b5ed0a 100644 --- a/google/ads/googleads/v20/services/services/campaign_group_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_group_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_label_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_label_service/async_client.py index 986234349..1fa94785e 100644 --- a/google/ads/googleads/v20/services/services/campaign_label_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignLabelServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignLabelServiceAsyncClient: The constructed client. """ - return CampaignLabelServiceClient.from_service_account_info.__func__(CampaignLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignLabelServiceAsyncClient: The constructed client. """ - return CampaignLabelServiceClient.from_service_account_file.__func__(CampaignLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_label_service/client.py b/google/ads/googleads/v20/services/services/campaign_label_service/client.py index f2f714c6c..8366855ce 100644 --- a/google/ads/googleads/v20/services/services/campaign_label_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import campaign_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignLabelServiceGrpcTransport from .transports.grpc_asyncio import CampaignLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -378,14 +406,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -393,7 +417,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -425,22 +449,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_label_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_label_service/transports/base.py index 41c992b0c..63541c2e2 100644 --- a/google/ads/googleads/v20/services/services/campaign_label_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_label_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_label_service/transports/grpc.py index 0d1000c63..19f37f9c2 100644 --- a/google/ads/googleads/v20/services/services/campaign_label_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_label_service/transports/grpc_asyncio.py index f6a72f3ac..9946175f4 100644 --- a/google/ads/googleads/v20/services/services/campaign_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/async_client.py index 3774eb886..b236656e5 100644 --- a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignLifecycleGoalServiceAsyncClient: The constructed client. """ - return CampaignLifecycleGoalServiceClient.from_service_account_info.__func__(CampaignLifecycleGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignLifecycleGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignLifecycleGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignLifecycleGoalServiceAsyncClient: The constructed client. """ - return CampaignLifecycleGoalServiceClient.from_service_account_file.__func__(CampaignLifecycleGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignLifecycleGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignLifecycleGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -337,7 +346,7 @@ async def configure_campaign_lifecycle_goals( Args: request (Optional[Union[google.ads.googleads.v20.services.types.ConfigureCampaignLifecycleGoalsRequest, dict]]): The request object. Request message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v20.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. customer_id (:class:`str`): Required. The ID of the customer performing the upload. @@ -363,7 +372,7 @@ async def configure_campaign_lifecycle_goals( Returns: google.ads.googleads.v20.services.types.ConfigureCampaignLifecycleGoalsResponse: Response message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v20.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/client.py b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/client.py index 54654db85..54bb4a0d1 100644 --- a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -355,14 +383,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignLifecycleGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -370,7 +394,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -402,22 +426,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignLifecycleGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -801,7 +821,7 @@ def configure_campaign_lifecycle_goals( Args: request (Union[google.ads.googleads.v20.services.types.ConfigureCampaignLifecycleGoalsRequest, dict]): The request object. Request message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v20.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. customer_id (str): Required. The ID of the customer performing the upload. @@ -827,7 +847,7 @@ def configure_campaign_lifecycle_goals( Returns: google.ads.googleads.v20.services.types.ConfigureCampaignLifecycleGoalsResponse: Response message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v20.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/base.py index c9e2ad16f..62c083a2b 100644 --- a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/grpc.py index 0125b568b..294f5f191 100644 --- a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/grpc_asyncio.py index 542a04e3d..79914ee56 100644 --- a/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_lifecycle_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_service/async_client.py index 709933b41..fc8395f8e 100644 --- a/google/ads/googleads/v20/services/services/campaign_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignServiceClient @@ -148,7 +147,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignServiceAsyncClient: The constructed client. """ - return CampaignServiceClient.from_service_account_info.__func__(CampaignServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(CampaignServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -164,7 +166,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignServiceAsyncClient: The constructed client. """ - return CampaignServiceClient.from_service_account_file.__func__(CampaignServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_service/client.py b/google/ads/googleads/v20/services/services/campaign_service/client.py index b1770f5af..51afd4015 100644 --- a/google/ads/googleads/v20/services/services/campaign_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import campaign_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignServiceGrpcTransport from .transports.grpc_asyncio import CampaignServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -479,14 +507,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = CampaignServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -494,7 +516,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -526,22 +548,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = CampaignServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_service/transports/base.py index ed91733d3..ebdd887c9 100644 --- a/google/ads/googleads/v20/services/services/campaign_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_service/transports/grpc.py index af9c6e701..e121362f7 100644 --- a/google/ads/googleads/v20/services/services/campaign_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_service/transports/grpc_asyncio.py index b163da5c5..f175deef5 100644 --- a/google/ads/googleads/v20/services/services/campaign_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_shared_set_service/async_client.py b/google/ads/googleads/v20/services/services/campaign_shared_set_service/async_client.py index b075307de..f5422f2f8 100644 --- a/google/ads/googleads/v20/services/services/campaign_shared_set_service/async_client.py +++ b/google/ads/googleads/v20/services/services/campaign_shared_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import campaign_shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignSharedSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignSharedSetServiceAsyncClient: The constructed client. """ - return CampaignSharedSetServiceClient.from_service_account_info.__func__(CampaignSharedSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignSharedSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignSharedSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignSharedSetServiceAsyncClient: The constructed client. """ - return CampaignSharedSetServiceClient.from_service_account_file.__func__(CampaignSharedSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignSharedSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignSharedSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/campaign_shared_set_service/client.py b/google/ads/googleads/v20/services/services/campaign_shared_set_service/client.py index b266930c4..dc1d629e3 100644 --- a/google/ads/googleads/v20/services/services/campaign_shared_set_service/client.py +++ b/google/ads/googleads/v20/services/services/campaign_shared_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import campaign_shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignSharedSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignSharedSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignSharedSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/base.py b/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/base.py index b23927818..39937e070 100644 --- a/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/grpc.py b/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/grpc.py index f98c25bb7..a84f88945 100644 --- a/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/grpc_asyncio.py index ca7c71f15..85ddaf083 100644 --- a/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/campaign_shared_set_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/content_creator_insights_service/async_client.py b/google/ads/googleads/v20/services/services/content_creator_insights_service/async_client.py index 7a29341d7..89d81d2c3 100644 --- a/google/ads/googleads/v20/services/services/content_creator_insights_service/async_client.py +++ b/google/ads/googleads/v20/services/services/content_creator_insights_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -116,7 +115,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ContentCreatorInsightsServiceAsyncClient: The constructed client. """ - return ContentCreatorInsightsServiceClient.from_service_account_info.__func__(ContentCreatorInsightsServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ContentCreatorInsightsServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ContentCreatorInsightsServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,7 +136,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ContentCreatorInsightsServiceAsyncClient: The constructed client. """ - return ContentCreatorInsightsServiceClient.from_service_account_file.__func__(ContentCreatorInsightsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ContentCreatorInsightsServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ContentCreatorInsightsServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -405,7 +414,7 @@ async def generate_trending_insights( Args: request (Optional[Union[google.ads.googleads.v20.services.types.GenerateTrendingInsightsRequest, dict]]): The request object. Request message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v20.services.ContentCreatorInsightsService.GenerateTrendingInsights]. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -417,7 +426,7 @@ async def generate_trending_insights( Returns: google.ads.googleads.v20.services.types.GenerateTrendingInsightsResponse: Response message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v20.services.ContentCreatorInsightsService.GenerateTrendingInsights]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/content_creator_insights_service/client.py b/google/ads/googleads/v20/services/services/content_creator_insights_service/client.py index 96b9d4e87..b3bc85367 100644 --- a/google/ads/googleads/v20/services/services/content_creator_insights_service/client.py +++ b/google/ads/googleads/v20/services/services/content_creator_insights_service/client.py @@ -148,6 +148,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -319,14 +347,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ContentCreatorInsightsServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -334,7 +358,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -366,22 +390,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ContentCreatorInsightsServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -839,7 +859,7 @@ def generate_trending_insights( Args: request (Union[google.ads.googleads.v20.services.types.GenerateTrendingInsightsRequest, dict]): The request object. Request message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v20.services.ContentCreatorInsightsService.GenerateTrendingInsights]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -851,7 +871,7 @@ def generate_trending_insights( Returns: google.ads.googleads.v20.services.types.GenerateTrendingInsightsResponse: Response message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v20.services.ContentCreatorInsightsService.GenerateTrendingInsights]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/base.py b/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/base.py index 44214aa57..334009a8a 100644 --- a/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/grpc.py b/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/grpc.py index 7211b1fa3..7c2de90f4 100644 --- a/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/grpc_asyncio.py index 1ac690b1e..52b9514d2 100644 --- a/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/content_creator_insights_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_action_service/async_client.py b/google/ads/googleads/v20/services/services/conversion_action_service/async_client.py index 84fcd75c8..337fe3637 100644 --- a/google/ads/googleads/v20/services/services/conversion_action_service/async_client.py +++ b/google/ads/googleads/v20/services/services/conversion_action_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import conversion_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -119,7 +118,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionActionServiceAsyncClient: The constructed client. """ - return ConversionActionServiceClient.from_service_account_info.__func__(ConversionActionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionActionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionActionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -135,7 +139,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionActionServiceAsyncClient: The constructed client. """ - return ConversionActionServiceClient.from_service_account_file.__func__(ConversionActionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionActionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionActionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/conversion_action_service/client.py b/google/ads/googleads/v20/services/services/conversion_action_service/client.py index 81e751937..18d42c67d 100644 --- a/google/ads/googleads/v20/services/services/conversion_action_service/client.py +++ b/google/ads/googleads/v20/services/services/conversion_action_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import conversion_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -357,14 +385,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionActionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -372,7 +396,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -404,22 +428,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionActionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/conversion_action_service/transports/base.py b/google/ads/googleads/v20/services/services/conversion_action_service/transports/base.py index f3126d813..a02e95a26 100644 --- a/google/ads/googleads/v20/services/services/conversion_action_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/conversion_action_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/conversion_action_service/transports/grpc.py b/google/ads/googleads/v20/services/services/conversion_action_service/transports/grpc.py index 3897ff7eb..b9da8d03e 100644 --- a/google/ads/googleads/v20/services/services/conversion_action_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/conversion_action_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_action_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/conversion_action_service/transports/grpc_asyncio.py index 4c819ff25..ec7ad0866 100644 --- a/google/ads/googleads/v20/services/services/conversion_action_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/conversion_action_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/async_client.py b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/async_client.py index 35e6b9721..ca605d892 100644 --- a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/async_client.py +++ b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( conversion_adjustment_upload_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionAdjustmentUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionAdjustmentUploadServiceAsyncClient: The constructed client. """ - return ConversionAdjustmentUploadServiceClient.from_service_account_info.__func__(ConversionAdjustmentUploadServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionAdjustmentUploadServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionAdjustmentUploadServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionAdjustmentUploadServiceAsyncClient: The constructed client. """ - return ConversionAdjustmentUploadServiceClient.from_service_account_file.__func__(ConversionAdjustmentUploadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionAdjustmentUploadServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionAdjustmentUploadServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/client.py b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/client.py index 6bb86ac05..733aa43e5 100644 --- a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/client.py +++ b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( conversion_adjustment_upload_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionAdjustmentUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -326,14 +354,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionAdjustmentUploadServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -341,7 +365,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -373,22 +397,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionAdjustmentUploadServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/base.py b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/base.py index b5f0c353d..9212d5e4f 100644 --- a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/grpc.py b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/grpc.py index 70e032a7f..faaae7c43 100644 --- a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/grpc_asyncio.py index a361edf24..9f4051fa6 100644 --- a/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/conversion_adjustment_upload_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/async_client.py b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/async_client.py index c6d77f5c1..1e1e77ec5 100644 --- a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/async_client.py +++ b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( conversion_custom_variable_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionCustomVariableServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionCustomVariableServiceAsyncClient: The constructed client. """ - return ConversionCustomVariableServiceClient.from_service_account_info.__func__(ConversionCustomVariableServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionCustomVariableServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionCustomVariableServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionCustomVariableServiceAsyncClient: The constructed client. """ - return ConversionCustomVariableServiceClient.from_service_account_file.__func__(ConversionCustomVariableServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionCustomVariableServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionCustomVariableServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/client.py b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/client.py index fc307047e..104d54c3a 100644 --- a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/client.py +++ b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( conversion_custom_variable_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionCustomVariableServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -361,14 +389,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionCustomVariableServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -376,7 +400,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -408,22 +432,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionCustomVariableServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/base.py b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/base.py index 90f12aecd..2a4bfcb0a 100644 --- a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/grpc.py b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/grpc.py index 96df75c76..cb29fd7fe 100644 --- a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/grpc_asyncio.py index 44be4fa87..7dbfdbaa8 100644 --- a/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/conversion_custom_variable_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/async_client.py b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/async_client.py index b8d423929..c6fea7a97 100644 --- a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/async_client.py +++ b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -134,7 +133,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionGoalCampaignConfigServiceAsyncClient: The constructed client. """ - return ConversionGoalCampaignConfigServiceClient.from_service_account_info.__func__(ConversionGoalCampaignConfigServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionGoalCampaignConfigServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionGoalCampaignConfigServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -150,7 +157,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionGoalCampaignConfigServiceAsyncClient: The constructed client. """ - return ConversionGoalCampaignConfigServiceClient.from_service_account_file.__func__(ConversionGoalCampaignConfigServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionGoalCampaignConfigServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionGoalCampaignConfigServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/client.py b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/client.py index f9d3ff5b4..170dc6c99 100644 --- a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/client.py +++ b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/client.py @@ -156,6 +156,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -387,14 +415,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionGoalCampaignConfigServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -402,7 +426,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -434,22 +458,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionGoalCampaignConfigServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/base.py b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/base.py index 6f7ab194a..ada659fdf 100644 --- a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/grpc.py b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/grpc.py index 2fcf26232..413a45ec4 100644 --- a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/grpc_asyncio.py index 75b02fa60..f8a659f53 100644 --- a/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/conversion_goal_campaign_config_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_upload_service/async_client.py b/google/ads/googleads/v20/services/services/conversion_upload_service/async_client.py index 9695df0e7..5e311f518 100644 --- a/google/ads/googleads/v20/services/services/conversion_upload_service/async_client.py +++ b/google/ads/googleads/v20/services/services/conversion_upload_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import conversion_upload_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionUploadServiceAsyncClient: The constructed client. """ - return ConversionUploadServiceClient.from_service_account_info.__func__(ConversionUploadServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionUploadServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionUploadServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionUploadServiceAsyncClient: The constructed client. """ - return ConversionUploadServiceClient.from_service_account_file.__func__(ConversionUploadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionUploadServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionUploadServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/conversion_upload_service/client.py b/google/ads/googleads/v20/services/services/conversion_upload_service/client.py index 95893a043..3c393bac7 100644 --- a/google/ads/googleads/v20/services/services/conversion_upload_service/client.py +++ b/google/ads/googleads/v20/services/services/conversion_upload_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import conversion_upload_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -342,14 +370,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionUploadServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -357,7 +381,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -389,22 +413,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionUploadServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/conversion_upload_service/transports/base.py b/google/ads/googleads/v20/services/services/conversion_upload_service/transports/base.py index 9e1bb4cf3..da96f92ab 100644 --- a/google/ads/googleads/v20/services/services/conversion_upload_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/conversion_upload_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/conversion_upload_service/transports/grpc.py b/google/ads/googleads/v20/services/services/conversion_upload_service/transports/grpc.py index 3f926928a..578d10242 100644 --- a/google/ads/googleads/v20/services/services/conversion_upload_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/conversion_upload_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_upload_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/conversion_upload_service/transports/grpc_asyncio.py index 252e85bb0..ce3c4e0b1 100644 --- a/google/ads/googleads/v20/services/services/conversion_upload_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/conversion_upload_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_service/async_client.py b/google/ads/googleads/v20/services/services/conversion_value_rule_service/async_client.py index 527ab5bee..270a9bad0 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_service/async_client.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( conversion_value_rule_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleServiceTransport, DEFAULT_CLIENT_INFO, @@ -141,7 +140,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionValueRuleServiceAsyncClient: The constructed client. """ - return ConversionValueRuleServiceClient.from_service_account_info.__func__(ConversionValueRuleServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionValueRuleServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionValueRuleServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -157,7 +161,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionValueRuleServiceAsyncClient: The constructed client. """ - return ConversionValueRuleServiceClient.from_service_account_file.__func__(ConversionValueRuleServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionValueRuleServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionValueRuleServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_service/client.py b/google/ads/googleads/v20/services/services/conversion_value_rule_service/client.py index af04010c6..ccba4f47d 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_service/client.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( conversion_value_rule_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -418,14 +446,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionValueRuleServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -433,7 +457,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -465,22 +489,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionValueRuleServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/base.py b/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/base.py index 4632a1ee1..774949cbf 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/grpc.py b/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/grpc.py index 516fe54cb..c6a6a6138 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/grpc_asyncio.py index 1bd9e3508..843b4c10d 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/async_client.py b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/async_client.py index 7b401aaf1..9b6f904f8 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/async_client.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( conversion_value_rule_set_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -137,7 +136,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionValueRuleSetServiceAsyncClient: The constructed client. """ - return ConversionValueRuleSetServiceClient.from_service_account_info.__func__(ConversionValueRuleSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionValueRuleSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionValueRuleSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -153,7 +157,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionValueRuleSetServiceAsyncClient: The constructed client. """ - return ConversionValueRuleSetServiceClient.from_service_account_file.__func__(ConversionValueRuleSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionValueRuleSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionValueRuleSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/client.py b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/client.py index 43b577f19..b287d763c 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/client.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( conversion_value_rule_set_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -401,14 +429,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionValueRuleSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -416,7 +440,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -448,22 +472,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionValueRuleSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/base.py b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/base.py index 95efd9784..b84aac68a 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/grpc.py b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/grpc.py index 48f39d469..26aa9d135 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/grpc_asyncio.py index c0c0f099e..2b192b53b 100644 --- a/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/conversion_value_rule_set_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/custom_audience_service/async_client.py b/google/ads/googleads/v20/services/services/custom_audience_service/async_client.py index e37d27177..3f03736de 100644 --- a/google/ads/googleads/v20/services/services/custom_audience_service/async_client.py +++ b/google/ads/googleads/v20/services/services/custom_audience_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomAudienceServiceAsyncClient: The constructed client. """ - return CustomAudienceServiceClient.from_service_account_info.__func__(CustomAudienceServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomAudienceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomAudienceServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomAudienceServiceAsyncClient: The constructed client. """ - return CustomAudienceServiceClient.from_service_account_file.__func__(CustomAudienceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomAudienceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomAudienceServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/custom_audience_service/client.py b/google/ads/googleads/v20/services/services/custom_audience_service/client.py index b720cd1cb..896f0661a 100644 --- a/google/ads/googleads/v20/services/services/custom_audience_service/client.py +++ b/google/ads/googleads/v20/services/services/custom_audience_service/client.py @@ -145,6 +145,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -336,14 +364,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomAudienceServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -351,7 +375,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -383,22 +407,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomAudienceServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/custom_audience_service/transports/base.py b/google/ads/googleads/v20/services/services/custom_audience_service/transports/base.py index b6572f21c..32a9c3a04 100644 --- a/google/ads/googleads/v20/services/services/custom_audience_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/custom_audience_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/custom_audience_service/transports/grpc.py b/google/ads/googleads/v20/services/services/custom_audience_service/transports/grpc.py index 00fb1eb6e..a6a31e7b0 100644 --- a/google/ads/googleads/v20/services/services/custom_audience_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/custom_audience_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/custom_audience_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/custom_audience_service/transports/grpc_asyncio.py index b257257b3..c077c462f 100644 --- a/google/ads/googleads/v20/services/services/custom_audience_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/custom_audience_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/async_client.py b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/async_client.py index 641a3a009..b5b36a6ea 100644 --- a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/async_client.py +++ b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomConversionGoalServiceAsyncClient: The constructed client. """ - return CustomConversionGoalServiceClient.from_service_account_info.__func__(CustomConversionGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomConversionGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomConversionGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomConversionGoalServiceAsyncClient: The constructed client. """ - return CustomConversionGoalServiceClient.from_service_account_file.__func__(CustomConversionGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomConversionGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomConversionGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/client.py b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/client.py index 7adb837da..0463230ca 100644 --- a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/client.py +++ b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -365,14 +393,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomConversionGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -380,7 +404,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -412,22 +436,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomConversionGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/base.py b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/base.py index 8991ffac3..04d6b4a53 100644 --- a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/grpc.py b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/grpc.py index 1e1f90b43..43dc455ef 100644 --- a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/grpc_asyncio.py index baf6c6418..10a28a980 100644 --- a/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/custom_conversion_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/custom_interest_service/async_client.py b/google/ads/googleads/v20/services/services/custom_interest_service/async_client.py index 6fa64b4bd..ae584eb70 100644 --- a/google/ads/googleads/v20/services/services/custom_interest_service/async_client.py +++ b/google/ads/googleads/v20/services/services/custom_interest_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomInterestServiceAsyncClient: The constructed client. """ - return CustomInterestServiceClient.from_service_account_info.__func__(CustomInterestServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomInterestServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomInterestServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomInterestServiceAsyncClient: The constructed client. """ - return CustomInterestServiceClient.from_service_account_file.__func__(CustomInterestServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomInterestServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomInterestServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/custom_interest_service/client.py b/google/ads/googleads/v20/services/services/custom_interest_service/client.py index 71d8c4ff7..f2e9003ae 100644 --- a/google/ads/googleads/v20/services/services/custom_interest_service/client.py +++ b/google/ads/googleads/v20/services/services/custom_interest_service/client.py @@ -145,6 +145,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -336,14 +364,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomInterestServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -351,7 +375,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -383,22 +407,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomInterestServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/custom_interest_service/transports/base.py b/google/ads/googleads/v20/services/services/custom_interest_service/transports/base.py index 1031ab9b7..eb9903c8d 100644 --- a/google/ads/googleads/v20/services/services/custom_interest_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/custom_interest_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/custom_interest_service/transports/grpc.py b/google/ads/googleads/v20/services/services/custom_interest_service/transports/grpc.py index c60d1bb2d..b96896850 100644 --- a/google/ads/googleads/v20/services/services/custom_interest_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/custom_interest_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/custom_interest_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/custom_interest_service/transports/grpc_asyncio.py index e8a7093ef..fc4ab95f3 100644 --- a/google/ads/googleads/v20/services/services/custom_interest_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/custom_interest_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_asset_service/async_client.py b/google/ads/googleads/v20/services/services/customer_asset_service/async_client.py index b31f360e4..971ee7d40 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import customer_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import CustomerAssetServiceClient @@ -114,7 +113,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerAssetServiceAsyncClient: The constructed client. """ - return CustomerAssetServiceClient.from_service_account_info.__func__(CustomerAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +134,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerAssetServiceAsyncClient: The constructed client. """ - return CustomerAssetServiceClient.from_service_account_file.__func__(CustomerAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_asset_service/client.py b/google/ads/googleads/v20/services/services/customer_asset_service/client.py index b364625f3..c6d10144d 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import customer_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CustomerAssetServiceGrpcTransport from .transports.grpc_asyncio import CustomerAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -358,14 +386,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -373,7 +397,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -405,22 +429,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_asset_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_asset_service/transports/base.py index 569e7b8ab..62e7a54b0 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_asset_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_asset_service/transports/grpc.py index 3b262c383..4555a6487 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_asset_service/transports/grpc_asyncio.py index 5a5bc2e27..e0a0f6dc9 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_asset_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_asset_set_service/async_client.py b/google/ads/googleads/v20/services/services/customer_asset_set_service/async_client.py index 680423c6c..cd7a6df43 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_set_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import customer_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerAssetSetServiceAsyncClient: The constructed client. """ - return CustomerAssetSetServiceClient.from_service_account_info.__func__(CustomerAssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerAssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerAssetSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerAssetSetServiceAsyncClient: The constructed client. """ - return CustomerAssetSetServiceClient.from_service_account_file.__func__(CustomerAssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerAssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerAssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_asset_set_service/client.py b/google/ads/googleads/v20/services/services/customer_asset_set_service/client.py index e55ab3503..a166aecde 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_set_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import customer_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -379,14 +407,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerAssetSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -394,7 +418,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -426,22 +450,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerAssetSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/base.py index 909df06ea..b1afe3ba1 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/grpc.py index 0704d8484..65f11c62c 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/grpc_asyncio.py index 7b8fbe31b..931e82062 100644 --- a/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_asset_set_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_client_link_service/async_client.py b/google/ads/googleads/v20/services/services/customer_client_link_service/async_client.py index db734068e..f25c8af4f 100644 --- a/google/ads/googleads/v20/services/services/customer_client_link_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_client_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerClientLinkServiceAsyncClient: The constructed client. """ - return CustomerClientLinkServiceClient.from_service_account_info.__func__(CustomerClientLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerClientLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerClientLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerClientLinkServiceAsyncClient: The constructed client. """ - return CustomerClientLinkServiceClient.from_service_account_file.__func__(CustomerClientLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerClientLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerClientLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_client_link_service/client.py b/google/ads/googleads/v20/services/services/customer_client_link_service/client.py index 089f1b451..054ef6df3 100644 --- a/google/ads/googleads/v20/services/services/customer_client_link_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_client_link_service/client.py @@ -142,6 +142,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -350,14 +378,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerClientLinkServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -365,7 +389,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -397,22 +421,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerClientLinkServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_client_link_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_client_link_service/transports/base.py index ba869732f..8fbe416da 100644 --- a/google/ads/googleads/v20/services/services/customer_client_link_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_client_link_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_client_link_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_client_link_service/transports/grpc.py index 9c54e1ba4..9f472b444 100644 --- a/google/ads/googleads/v20/services/services/customer_client_link_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_client_link_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_client_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_client_link_service/transports/grpc_asyncio.py index a0e6f9775..eb5074e99 100644 --- a/google/ads/googleads/v20/services/services/customer_client_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_client_link_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/async_client.py b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/async_client.py index c438c84ee..3d1b70689 100644 --- a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerConversionGoalServiceAsyncClient: The constructed client. """ - return CustomerConversionGoalServiceClient.from_service_account_info.__func__(CustomerConversionGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerConversionGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerConversionGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerConversionGoalServiceAsyncClient: The constructed client. """ - return CustomerConversionGoalServiceClient.from_service_account_file.__func__(CustomerConversionGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerConversionGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerConversionGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/client.py b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/client.py index 8db02f8b7..3fd29c5e6 100644 --- a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -347,14 +375,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerConversionGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -362,7 +386,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -394,22 +418,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerConversionGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/base.py index 6e8b476b8..ec6390a2b 100644 --- a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/grpc.py index 063131e48..f1bdd8a17 100644 --- a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/grpc_asyncio.py index 1bf809227..b1d5321d2 100644 --- a/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_conversion_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_customizer_service/async_client.py b/google/ads/googleads/v20/services/services/customer_customizer_service/async_client.py index b2943ac30..0ff72f282 100644 --- a/google/ads/googleads/v20/services/services/customer_customizer_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import customer_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerCustomizerServiceAsyncClient: The constructed client. """ - return CustomerCustomizerServiceClient.from_service_account_info.__func__(CustomerCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerCustomizerServiceAsyncClient: The constructed client. """ - return CustomerCustomizerServiceClient.from_service_account_file.__func__(CustomerCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerCustomizerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_customizer_service/client.py b/google/ads/googleads/v20/services/services/customer_customizer_service/client.py index 91f74fac6..ee2882a53 100644 --- a/google/ads/googleads/v20/services/services/customer_customizer_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_customizer_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import customer_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -364,14 +392,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -379,7 +403,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -411,22 +435,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_customizer_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_customizer_service/transports/base.py index d9d78279e..cabe241f8 100644 --- a/google/ads/googleads/v20/services/services/customer_customizer_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_customizer_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_customizer_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_customizer_service/transports/grpc.py index 6a00a2727..73f492a72 100644 --- a/google/ads/googleads/v20/services/services/customer_customizer_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_customizer_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_customizer_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_customizer_service/transports/grpc_asyncio.py index 52eb84eac..08bf65f8c 100644 --- a/google/ads/googleads/v20/services/services/customer_customizer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_customizer_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_label_service/async_client.py b/google/ads/googleads/v20/services/services/customer_label_service/async_client.py index 65a5fd3cd..80879c047 100644 --- a/google/ads/googleads/v20/services/services/customer_label_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import customer_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import CustomerLabelServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerLabelServiceAsyncClient: The constructed client. """ - return CustomerLabelServiceClient.from_service_account_info.__func__(CustomerLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerLabelServiceAsyncClient: The constructed client. """ - return CustomerLabelServiceClient.from_service_account_file.__func__(CustomerLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_label_service/client.py b/google/ads/googleads/v20/services/services/customer_label_service/client.py index 609347427..b99cfa736 100644 --- a/google/ads/googleads/v20/services/services/customer_label_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import customer_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CustomerLabelServiceGrpcTransport from .transports.grpc_asyncio import CustomerLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -371,14 +399,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -386,7 +410,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -418,22 +442,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_label_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_label_service/transports/base.py index ccdb72eb6..84bba667b 100644 --- a/google/ads/googleads/v20/services/services/customer_label_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_label_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_label_service/transports/grpc.py index ce35a00b7..d53bbf5df 100644 --- a/google/ads/googleads/v20/services/services/customer_label_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_label_service/transports/grpc_asyncio.py index d25ddc71c..fdc8454e6 100644 --- a/google/ads/googleads/v20/services/services/customer_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/async_client.py b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/async_client.py index 9974d84d3..d25711f82 100644 --- a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerLifecycleGoalServiceAsyncClient: The constructed client. """ - return CustomerLifecycleGoalServiceClient.from_service_account_info.__func__(CustomerLifecycleGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerLifecycleGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerLifecycleGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerLifecycleGoalServiceAsyncClient: The constructed client. """ - return CustomerLifecycleGoalServiceClient.from_service_account_file.__func__(CustomerLifecycleGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerLifecycleGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerLifecycleGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -337,7 +346,7 @@ async def configure_customer_lifecycle_goals( Args: request (Optional[Union[google.ads.googleads.v20.services.types.ConfigureCustomerLifecycleGoalsRequest, dict]]): The request object. Request message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v20.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. customer_id (:class:`str`): Required. The ID of the customer performing the upload. @@ -363,7 +372,7 @@ async def configure_customer_lifecycle_goals( Returns: google.ads.googleads.v20.services.types.ConfigureCustomerLifecycleGoalsResponse: Response message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v20.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/client.py b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/client.py index 111682e18..81810e162 100644 --- a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -347,14 +375,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerLifecycleGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -362,7 +386,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -394,22 +418,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerLifecycleGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -793,7 +813,7 @@ def configure_customer_lifecycle_goals( Args: request (Union[google.ads.googleads.v20.services.types.ConfigureCustomerLifecycleGoalsRequest, dict]): The request object. Request message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v20.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. customer_id (str): Required. The ID of the customer performing the upload. @@ -819,7 +839,7 @@ def configure_customer_lifecycle_goals( Returns: google.ads.googleads.v20.services.types.ConfigureCustomerLifecycleGoalsResponse: Response message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v20.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/base.py index 6699c0cac..f7e125bd5 100644 --- a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/grpc.py index f3b7891e7..068269481 100644 --- a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/grpc_asyncio.py index 4ecb111b5..f4898073b 100644 --- a/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_lifecycle_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_manager_link_service/async_client.py b/google/ads/googleads/v20/services/services/customer_manager_link_service/async_client.py index 3999f89bf..4d4424d1a 100644 --- a/google/ads/googleads/v20/services/services/customer_manager_link_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_manager_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerManagerLinkServiceAsyncClient: The constructed client. """ - return CustomerManagerLinkServiceClient.from_service_account_info.__func__(CustomerManagerLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerManagerLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerManagerLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerManagerLinkServiceAsyncClient: The constructed client. """ - return CustomerManagerLinkServiceClient.from_service_account_file.__func__(CustomerManagerLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerManagerLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerManagerLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_manager_link_service/client.py b/google/ads/googleads/v20/services/services/customer_manager_link_service/client.py index 7727aaeed..770748ff2 100644 --- a/google/ads/googleads/v20/services/services/customer_manager_link_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_manager_link_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -362,14 +390,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerManagerLinkServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -377,7 +401,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -409,22 +433,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerManagerLinkServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/base.py index 512a749e4..22dac67b0 100644 --- a/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/grpc.py index 07c205adb..c56d0c746 100644 --- a/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/grpc_asyncio.py index a4fadcde3..caadb0511 100644 --- a/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_manager_link_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/async_client.py b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/async_client.py index 31bbaf703..6ea30bf19 100644 --- a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( customer_negative_criterion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerNegativeCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerNegativeCriterionServiceAsyncClient: The constructed client. """ - return CustomerNegativeCriterionServiceClient.from_service_account_info.__func__(CustomerNegativeCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerNegativeCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerNegativeCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerNegativeCriterionServiceAsyncClient: The constructed client. """ - return CustomerNegativeCriterionServiceClient.from_service_account_file.__func__(CustomerNegativeCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerNegativeCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerNegativeCriterionServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/client.py b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/client.py index 257b01f70..a08f1cf3c 100644 --- a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( customer_negative_criterion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerNegativeCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -364,14 +392,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerNegativeCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -379,7 +403,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -411,22 +435,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerNegativeCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/base.py index 3d5df6dfb..957196539 100644 --- a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/grpc.py index 9deb732e3..a7f7f1c13 100644 --- a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/grpc_asyncio.py index 799d18ed3..5265cf982 100644 --- a/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_negative_criterion_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_service/async_client.py b/google/ads/googleads/v20/services/services/customer_service/async_client.py index 680c967d8..82c7c0eb7 100644 --- a/google/ads/googleads/v20/services/services/customer_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -114,7 +113,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerServiceAsyncClient: The constructed client. """ - return CustomerServiceClient.from_service_account_info.__func__(CustomerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(CustomerServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerServiceAsyncClient: The constructed client. """ - return CustomerServiceClient.from_service_account_file.__func__(CustomerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_service/client.py b/google/ads/googleads/v20/services/services/customer_service/client.py index cf9dad11c..7b9687cc8 100644 --- a/google/ads/googleads/v20/services/services/customer_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_service/client.py @@ -134,6 +134,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -340,14 +368,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = CustomerServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -355,7 +377,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -387,22 +409,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = CustomerServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_service/transports/base.py index 7dc8da679..24ded5f2d 100644 --- a/google/ads/googleads/v20/services/services/customer_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_service/transports/grpc.py index 5eaad2d39..444b6ea16 100644 --- a/google/ads/googleads/v20/services/services/customer_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_service/transports/grpc_asyncio.py index 6b90e3b24..4409e638f 100644 --- a/google/ads/googleads/v20/services/services/customer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py index 4a4cb4840..3e36c53a7 100644 --- a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( customer_sk_ad_network_conversion_value_schema_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerSkAdNetworkConversionValueSchemaServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient: The constructed client. """ - return CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_info.__func__(CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +146,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient: The constructed client. """ - return CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_file.__func__(CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py index ffe1cac4b..95a4034c2 100644 --- a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py @@ -52,7 +52,7 @@ from google.ads.googleads.v20.services.types import ( customer_sk_ad_network_conversion_value_schema_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerSkAdNetworkConversionValueSchemaServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +383,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +415,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py index a18676300..9f6e90d48 100644 --- a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc.py index f9ad2d8ae..ad74011e7 100644 --- a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc_asyncio.py index 3fbbeebe5..8675c72ff 100644 --- a/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/async_client.py b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/async_client.py index 4c3f77f82..0514fed28 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerUserAccessInvitationServiceAsyncClient: The constructed client. """ - return CustomerUserAccessInvitationServiceClient.from_service_account_info.__func__(CustomerUserAccessInvitationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerUserAccessInvitationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerUserAccessInvitationServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +147,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerUserAccessInvitationServiceAsyncClient: The constructed client. """ - return CustomerUserAccessInvitationServiceClient.from_service_account_file.__func__(CustomerUserAccessInvitationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerUserAccessInvitationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerUserAccessInvitationServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/client.py b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/client.py index 13aec0285..d16207c14 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/client.py @@ -148,6 +148,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -339,14 +367,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerUserAccessInvitationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -354,7 +378,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -386,22 +410,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerUserAccessInvitationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/base.py index 460c5e29f..076529f81 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/grpc.py index e42228b36..5e0a89702 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/grpc.py @@ -170,9 +170,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -313,9 +314,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/grpc_asyncio.py index 386bec24f..fc0d67872 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_invitation_service/transports/grpc_asyncio.py @@ -160,8 +160,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -216,9 +217,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_user_access_service/async_client.py b/google/ads/googleads/v20/services/services/customer_user_access_service/async_client.py index 9643bb83f..0b58d0d98 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerUserAccessServiceAsyncClient: The constructed client. """ - return CustomerUserAccessServiceClient.from_service_account_info.__func__(CustomerUserAccessServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerUserAccessServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerUserAccessServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerUserAccessServiceAsyncClient: The constructed client. """ - return CustomerUserAccessServiceClient.from_service_account_file.__func__(CustomerUserAccessServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerUserAccessServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerUserAccessServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customer_user_access_service/client.py b/google/ads/googleads/v20/services/services/customer_user_access_service/client.py index a916c2973..eec6e01b3 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_service/client.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerUserAccessServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +374,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +406,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerUserAccessServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customer_user_access_service/transports/base.py b/google/ads/googleads/v20/services/services/customer_user_access_service/transports/base.py index 672748d1f..e62d3eed1 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customer_user_access_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customer_user_access_service/transports/grpc.py index 560b7afd4..eccbe0f14 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_service/transports/grpc.py @@ -165,9 +165,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -308,9 +309,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customer_user_access_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customer_user_access_service/transports/grpc_asyncio.py index a0b0da37f..1ba9dea05 100644 --- a/google/ads/googleads/v20/services/services/customer_user_access_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customer_user_access_service/transports/grpc_asyncio.py @@ -155,8 +155,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -211,9 +212,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customizer_attribute_service/async_client.py b/google/ads/googleads/v20/services/services/customizer_attribute_service/async_client.py index 5a97a3147..2037a62a0 100644 --- a/google/ads/googleads/v20/services/services/customizer_attribute_service/async_client.py +++ b/google/ads/googleads/v20/services/services/customizer_attribute_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import customizer_attribute_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomizerAttributeServiceTransport, DEFAULT_CLIENT_INFO, @@ -117,7 +116,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomizerAttributeServiceAsyncClient: The constructed client. """ - return CustomizerAttributeServiceClient.from_service_account_info.__func__(CustomizerAttributeServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomizerAttributeServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomizerAttributeServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -133,7 +137,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomizerAttributeServiceAsyncClient: The constructed client. """ - return CustomizerAttributeServiceClient.from_service_account_file.__func__(CustomizerAttributeServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomizerAttributeServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomizerAttributeServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/customizer_attribute_service/client.py b/google/ads/googleads/v20/services/services/customizer_attribute_service/client.py index d6541c382..334bb7a7d 100644 --- a/google/ads/googleads/v20/services/services/customizer_attribute_service/client.py +++ b/google/ads/googleads/v20/services/services/customizer_attribute_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import customizer_attribute_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomizerAttributeServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomizerAttributeServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +383,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +415,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomizerAttributeServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/base.py b/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/base.py index ff4d5f819..a23c59850 100644 --- a/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/grpc.py b/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/grpc.py index edcf948ca..a44415abc 100644 --- a/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/grpc_asyncio.py index c89dedaff..69c506fa6 100644 --- a/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/customizer_attribute_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/data_link_service/async_client.py b/google/ads/googleads/v20/services/services/data_link_service/async_client.py index 6290f3fa7..a1bc8f89f 100644 --- a/google/ads/googleads/v20/services/services/data_link_service/async_client.py +++ b/google/ads/googleads/v20/services/services/data_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -113,7 +112,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: DataLinkServiceAsyncClient: The constructed client. """ - return DataLinkServiceClient.from_service_account_info.__func__(DataLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + DataLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(DataLinkServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -129,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: DataLinkServiceAsyncClient: The constructed client. """ - return DataLinkServiceClient.from_service_account_file.__func__(DataLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + DataLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + DataLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/data_link_service/client.py b/google/ads/googleads/v20/services/services/data_link_service/client.py index 4249b588d..d70799dfc 100644 --- a/google/ads/googleads/v20/services/services/data_link_service/client.py +++ b/google/ads/googleads/v20/services/services/data_link_service/client.py @@ -139,6 +139,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -332,14 +360,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = DataLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -347,7 +369,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -379,22 +401,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = DataLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/data_link_service/transports/base.py b/google/ads/googleads/v20/services/services/data_link_service/transports/base.py index 0ad38b764..4a609718e 100644 --- a/google/ads/googleads/v20/services/services/data_link_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/data_link_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/data_link_service/transports/grpc.py b/google/ads/googleads/v20/services/services/data_link_service/transports/grpc.py index b92a76866..fefeba5c3 100644 --- a/google/ads/googleads/v20/services/services/data_link_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/data_link_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/data_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/data_link_service/transports/grpc_asyncio.py index bda43819e..4f13f0e0f 100644 --- a/google/ads/googleads/v20/services/services/data_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/data_link_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/experiment_arm_service/async_client.py b/google/ads/googleads/v20/services/services/experiment_arm_service/async_client.py index 0017539f3..1b2661317 100644 --- a/google/ads/googleads/v20/services/services/experiment_arm_service/async_client.py +++ b/google/ads/googleads/v20/services/services/experiment_arm_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import experiment_arm_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentArmServiceTransport, DEFAULT_CLIENT_INFO from .client import ExperimentArmServiceClient @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ExperimentArmServiceAsyncClient: The constructed client. """ - return ExperimentArmServiceClient.from_service_account_info.__func__(ExperimentArmServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ExperimentArmServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ExperimentArmServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ExperimentArmServiceAsyncClient: The constructed client. """ - return ExperimentArmServiceClient.from_service_account_file.__func__(ExperimentArmServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ExperimentArmServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ExperimentArmServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/experiment_arm_service/client.py b/google/ads/googleads/v20/services/services/experiment_arm_service/client.py index 119d53435..dcd069539 100644 --- a/google/ads/googleads/v20/services/services/experiment_arm_service/client.py +++ b/google/ads/googleads/v20/services/services/experiment_arm_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import experiment_arm_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentArmServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ExperimentArmServiceGrpcTransport from .transports.grpc_asyncio import ExperimentArmServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -379,14 +407,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ExperimentArmServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -394,7 +418,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -426,22 +450,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ExperimentArmServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/experiment_arm_service/transports/base.py b/google/ads/googleads/v20/services/services/experiment_arm_service/transports/base.py index cac09beca..dd831097f 100644 --- a/google/ads/googleads/v20/services/services/experiment_arm_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/experiment_arm_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/experiment_arm_service/transports/grpc.py b/google/ads/googleads/v20/services/services/experiment_arm_service/transports/grpc.py index 7cdbb6753..1ccf457ea 100644 --- a/google/ads/googleads/v20/services/services/experiment_arm_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/experiment_arm_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/experiment_arm_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/experiment_arm_service/transports/grpc_asyncio.py index aa1838d8f..19da1c7e0 100644 --- a/google/ads/googleads/v20/services/services/experiment_arm_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/experiment_arm_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/experiment_service/async_client.py b/google/ads/googleads/v20/services/services/experiment_service/async_client.py index 33ba7b603..c84d1d385 100644 --- a/google/ads/googleads/v20/services/services/experiment_service/async_client.py +++ b/google/ads/googleads/v20/services/services/experiment_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -35,10 +34,10 @@ from google.ads.googleads.v20.services.services.experiment_service import pagers from google.ads.googleads.v20.services.types import experiment_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO from .client import ExperimentServiceClient @@ -124,7 +123,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ExperimentServiceAsyncClient: The constructed client. """ - return ExperimentServiceClient.from_service_account_info.__func__(ExperimentServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ExperimentServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(ExperimentServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ExperimentServiceAsyncClient: The constructed client. """ - return ExperimentServiceClient.from_service_account_file.__func__(ExperimentServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ExperimentServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ExperimentServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/experiment_service/client.py b/google/ads/googleads/v20/services/services/experiment_service/client.py index c52ebc8fd..5f99cfe72 100644 --- a/google/ads/googleads/v20/services/services/experiment_service/client.py +++ b/google/ads/googleads/v20/services/services/experiment_service/client.py @@ -61,10 +61,10 @@ from google.ads.googleads.v20.services.services.experiment_service import pagers from google.ads.googleads.v20.services.types import experiment_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ExperimentServiceGrpcTransport from .transports.grpc_asyncio import ExperimentServiceGrpcAsyncIOTransport @@ -148,6 +148,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -379,14 +407,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = ExperimentServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -394,7 +416,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -426,22 +448,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ExperimentServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/experiment_service/pagers.py b/google/ads/googleads/v20/services/services/experiment_service/pagers.py index a8b961fcb..d38a58a6a 100644 --- a/google/ads/googleads/v20/services/services/experiment_service/pagers.py +++ b/google/ads/googleads/v20/services/services/experiment_service/pagers.py @@ -37,7 +37,7 @@ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import experiment_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore class ListExperimentAsyncErrorsPager: diff --git a/google/ads/googleads/v20/services/services/experiment_service/transports/base.py b/google/ads/googleads/v20/services/services/experiment_service/transports/base.py index 1e61fd0d2..15adee841 100644 --- a/google/ads/googleads/v20/services/services/experiment_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/experiment_service/transports/base.py @@ -28,7 +28,7 @@ from google.ads.googleads.v20.services.types import experiment_service from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/experiment_service/transports/grpc.py b/google/ads/googleads/v20/services/services/experiment_service/transports/grpc.py index de6dcb626..cf91fb190 100644 --- a/google/ads/googleads/v20/services/services/experiment_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/experiment_service/transports/grpc.py @@ -32,7 +32,7 @@ from google.ads.googleads.v20.services.types import experiment_service from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO try: @@ -165,9 +165,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/experiment_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/experiment_service/transports/grpc_asyncio.py index d12aa7a00..6101ccd5c 100644 --- a/google/ads/googleads/v20/services/services/experiment_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/experiment_service/transports/grpc_asyncio.py @@ -33,7 +33,7 @@ from google.ads.googleads.v20.services.types import experiment_service from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO try: @@ -155,8 +155,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -211,9 +212,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/geo_target_constant_service/async_client.py b/google/ads/googleads/v20/services/services/geo_target_constant_service/async_client.py index 3eabdddb2..e425b1492 100644 --- a/google/ads/googleads/v20/services/services/geo_target_constant_service/async_client.py +++ b/google/ads/googleads/v20/services/services/geo_target_constant_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -114,7 +113,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GeoTargetConstantServiceAsyncClient: The constructed client. """ - return GeoTargetConstantServiceClient.from_service_account_info.__func__(GeoTargetConstantServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GeoTargetConstantServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + GeoTargetConstantServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +134,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GeoTargetConstantServiceAsyncClient: The constructed client. """ - return GeoTargetConstantServiceClient.from_service_account_file.__func__(GeoTargetConstantServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GeoTargetConstantServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + GeoTargetConstantServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/geo_target_constant_service/client.py b/google/ads/googleads/v20/services/services/geo_target_constant_service/client.py index 1b51b5351..096116e8e 100644 --- a/google/ads/googleads/v20/services/services/geo_target_constant_service/client.py +++ b/google/ads/googleads/v20/services/services/geo_target_constant_service/client.py @@ -142,6 +142,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -328,14 +356,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + GeoTargetConstantServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -343,7 +367,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -375,22 +399,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + GeoTargetConstantServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/base.py b/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/base.py index 695f7c538..b2dd873e1 100644 --- a/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/grpc.py b/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/grpc.py index 573f071eb..6152999e6 100644 --- a/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/grpc_asyncio.py index 02f1e3295..995a689a0 100644 --- a/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/geo_target_constant_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/google_ads_field_service/async_client.py b/google/ads/googleads/v20/services/services/google_ads_field_service/async_client.py index 43a06e718..97928eef7 100644 --- a/google/ads/googleads/v20/services/services/google_ads_field_service/async_client.py +++ b/google/ads/googleads/v20/services/services/google_ads_field_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GoogleAdsFieldServiceAsyncClient: The constructed client. """ - return GoogleAdsFieldServiceClient.from_service_account_info.__func__(GoogleAdsFieldServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GoogleAdsFieldServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + GoogleAdsFieldServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GoogleAdsFieldServiceAsyncClient: The constructed client. """ - return GoogleAdsFieldServiceClient.from_service_account_file.__func__(GoogleAdsFieldServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GoogleAdsFieldServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + GoogleAdsFieldServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/google_ads_field_service/client.py b/google/ads/googleads/v20/services/services/google_ads_field_service/client.py index 710f7d69a..8c25a567a 100644 --- a/google/ads/googleads/v20/services/services/google_ads_field_service/client.py +++ b/google/ads/googleads/v20/services/services/google_ads_field_service/client.py @@ -139,6 +139,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -325,14 +353,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + GoogleAdsFieldServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -340,7 +364,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -372,22 +396,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + GoogleAdsFieldServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/google_ads_field_service/transports/base.py b/google/ads/googleads/v20/services/services/google_ads_field_service/transports/base.py index b980ea016..f5c230bea 100644 --- a/google/ads/googleads/v20/services/services/google_ads_field_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/google_ads_field_service/transports/base.py @@ -67,9 +67,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -82,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/google_ads_field_service/transports/grpc.py b/google/ads/googleads/v20/services/services/google_ads_field_service/transports/grpc.py index a0ab5f903..246411ad5 100644 --- a/google/ads/googleads/v20/services/services/google_ads_field_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/google_ads_field_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/google_ads_field_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/google_ads_field_service/transports/grpc_asyncio.py index 202556244..0b039d471 100644 --- a/google/ads/googleads/v20/services/services/google_ads_field_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/google_ads_field_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/google_ads_service/async_client.py b/google/ads/googleads/v20/services/services/google_ads_service/async_client.py index 51713ff81..c9a3c885c 100644 --- a/google/ads/googleads/v20/services/services/google_ads_service/async_client.py +++ b/google/ads/googleads/v20/services/services/google_ads_service/async_client.py @@ -34,7 +34,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -44,8 +43,8 @@ from google.ads.googleads.v20.services.services.google_ads_service import pagers from google.ads.googleads.v20.services.types import google_ads_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import GoogleAdsServiceTransport, DEFAULT_CLIENT_INFO from .client import GoogleAdsServiceClient @@ -1047,7 +1046,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GoogleAdsServiceAsyncClient: The constructed client. """ - return GoogleAdsServiceClient.from_service_account_info.__func__(GoogleAdsServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GoogleAdsServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(GoogleAdsServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -1063,7 +1065,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GoogleAdsServiceAsyncClient: The constructed client. """ - return GoogleAdsServiceClient.from_service_account_file.__func__(GoogleAdsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GoogleAdsServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + GoogleAdsServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -1478,9 +1485,9 @@ async def mutate( methods. The only features it offers over calling those methods directly are: - - Atomic transactions - - Temp resource names (described below) - - Somewhat reduced latency over making a series of mutate calls + - Atomic transactions + - Temp resource names (described below) + - Somewhat reduced latency over making a series of mutate calls Note: Only resources that support atomic transactions are included, so this method can't replace all calls to individual @@ -1510,14 +1517,13 @@ async def mutate( Note: - - Resources must be created with a temp name before the name - can be reused. For example, the previous - CampaignBudget+Campaign example would fail if the mutate - order was reversed. - - Temp names are not remembered across requests. - - There's no limit to the number of temp names in a request. - - Each temp name must use a unique negative number, even if the - resource types differ. + - Resources must be created with a temp name before the name can + be reused. For example, the previous CampaignBudget+Campaign + example would fail if the mutate order was reversed. + - Temp names are not remembered across requests. + - There's no limit to the number of temp names in a request. + - Each temp name must use a unique negative number, even if the + resource types differ. Latency ------- diff --git a/google/ads/googleads/v20/services/services/google_ads_service/client.py b/google/ads/googleads/v20/services/services/google_ads_service/client.py index 054641ba7..cf93bb310 100644 --- a/google/ads/googleads/v20/services/services/google_ads_service/client.py +++ b/google/ads/googleads/v20/services/services/google_ads_service/client.py @@ -62,8 +62,8 @@ from google.ads.googleads.v20.services.services.google_ads_service import pagers from google.ads.googleads.v20.services.types import google_ads_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import GoogleAdsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import GoogleAdsServiceGrpcTransport from .transports.grpc_asyncio import GoogleAdsServiceGrpcAsyncIOTransport @@ -147,6 +147,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -3906,14 +3934,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = GoogleAdsServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -3921,7 +3943,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -3953,22 +3975,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = GoogleAdsServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -4549,9 +4565,9 @@ def mutate( methods. The only features it offers over calling those methods directly are: - - Atomic transactions - - Temp resource names (described below) - - Somewhat reduced latency over making a series of mutate calls + - Atomic transactions + - Temp resource names (described below) + - Somewhat reduced latency over making a series of mutate calls Note: Only resources that support atomic transactions are included, so this method can't replace all calls to individual @@ -4581,14 +4597,13 @@ def mutate( Note: - - Resources must be created with a temp name before the name - can be reused. For example, the previous - CampaignBudget+Campaign example would fail if the mutate - order was reversed. - - Temp names are not remembered across requests. - - There's no limit to the number of temp names in a request. - - Each temp name must use a unique negative number, even if the - resource types differ. + - Resources must be created with a temp name before the name can + be reused. For example, the previous CampaignBudget+Campaign + example would fail if the mutate order was reversed. + - Temp names are not remembered across requests. + - There's no limit to the number of temp names in a request. + - Each temp name must use a unique negative number, even if the + resource types differ. Latency ------- diff --git a/google/ads/googleads/v20/services/services/google_ads_service/transports/base.py b/google/ads/googleads/v20/services/services/google_ads_service/transports/base.py index 606489c90..9ea8363d2 100644 --- a/google/ads/googleads/v20/services/services/google_ads_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/google_ads_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/google_ads_service/transports/grpc.py b/google/ads/googleads/v20/services/services/google_ads_service/transports/grpc.py index ee3a2446b..d64e6146b 100644 --- a/google/ads/googleads/v20/services/services/google_ads_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/google_ads_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -427,9 +429,9 @@ def mutate( methods. The only features it offers over calling those methods directly are: - - Atomic transactions - - Temp resource names (described below) - - Somewhat reduced latency over making a series of mutate calls + - Atomic transactions + - Temp resource names (described below) + - Somewhat reduced latency over making a series of mutate calls Note: Only resources that support atomic transactions are included, so this method can't replace all calls to individual @@ -459,14 +461,13 @@ def mutate( Note: - - Resources must be created with a temp name before the name - can be reused. For example, the previous - CampaignBudget+Campaign example would fail if the mutate - order was reversed. - - Temp names are not remembered across requests. - - There's no limit to the number of temp names in a request. - - Each temp name must use a unique negative number, even if the - resource types differ. + - Resources must be created with a temp name before the name can + be reused. For example, the previous CampaignBudget+Campaign + example would fail if the mutate order was reversed. + - Temp names are not remembered across requests. + - There's no limit to the number of temp names in a request. + - Each temp name must use a unique negative number, even if the + resource types differ. Latency ------- diff --git a/google/ads/googleads/v20/services/services/google_ads_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/google_ads_service/transports/grpc_asyncio.py index 4e235e9a2..60ca023de 100644 --- a/google/ads/googleads/v20/services/services/google_ads_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/google_ads_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -433,9 +435,9 @@ def mutate( methods. The only features it offers over calling those methods directly are: - - Atomic transactions - - Temp resource names (described below) - - Somewhat reduced latency over making a series of mutate calls + - Atomic transactions + - Temp resource names (described below) + - Somewhat reduced latency over making a series of mutate calls Note: Only resources that support atomic transactions are included, so this method can't replace all calls to individual @@ -465,14 +467,13 @@ def mutate( Note: - - Resources must be created with a temp name before the name - can be reused. For example, the previous - CampaignBudget+Campaign example would fail if the mutate - order was reversed. - - Temp names are not remembered across requests. - - There's no limit to the number of temp names in a request. - - Each temp name must use a unique negative number, even if the - resource types differ. + - Resources must be created with a temp name before the name can + be reused. For example, the previous CampaignBudget+Campaign + example would fail if the mutate order was reversed. + - Temp names are not remembered across requests. + - There's no limit to the number of temp names in a request. + - Each temp name must use a unique negative number, even if the + resource types differ. Latency ------- diff --git a/google/ads/googleads/v20/services/services/identity_verification_service/async_client.py b/google/ads/googleads/v20/services/services/identity_verification_service/async_client.py index dd4a2e1c8..8e400439f 100644 --- a/google/ads/googleads/v20/services/services/identity_verification_service/async_client.py +++ b/google/ads/googleads/v20/services/services/identity_verification_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -113,7 +112,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: IdentityVerificationServiceAsyncClient: The constructed client. """ - return IdentityVerificationServiceClient.from_service_account_info.__func__(IdentityVerificationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + IdentityVerificationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + IdentityVerificationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -129,7 +133,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: IdentityVerificationServiceAsyncClient: The constructed client. """ - return IdentityVerificationServiceClient.from_service_account_file.__func__(IdentityVerificationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + IdentityVerificationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + IdentityVerificationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -324,7 +333,7 @@ async def start_identity_verification( Args: request (Optional[Union[google.ads.googleads.v20.services.types.StartIdentityVerificationRequest, dict]]): The request object. Request message for - [IdentityVerificationService.StartIdentityVerification]. + [StartIdentityVerification][google.ads.googleads.v20.services.IdentityVerificationService.StartIdentityVerification]. customer_id (:class:`str`): Required. The Id of the customer for whom we are creating this verification. @@ -428,7 +437,7 @@ async def get_identity_verification( Args: request (Optional[Union[google.ads.googleads.v20.services.types.GetIdentityVerificationRequest, dict]]): The request object. Request message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v20.services.IdentityVerificationService.GetIdentityVerification]. customer_id (:class:`str`): Required. The ID of the customer for whom we are requesting verification @@ -448,7 +457,7 @@ async def get_identity_verification( Returns: google.ads.googleads.v20.services.types.GetIdentityVerificationResponse: Response message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v20.services.IdentityVerificationService.GetIdentityVerification]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/identity_verification_service/client.py b/google/ads/googleads/v20/services/services/identity_verification_service/client.py index e7a2dee2b..7b9005ad3 100644 --- a/google/ads/googleads/v20/services/services/identity_verification_service/client.py +++ b/google/ads/googleads/v20/services/services/identity_verification_service/client.py @@ -145,6 +145,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -316,14 +344,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + IdentityVerificationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -331,7 +355,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -363,22 +387,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + IdentityVerificationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -758,7 +778,7 @@ def start_identity_verification( Args: request (Union[google.ads.googleads.v20.services.types.StartIdentityVerificationRequest, dict]): The request object. Request message for - [IdentityVerificationService.StartIdentityVerification]. + [StartIdentityVerification][google.ads.googleads.v20.services.IdentityVerificationService.StartIdentityVerification]. customer_id (str): Required. The Id of the customer for whom we are creating this verification. @@ -861,7 +881,7 @@ def get_identity_verification( Args: request (Union[google.ads.googleads.v20.services.types.GetIdentityVerificationRequest, dict]): The request object. Request message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v20.services.IdentityVerificationService.GetIdentityVerification]. customer_id (str): Required. The ID of the customer for whom we are requesting verification @@ -881,7 +901,7 @@ def get_identity_verification( Returns: google.ads.googleads.v20.services.types.GetIdentityVerificationResponse: Response message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v20.services.IdentityVerificationService.GetIdentityVerification]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/identity_verification_service/transports/base.py b/google/ads/googleads/v20/services/services/identity_verification_service/transports/base.py index d876dca7b..67a80e5f8 100644 --- a/google/ads/googleads/v20/services/services/identity_verification_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/identity_verification_service/transports/base.py @@ -29,7 +29,7 @@ from google.ads.googleads.v20.services.types import ( identity_verification_service, ) -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -69,9 +69,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -84,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +100,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/identity_verification_service/transports/grpc.py b/google/ads/googleads/v20/services/services/identity_verification_service/transports/grpc.py index c10aec610..ec0684844 100644 --- a/google/ads/googleads/v20/services/services/identity_verification_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/identity_verification_service/transports/grpc.py @@ -32,7 +32,7 @@ from google.ads.googleads.v20.services.types import ( identity_verification_service, ) -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import IdentityVerificationServiceTransport, DEFAULT_CLIENT_INFO try: @@ -167,9 +167,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -310,9 +311,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/identity_verification_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/identity_verification_service/transports/grpc_asyncio.py index 634649e0c..d6fbaedd9 100644 --- a/google/ads/googleads/v20/services/services/identity_verification_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/identity_verification_service/transports/grpc_asyncio.py @@ -33,7 +33,7 @@ from google.ads.googleads.v20.services.types import ( identity_verification_service, ) -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import IdentityVerificationServiceTransport, DEFAULT_CLIENT_INFO try: @@ -157,8 +157,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -213,9 +214,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/invoice_service/async_client.py b/google/ads/googleads/v20/services/services/invoice_service/async_client.py index 352f9bed4..39f3fe04e 100644 --- a/google/ads/googleads/v20/services/services/invoice_service/async_client.py +++ b/google/ads/googleads/v20/services/services/invoice_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -104,7 +103,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: InvoiceServiceAsyncClient: The constructed client. """ - return InvoiceServiceClient.from_service_account_info.__func__(InvoiceServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + InvoiceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(InvoiceServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -120,7 +122,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: InvoiceServiceAsyncClient: The constructed client. """ - return InvoiceServiceClient.from_service_account_file.__func__(InvoiceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + InvoiceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + InvoiceServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/invoice_service/client.py b/google/ads/googleads/v20/services/services/invoice_service/client.py index d728d6d24..2fff5ae36 100644 --- a/google/ads/googleads/v20/services/services/invoice_service/client.py +++ b/google/ads/googleads/v20/services/services/invoice_service/client.py @@ -136,6 +136,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -327,14 +355,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = InvoiceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -342,7 +364,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -374,22 +396,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = InvoiceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/invoice_service/transports/base.py b/google/ads/googleads/v20/services/services/invoice_service/transports/base.py index 9fad10482..78f9374ff 100644 --- a/google/ads/googleads/v20/services/services/invoice_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/invoice_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/invoice_service/transports/grpc.py b/google/ads/googleads/v20/services/services/invoice_service/transports/grpc.py index f973e4e5c..7a4701264 100644 --- a/google/ads/googleads/v20/services/services/invoice_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/invoice_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/invoice_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/invoice_service/transports/grpc_asyncio.py index c55ed0477..2c031b8e5 100644 --- a/google/ads/googleads/v20/services/services/invoice_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/invoice_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/async_client.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/async_client.py index e969aac8b..273ac0499 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/async_client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( keyword_plan_ad_group_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -132,7 +131,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanAdGroupKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupKeywordServiceClient.from_service_account_info.__func__(KeywordPlanAdGroupKeywordServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanAdGroupKeywordServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanAdGroupKeywordServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -148,7 +152,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanAdGroupKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupKeywordServiceClient.from_service_account_file.__func__(KeywordPlanAdGroupKeywordServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanAdGroupKeywordServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanAdGroupKeywordServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/client.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/client.py index 5cc596666..456b716a7 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( keyword_plan_ad_group_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -162,6 +162,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -373,14 +401,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanAdGroupKeywordServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -388,7 +412,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -420,22 +444,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanAdGroupKeywordServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/base.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/base.py index 19c917d8e..c4e747ab6 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/grpc.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/grpc.py index 1fe6b09b6..d21723400 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/grpc.py @@ -172,9 +172,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -315,9 +316,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/grpc_asyncio.py index 9b54a4a8a..338010634 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_keyword_service/transports/grpc_asyncio.py @@ -162,8 +162,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -218,9 +219,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/async_client.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/async_client.py index 8dd9e2848..4f2f9d5b9 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/async_client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( keyword_plan_ad_group_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanAdGroupServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupServiceClient.from_service_account_info.__func__(KeywordPlanAdGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanAdGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanAdGroupServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanAdGroupServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupServiceClient.from_service_account_file.__func__(KeywordPlanAdGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanAdGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanAdGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/client.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/client.py index 97502fb28..cc1b3847b 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( keyword_plan_ad_group_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -366,14 +394,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanAdGroupServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -381,7 +405,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -413,22 +437,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanAdGroupServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/base.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/base.py index 280df104a..71567b92c 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/grpc.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/grpc.py index c5ca2c440..4bf875349 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/grpc_asyncio.py index 6916ad3bd..9884d6508 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_ad_group_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/async_client.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/async_client.py index 4d90ea689..f5fae3c2c 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/async_client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( keyword_plan_campaign_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -132,7 +131,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanCampaignKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignKeywordServiceClient.from_service_account_info.__func__(KeywordPlanCampaignKeywordServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanCampaignKeywordServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanCampaignKeywordServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -148,7 +152,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanCampaignKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignKeywordServiceClient.from_service_account_file.__func__(KeywordPlanCampaignKeywordServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanCampaignKeywordServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanCampaignKeywordServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/client.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/client.py index 5ee24bb27..c769866f9 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( keyword_plan_campaign_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -160,6 +160,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -371,14 +399,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanCampaignKeywordServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -386,7 +410,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -418,22 +442,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanCampaignKeywordServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/base.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/base.py index c1079cff8..a3332fcf2 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/grpc.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/grpc.py index a938cda8c..1c7615b83 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/grpc.py @@ -173,9 +173,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -316,9 +317,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/grpc_asyncio.py index ff7605918..de33d9890 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_keyword_service/transports/grpc_asyncio.py @@ -163,8 +163,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -219,9 +220,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/async_client.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/async_client.py index 127b1857d..307622f47 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/async_client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( keyword_plan_campaign_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignServiceTransport, DEFAULT_CLIENT_INFO, @@ -137,7 +136,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanCampaignServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignServiceClient.from_service_account_info.__func__(KeywordPlanCampaignServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanCampaignServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanCampaignServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -153,7 +157,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanCampaignServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignServiceClient.from_service_account_file.__func__(KeywordPlanCampaignServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanCampaignServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanCampaignServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/client.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/client.py index 5e001eb90..80403f862 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( keyword_plan_campaign_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -396,14 +424,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanCampaignServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -411,7 +435,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -443,22 +467,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanCampaignServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/base.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/base.py index a3356aa09..0ef879933 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/grpc.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/grpc.py index f96fc9256..a5e4e3c5e 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/grpc_asyncio.py index f1acb03d5..5e677094c 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_campaign_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/async_client.py b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/async_client.py index 7a7dd60a8..3ade7789f 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/async_client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanIdeaServiceAsyncClient: The constructed client. """ - return KeywordPlanIdeaServiceClient.from_service_account_info.__func__(KeywordPlanIdeaServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanIdeaServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanIdeaServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanIdeaServiceAsyncClient: The constructed client. """ - return KeywordPlanIdeaServiceClient.from_service_account_file.__func__(KeywordPlanIdeaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanIdeaServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanIdeaServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -603,7 +612,7 @@ async def generate_keyword_forecast_metrics( Args: request (Optional[Union[google.ads.googleads.v20.services.types.GenerateKeywordForecastMetricsRequest, dict]]): The request object. Request message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v20.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. campaign (:class:`google.ads.googleads.v20.services.types.CampaignToForecast`): Required. The campaign used in the forecast. @@ -622,7 +631,7 @@ async def generate_keyword_forecast_metrics( Returns: google.ads.googleads.v20.services.types.GenerateKeywordForecastMetricsResponse: Response message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v20.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/client.py b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/client.py index bdb5175d9..b36283279 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/client.py @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -322,14 +350,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanIdeaServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -337,7 +361,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -369,22 +393,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanIdeaServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -1039,7 +1059,7 @@ def generate_keyword_forecast_metrics( Args: request (Union[google.ads.googleads.v20.services.types.GenerateKeywordForecastMetricsRequest, dict]): The request object. Request message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v20.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. campaign (google.ads.googleads.v20.services.types.CampaignToForecast): Required. The campaign used in the forecast. @@ -1058,7 +1078,7 @@ def generate_keyword_forecast_metrics( Returns: google.ads.googleads.v20.services.types.GenerateKeywordForecastMetricsResponse: Response message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v20.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/base.py b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/base.py index 87a9e7436..12eafdc17 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/grpc.py b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/grpc.py index b6f8535b5..6121b0009 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/grpc_asyncio.py index cb06580f5..1d468c017 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_idea_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_service/async_client.py b/google/ads/googleads/v20/services/services/keyword_plan_service/async_client.py index 7ff718d6d..fac6939d4 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_service/async_client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import keyword_plan_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import KeywordPlanServiceTransport, DEFAULT_CLIENT_INFO from .client import KeywordPlanServiceClient @@ -110,7 +109,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanServiceAsyncClient: The constructed client. """ - return KeywordPlanServiceClient.from_service_account_info.__func__(KeywordPlanServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -126,7 +130,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanServiceAsyncClient: The constructed client. """ - return KeywordPlanServiceClient.from_service_account_file.__func__(KeywordPlanServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/keyword_plan_service/client.py b/google/ads/googleads/v20/services/services/keyword_plan_service/client.py index 6a0566e47..c41480f2c 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_service/client.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import keyword_plan_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import KeywordPlanServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import KeywordPlanServiceGrpcTransport from .transports.grpc_asyncio import KeywordPlanServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = KeywordPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = KeywordPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_service/transports/base.py b/google/ads/googleads/v20/services/services/keyword_plan_service/transports/base.py index dcba45aa1..46c8818e1 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/keyword_plan_service/transports/grpc.py b/google/ads/googleads/v20/services/services/keyword_plan_service/transports/grpc.py index bd9c5e3c9..bba017168 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_plan_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/keyword_plan_service/transports/grpc_asyncio.py index d9184fae3..0757af744 100644 --- a/google/ads/googleads/v20/services/services/keyword_plan_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/keyword_plan_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/async_client.py b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/async_client.py index 28583c049..44ac95a7b 100644 --- a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/async_client.py +++ b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordThemeConstantServiceAsyncClient: The constructed client. """ - return KeywordThemeConstantServiceClient.from_service_account_info.__func__(KeywordThemeConstantServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordThemeConstantServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordThemeConstantServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordThemeConstantServiceAsyncClient: The constructed client. """ - return KeywordThemeConstantServiceClient.from_service_account_file.__func__(KeywordThemeConstantServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordThemeConstantServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordThemeConstantServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/client.py b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/client.py index 615143cee..9f0f98bca 100644 --- a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/client.py +++ b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordThemeConstantServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +374,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +406,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordThemeConstantServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/base.py b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/base.py index 2df585051..0775ed3ba 100644 --- a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/grpc.py b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/grpc.py index 698a92fa8..29632ccc2 100644 --- a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/grpc_asyncio.py index 76dc460bd..caf8e1e24 100644 --- a/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/keyword_theme_constant_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/label_service/async_client.py b/google/ads/googleads/v20/services/services/label_service/async_client.py index 0ea10cd18..aeb295119 100644 --- a/google/ads/googleads/v20/services/services/label_service/async_client.py +++ b/google/ads/googleads/v20/services/services/label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import LabelServiceTransport, DEFAULT_CLIENT_INFO from .client import LabelServiceClient @@ -100,7 +99,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: LabelServiceAsyncClient: The constructed client. """ - return LabelServiceClient.from_service_account_info.__func__(LabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + LabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(LabelServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -116,7 +118,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LabelServiceAsyncClient: The constructed client. """ - return LabelServiceClient.from_service_account_file.__func__(LabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + LabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(LabelServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/label_service/client.py b/google/ads/googleads/v20/services/services/label_service/client.py index 15636ca35..165e5668f 100644 --- a/google/ads/googleads/v20/services/services/label_service/client.py +++ b/google/ads/googleads/v20/services/services/label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import LabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import LabelServiceGrpcTransport from .transports.grpc_asyncio import LabelServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -334,14 +362,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = LabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -349,7 +371,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -381,22 +403,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = LabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/label_service/transports/base.py b/google/ads/googleads/v20/services/services/label_service/transports/base.py index c901f8cc3..390b60498 100644 --- a/google/ads/googleads/v20/services/services/label_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/label_service/transports/grpc.py b/google/ads/googleads/v20/services/services/label_service/transports/grpc.py index d6d9f6238..aecafd85d 100644 --- a/google/ads/googleads/v20/services/services/label_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/label_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/label_service/transports/grpc_asyncio.py index d2c2f8fbf..27a4b1f33 100644 --- a/google/ads/googleads/v20/services/services/label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/local_services_lead_service/async_client.py b/google/ads/googleads/v20/services/services/local_services_lead_service/async_client.py index 0fe8c1fef..3ebe0e3a3 100644 --- a/google/ads/googleads/v20/services/services/local_services_lead_service/async_client.py +++ b/google/ads/googleads/v20/services/services/local_services_lead_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -116,7 +115,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: LocalServicesLeadServiceAsyncClient: The constructed client. """ - return LocalServicesLeadServiceClient.from_service_account_info.__func__(LocalServicesLeadServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + LocalServicesLeadServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + LocalServicesLeadServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,7 +136,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LocalServicesLeadServiceAsyncClient: The constructed client. """ - return LocalServicesLeadServiceClient.from_service_account_file.__func__(LocalServicesLeadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + LocalServicesLeadServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + LocalServicesLeadServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/local_services_lead_service/client.py b/google/ads/googleads/v20/services/services/local_services_lead_service/client.py index 38ba350dc..d86550790 100644 --- a/google/ads/googleads/v20/services/services/local_services_lead_service/client.py +++ b/google/ads/googleads/v20/services/services/local_services_lead_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -345,14 +373,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + LocalServicesLeadServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -360,7 +384,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -392,22 +416,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + LocalServicesLeadServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/local_services_lead_service/transports/base.py b/google/ads/googleads/v20/services/services/local_services_lead_service/transports/base.py index c2d95faef..111db071b 100644 --- a/google/ads/googleads/v20/services/services/local_services_lead_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/local_services_lead_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/local_services_lead_service/transports/grpc.py b/google/ads/googleads/v20/services/services/local_services_lead_service/transports/grpc.py index d9598b4cd..8a3b5dd49 100644 --- a/google/ads/googleads/v20/services/services/local_services_lead_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/local_services_lead_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/local_services_lead_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/local_services_lead_service/transports/grpc_asyncio.py index 36fcca3ae..199c25e27 100644 --- a/google/ads/googleads/v20/services/services/local_services_lead_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/local_services_lead_service/transports/grpc_asyncio.py @@ -155,8 +155,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -211,9 +212,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/offline_user_data_job_service/async_client.py b/google/ads/googleads/v20/services/services/offline_user_data_job_service/async_client.py index 5b43b8bfa..6673c569d 100644 --- a/google/ads/googleads/v20/services/services/offline_user_data_job_service/async_client.py +++ b/google/ads/googleads/v20/services/services/offline_user_data_job_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,10 +36,10 @@ from google.ads.googleads.v20.services.types import ( offline_user_data_job_service, ) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( OfflineUserDataJobServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: OfflineUserDataJobServiceAsyncClient: The constructed client. """ - return OfflineUserDataJobServiceClient.from_service_account_info.__func__(OfflineUserDataJobServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + OfflineUserDataJobServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + OfflineUserDataJobServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: OfflineUserDataJobServiceAsyncClient: The constructed client. """ - return OfflineUserDataJobServiceClient.from_service_account_file.__func__(OfflineUserDataJobServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + OfflineUserDataJobServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + OfflineUserDataJobServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/offline_user_data_job_service/client.py b/google/ads/googleads/v20/services/services/offline_user_data_job_service/client.py index bb1283534..250d490d3 100644 --- a/google/ads/googleads/v20/services/services/offline_user_data_job_service/client.py +++ b/google/ads/googleads/v20/services/services/offline_user_data_job_service/client.py @@ -63,10 +63,10 @@ from google.ads.googleads.v20.services.types import ( offline_user_data_job_service, ) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( OfflineUserDataJobServiceTransport, DEFAULT_CLIENT_INFO, @@ -159,6 +159,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -350,14 +378,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + OfflineUserDataJobServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -365,7 +389,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -397,22 +421,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + OfflineUserDataJobServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/base.py b/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/base.py index 975ec55c9..0c6fcfa01 100644 --- a/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/base.py @@ -69,9 +69,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -84,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +100,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/grpc.py b/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/grpc.py index 54df8b00e..1cdc5b90a 100644 --- a/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/grpc.py @@ -168,9 +168,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/grpc_asyncio.py index bb2f9a83b..7e79f051f 100644 --- a/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/offline_user_data_job_service/transports/grpc_asyncio.py @@ -158,8 +158,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -214,9 +215,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/payments_account_service/async_client.py b/google/ads/googleads/v20/services/services/payments_account_service/async_client.py index 1c126d624..28fb3e0cf 100644 --- a/google/ads/googleads/v20/services/services/payments_account_service/async_client.py +++ b/google/ads/googleads/v20/services/services/payments_account_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: PaymentsAccountServiceAsyncClient: The constructed client. """ - return PaymentsAccountServiceClient.from_service_account_info.__func__(PaymentsAccountServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + PaymentsAccountServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + PaymentsAccountServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: PaymentsAccountServiceAsyncClient: The constructed client. """ - return PaymentsAccountServiceClient.from_service_account_file.__func__(PaymentsAccountServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + PaymentsAccountServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + PaymentsAccountServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/payments_account_service/client.py b/google/ads/googleads/v20/services/services/payments_account_service/client.py index 4e42935b6..cf70d029d 100644 --- a/google/ads/googleads/v20/services/services/payments_account_service/client.py +++ b/google/ads/googleads/v20/services/services/payments_account_service/client.py @@ -140,6 +140,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -346,14 +374,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + PaymentsAccountServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -361,7 +385,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -393,22 +417,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + PaymentsAccountServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/payments_account_service/transports/base.py b/google/ads/googleads/v20/services/services/payments_account_service/transports/base.py index 0cd6b7111..4d12820fe 100644 --- a/google/ads/googleads/v20/services/services/payments_account_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/payments_account_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/payments_account_service/transports/grpc.py b/google/ads/googleads/v20/services/services/payments_account_service/transports/grpc.py index bdef3e30c..fc81f6138 100644 --- a/google/ads/googleads/v20/services/services/payments_account_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/payments_account_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/payments_account_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/payments_account_service/transports/grpc_asyncio.py index be3f538ee..690cda436 100644 --- a/google/ads/googleads/v20/services/services/payments_account_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/payments_account_service/transports/grpc_asyncio.py @@ -155,8 +155,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -211,9 +212,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/product_link_invitation_service/async_client.py b/google/ads/googleads/v20/services/services/product_link_invitation_service/async_client.py index 789b9d0dd..a0f9ec157 100644 --- a/google/ads/googleads/v20/services/services/product_link_invitation_service/async_client.py +++ b/google/ads/googleads/v20/services/services/product_link_invitation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -132,7 +131,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ProductLinkInvitationServiceAsyncClient: The constructed client. """ - return ProductLinkInvitationServiceClient.from_service_account_info.__func__(ProductLinkInvitationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ProductLinkInvitationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ProductLinkInvitationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -148,7 +152,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductLinkInvitationServiceAsyncClient: The constructed client. """ - return ProductLinkInvitationServiceClient.from_service_account_file.__func__(ProductLinkInvitationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ProductLinkInvitationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ProductLinkInvitationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -570,7 +579,7 @@ async def remove_product_link_invitation( Args: request (Optional[Union[google.ads.googleads.v20.services.types.RemoveProductLinkInvitationRequest, dict]]): The request object. Request message for - [ProductLinkinvitationService.RemoveProductLinkInvitation][]. + [ProductLinkInvitationService.RemoveProductLinkInvitation][google.ads.googleads.v20.services.ProductLinkInvitationService.RemoveProductLinkInvitation]. customer_id (:class:`str`): Required. The ID of the product link invitation being removed. @@ -582,7 +591,7 @@ async def remove_product_link_invitation( Required. The resource name of the product link invitation being removed. expected, in this format: - ```` + ``customers/{customer_id}/productLinkInvitations/{product_link_invitation_id}`` This corresponds to the ``resource_name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v20/services/services/product_link_invitation_service/client.py b/google/ads/googleads/v20/services/services/product_link_invitation_service/client.py index 90e78bad6..9bbae2883 100644 --- a/google/ads/googleads/v20/services/services/product_link_invitation_service/client.py +++ b/google/ads/googleads/v20/services/services/product_link_invitation_service/client.py @@ -152,6 +152,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -358,14 +386,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ProductLinkInvitationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -373,7 +397,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -405,22 +429,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ProductLinkInvitationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -1027,7 +1047,7 @@ def remove_product_link_invitation( Args: request (Union[google.ads.googleads.v20.services.types.RemoveProductLinkInvitationRequest, dict]): The request object. Request message for - [ProductLinkinvitationService.RemoveProductLinkInvitation][]. + [ProductLinkInvitationService.RemoveProductLinkInvitation][google.ads.googleads.v20.services.ProductLinkInvitationService.RemoveProductLinkInvitation]. customer_id (str): Required. The ID of the product link invitation being removed. @@ -1039,7 +1059,7 @@ def remove_product_link_invitation( Required. The resource name of the product link invitation being removed. expected, in this format: - ```` + ``customers/{customer_id}/productLinkInvitations/{product_link_invitation_id}`` This corresponds to the ``resource_name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/base.py b/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/base.py index 2cdeccefd..546615f27 100644 --- a/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/grpc.py b/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/grpc.py index da1110969..93d334a46 100644 --- a/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/grpc.py @@ -167,9 +167,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -310,9 +311,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/grpc_asyncio.py index 2c570c106..395cbfaf1 100644 --- a/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/product_link_invitation_service/transports/grpc_asyncio.py @@ -157,8 +157,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -213,9 +214,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/product_link_service/async_client.py b/google/ads/googleads/v20/services/services/product_link_service/async_client.py index 42116c094..eef8e5d36 100644 --- a/google/ads/googleads/v20/services/services/product_link_service/async_client.py +++ b/google/ads/googleads/v20/services/services/product_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ProductLinkServiceAsyncClient: The constructed client. """ - return ProductLinkServiceClient.from_service_account_info.__func__(ProductLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ProductLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ProductLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductLinkServiceAsyncClient: The constructed client. """ - return ProductLinkServiceClient.from_service_account_file.__func__(ProductLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ProductLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ProductLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/product_link_service/client.py b/google/ads/googleads/v20/services/services/product_link_service/client.py index e4223e3c9..92d2c0e8d 100644 --- a/google/ads/googleads/v20/services/services/product_link_service/client.py +++ b/google/ads/googleads/v20/services/services/product_link_service/client.py @@ -138,6 +138,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = ProductLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +381,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +413,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ProductLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/product_link_service/transports/base.py b/google/ads/googleads/v20/services/services/product_link_service/transports/base.py index e47733e56..49e0ebb3e 100644 --- a/google/ads/googleads/v20/services/services/product_link_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/product_link_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/product_link_service/transports/grpc.py b/google/ads/googleads/v20/services/services/product_link_service/transports/grpc.py index 91201f4ec..83a75d811 100644 --- a/google/ads/googleads/v20/services/services/product_link_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/product_link_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/product_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/product_link_service/transports/grpc_asyncio.py index 83c88817b..339e8a23f 100644 --- a/google/ads/googleads/v20/services/services/product_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/product_link_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/reach_plan_service/async_client.py b/google/ads/googleads/v20/services/services/reach_plan_service/async_client.py index 4b3e95022..771ac37dd 100644 --- a/google/ads/googleads/v20/services/services/reach_plan_service/async_client.py +++ b/google/ads/googleads/v20/services/services/reach_plan_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -109,7 +108,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ReachPlanServiceAsyncClient: The constructed client. """ - return ReachPlanServiceClient.from_service_account_info.__func__(ReachPlanServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ReachPlanServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(ReachPlanServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -125,7 +127,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ReachPlanServiceAsyncClient: The constructed client. """ - return ReachPlanServiceClient.from_service_account_file.__func__(ReachPlanServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ReachPlanServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ReachPlanServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -664,9 +671,9 @@ async def list_plannable_user_lists( status. User lists may not be plannable for a number of reasons, including: - - They are less than 10 days old. - - They have a membership lifespan that is less than 30 days - - They have less than 10,000 or more than 700,000 users. + - They are less than 10 days old. + - They have a membership lifespan that is less than 30 days + - They have less than 10,000 or more than 700,000 users. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `FieldError <>`__ `HeaderError <>`__ diff --git a/google/ads/googleads/v20/services/services/reach_plan_service/client.py b/google/ads/googleads/v20/services/services/reach_plan_service/client.py index 16e4ba85c..b98bb53f6 100644 --- a/google/ads/googleads/v20/services/services/reach_plan_service/client.py +++ b/google/ads/googleads/v20/services/services/reach_plan_service/client.py @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -320,14 +348,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = ReachPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -335,7 +357,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -367,22 +389,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ReachPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -1092,9 +1108,9 @@ def list_plannable_user_lists( status. User lists may not be plannable for a number of reasons, including: - - They are less than 10 days old. - - They have a membership lifespan that is less than 30 days - - They have less than 10,000 or more than 700,000 users. + - They are less than 10 days old. + - They have a membership lifespan that is less than 30 days + - They have less than 10,000 or more than 700,000 users. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `FieldError <>`__ `HeaderError <>`__ diff --git a/google/ads/googleads/v20/services/services/reach_plan_service/transports/base.py b/google/ads/googleads/v20/services/services/reach_plan_service/transports/base.py index a910a3d28..122537d1a 100644 --- a/google/ads/googleads/v20/services/services/reach_plan_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/reach_plan_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/reach_plan_service/transports/grpc.py b/google/ads/googleads/v20/services/services/reach_plan_service/transports/grpc.py index aceea5c88..2ac38cc9d 100644 --- a/google/ads/googleads/v20/services/services/reach_plan_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/reach_plan_service/transports/grpc.py @@ -167,9 +167,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -310,9 +311,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -501,9 +503,9 @@ def list_plannable_user_lists( status. User lists may not be plannable for a number of reasons, including: - - They are less than 10 days old. - - They have a membership lifespan that is less than 30 days - - They have less than 10,000 or more than 700,000 users. + - They are less than 10 days old. + - They have a membership lifespan that is less than 30 days + - They have less than 10,000 or more than 700,000 users. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `FieldError <>`__ `HeaderError <>`__ diff --git a/google/ads/googleads/v20/services/services/reach_plan_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/reach_plan_service/transports/grpc_asyncio.py index db00fb9cc..1de6fd0f0 100644 --- a/google/ads/googleads/v20/services/services/reach_plan_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/reach_plan_service/transports/grpc_asyncio.py @@ -157,8 +157,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -213,9 +214,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -507,9 +509,9 @@ def list_plannable_user_lists( status. User lists may not be plannable for a number of reasons, including: - - They are less than 10 days old. - - They have a membership lifespan that is less than 30 days - - They have less than 10,000 or more than 700,000 users. + - They are less than 10 days old. + - They have a membership lifespan that is less than 30 days + - They have less than 10,000 or more than 700,000 users. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `FieldError <>`__ `HeaderError <>`__ diff --git a/google/ads/googleads/v20/services/services/recommendation_service/async_client.py b/google/ads/googleads/v20/services/services/recommendation_service/async_client.py index cb69c67a5..fae329ba1 100644 --- a/google/ads/googleads/v20/services/services/recommendation_service/async_client.py +++ b/google/ads/googleads/v20/services/services/recommendation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -38,7 +37,7 @@ ) from google.ads.googleads.v20.enums.types import recommendation_type from google.ads.googleads.v20.services.types import recommendation_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO from .client import RecommendationServiceClient @@ -142,7 +141,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: RecommendationServiceAsyncClient: The constructed client. """ - return RecommendationServiceClient.from_service_account_info.__func__(RecommendationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + RecommendationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + RecommendationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -158,7 +162,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RecommendationServiceAsyncClient: The constructed client. """ - return RecommendationServiceClient.from_service_account_file.__func__(RecommendationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + RecommendationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + RecommendationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/recommendation_service/client.py b/google/ads/googleads/v20/services/services/recommendation_service/client.py index 6065036b6..3833da994 100644 --- a/google/ads/googleads/v20/services/services/recommendation_service/client.py +++ b/google/ads/googleads/v20/services/services/recommendation_service/client.py @@ -64,7 +64,7 @@ ) from google.ads.googleads.v20.enums.types import recommendation_type from google.ads.googleads.v20.services.types import recommendation_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import RecommendationServiceGrpcTransport from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport @@ -150,6 +150,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -459,14 +487,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + RecommendationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -474,7 +498,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -506,22 +530,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + RecommendationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/recommendation_service/transports/base.py b/google/ads/googleads/v20/services/services/recommendation_service/transports/base.py index 932854c7f..ccf5a3f48 100644 --- a/google/ads/googleads/v20/services/services/recommendation_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/recommendation_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/recommendation_service/transports/grpc.py b/google/ads/googleads/v20/services/services/recommendation_service/transports/grpc.py index c365569b5..78c0dcc07 100644 --- a/google/ads/googleads/v20/services/services/recommendation_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/recommendation_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/recommendation_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/recommendation_service/transports/grpc_asyncio.py index b3f32d254..13b00de3f 100644 --- a/google/ads/googleads/v20/services/services/recommendation_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/recommendation_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/recommendation_subscription_service/async_client.py b/google/ads/googleads/v20/services/services/recommendation_subscription_service/async_client.py index 603222efe..e99fa21da 100644 --- a/google/ads/googleads/v20/services/services/recommendation_subscription_service/async_client.py +++ b/google/ads/googleads/v20/services/services/recommendation_subscription_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( recommendation_subscription_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RecommendationSubscriptionServiceTransport, DEFAULT_CLIENT_INFO, @@ -121,7 +120,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: RecommendationSubscriptionServiceAsyncClient: The constructed client. """ - return RecommendationSubscriptionServiceClient.from_service_account_info.__func__(RecommendationSubscriptionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + RecommendationSubscriptionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + RecommendationSubscriptionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -137,7 +141,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RecommendationSubscriptionServiceAsyncClient: The constructed client. """ - return RecommendationSubscriptionServiceClient.from_service_account_file.__func__(RecommendationSubscriptionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + RecommendationSubscriptionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + RecommendationSubscriptionServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file @@ -333,13 +345,14 @@ async def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Args: request (Optional[Union[google.ads.googleads.v20.services.types.MutateRecommendationSubscriptionRequest, dict]]): The request object. Request message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v20.services.RecommendationSubscriptionService.MutateRecommendationSubscription] customer_id (:class:`str`): Required. The ID of the subscribing customer. @@ -365,7 +378,7 @@ async def mutate_recommendation_subscription( Returns: google.ads.googleads.v20.services.types.MutateRecommendationSubscriptionResponse: Response message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v20.services.RecommendationSubscriptionService.MutateRecommendationSubscription] """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/recommendation_subscription_service/client.py b/google/ads/googleads/v20/services/services/recommendation_subscription_service/client.py index 0c818c752..0c41faa24 100644 --- a/google/ads/googleads/v20/services/services/recommendation_subscription_service/client.py +++ b/google/ads/googleads/v20/services/services/recommendation_subscription_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( recommendation_subscription_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RecommendationSubscriptionServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -346,14 +374,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + RecommendationSubscriptionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -361,7 +385,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -393,22 +417,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + RecommendationSubscriptionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -793,13 +813,14 @@ def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Args: request (Union[google.ads.googleads.v20.services.types.MutateRecommendationSubscriptionRequest, dict]): The request object. Request message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v20.services.RecommendationSubscriptionService.MutateRecommendationSubscription] customer_id (str): Required. The ID of the subscribing customer. @@ -825,7 +846,7 @@ def mutate_recommendation_subscription( Returns: google.ads.googleads.v20.services.types.MutateRecommendationSubscriptionResponse: Response message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v20.services.RecommendationSubscriptionService.MutateRecommendationSubscription] """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/base.py b/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/base.py index 2e3211c52..875f9175a 100644 --- a/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/grpc.py b/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/grpc.py index 754cd11e8..458d97a65 100644 --- a/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -363,7 +365,8 @@ def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Returns: diff --git a/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/grpc_asyncio.py index d0f258282..ecff5421a 100644 --- a/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/recommendation_subscription_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -371,7 +373,8 @@ def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Returns: diff --git a/google/ads/googleads/v20/services/services/remarketing_action_service/async_client.py b/google/ads/googleads/v20/services/services/remarketing_action_service/async_client.py index eeccced92..73f59cc68 100644 --- a/google/ads/googleads/v20/services/services/remarketing_action_service/async_client.py +++ b/google/ads/googleads/v20/services/services/remarketing_action_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import remarketing_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RemarketingActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: RemarketingActionServiceAsyncClient: The constructed client. """ - return RemarketingActionServiceClient.from_service_account_info.__func__(RemarketingActionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + RemarketingActionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + RemarketingActionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RemarketingActionServiceAsyncClient: The constructed client. """ - return RemarketingActionServiceClient.from_service_account_file.__func__(RemarketingActionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + RemarketingActionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + RemarketingActionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/remarketing_action_service/client.py b/google/ads/googleads/v20/services/services/remarketing_action_service/client.py index c27e708d1..ab4fd7964 100644 --- a/google/ads/googleads/v20/services/services/remarketing_action_service/client.py +++ b/google/ads/googleads/v20/services/services/remarketing_action_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import remarketing_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RemarketingActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + RemarketingActionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +383,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +415,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + RemarketingActionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/remarketing_action_service/transports/base.py b/google/ads/googleads/v20/services/services/remarketing_action_service/transports/base.py index 164997592..d4dd349c0 100644 --- a/google/ads/googleads/v20/services/services/remarketing_action_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/remarketing_action_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/remarketing_action_service/transports/grpc.py b/google/ads/googleads/v20/services/services/remarketing_action_service/transports/grpc.py index c2fc3928a..8270e211f 100644 --- a/google/ads/googleads/v20/services/services/remarketing_action_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/remarketing_action_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/remarketing_action_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/remarketing_action_service/transports/grpc_asyncio.py index 022d9e173..86adb90bc 100644 --- a/google/ads/googleads/v20/services/services/remarketing_action_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/remarketing_action_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/shareable_preview_service/async_client.py b/google/ads/googleads/v20/services/services/shareable_preview_service/async_client.py index a56288183..6fd3d46b8 100644 --- a/google/ads/googleads/v20/services/services/shareable_preview_service/async_client.py +++ b/google/ads/googleads/v20/services/services/shareable_preview_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -108,7 +107,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ShareablePreviewServiceAsyncClient: The constructed client. """ - return ShareablePreviewServiceClient.from_service_account_info.__func__(ShareablePreviewServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ShareablePreviewServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ShareablePreviewServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +128,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ShareablePreviewServiceAsyncClient: The constructed client. """ - return ShareablePreviewServiceClient.from_service_account_file.__func__(ShareablePreviewServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ShareablePreviewServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ShareablePreviewServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/shareable_preview_service/client.py b/google/ads/googleads/v20/services/services/shareable_preview_service/client.py index 7dc7694e2..6eaf0d87f 100644 --- a/google/ads/googleads/v20/services/services/shareable_preview_service/client.py +++ b/google/ads/googleads/v20/services/services/shareable_preview_service/client.py @@ -150,6 +150,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -321,14 +349,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ShareablePreviewServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -336,7 +360,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -368,22 +392,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ShareablePreviewServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/shareable_preview_service/transports/base.py b/google/ads/googleads/v20/services/services/shareable_preview_service/transports/base.py index 50ada7a6b..05e3dbc3a 100644 --- a/google/ads/googleads/v20/services/services/shareable_preview_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/shareable_preview_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/shareable_preview_service/transports/grpc.py b/google/ads/googleads/v20/services/services/shareable_preview_service/transports/grpc.py index 889f6e83b..902fb68f2 100644 --- a/google/ads/googleads/v20/services/services/shareable_preview_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/shareable_preview_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/shareable_preview_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/shareable_preview_service/transports/grpc_asyncio.py index 5340a76e9..370aa1232 100644 --- a/google/ads/googleads/v20/services/services/shareable_preview_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/shareable_preview_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/shared_criterion_service/async_client.py b/google/ads/googleads/v20/services/services/shared_criterion_service/async_client.py index b5c27345b..a800b1b59 100644 --- a/google/ads/googleads/v20/services/services/shared_criterion_service/async_client.py +++ b/google/ads/googleads/v20/services/services/shared_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import shared_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SharedCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SharedCriterionServiceAsyncClient: The constructed client. """ - return SharedCriterionServiceClient.from_service_account_info.__func__(SharedCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SharedCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SharedCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SharedCriterionServiceAsyncClient: The constructed client. """ - return SharedCriterionServiceClient.from_service_account_file.__func__(SharedCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SharedCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SharedCriterionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/shared_criterion_service/client.py b/google/ads/googleads/v20/services/services/shared_criterion_service/client.py index e2bf48bf6..3adc7b987 100644 --- a/google/ads/googleads/v20/services/services/shared_criterion_service/client.py +++ b/google/ads/googleads/v20/services/services/shared_criterion_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import shared_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SharedCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -380,14 +408,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + SharedCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -395,7 +419,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -427,22 +451,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + SharedCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/shared_criterion_service/transports/base.py b/google/ads/googleads/v20/services/services/shared_criterion_service/transports/base.py index 6b79234d0..9c68be5b8 100644 --- a/google/ads/googleads/v20/services/services/shared_criterion_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/shared_criterion_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/shared_criterion_service/transports/grpc.py b/google/ads/googleads/v20/services/services/shared_criterion_service/transports/grpc.py index 5e213ba73..fccbbd8ff 100644 --- a/google/ads/googleads/v20/services/services/shared_criterion_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/shared_criterion_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/shared_criterion_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/shared_criterion_service/transports/grpc_asyncio.py index 6a2f3e7d1..ebe898d60 100644 --- a/google/ads/googleads/v20/services/services/shared_criterion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/shared_criterion_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/shared_set_service/async_client.py b/google/ads/googleads/v20/services/services/shared_set_service/async_client.py index 0b98c1bec..76f389e9a 100644 --- a/google/ads/googleads/v20/services/services/shared_set_service/async_client.py +++ b/google/ads/googleads/v20/services/services/shared_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import SharedSetServiceTransport, DEFAULT_CLIENT_INFO from .client import SharedSetServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SharedSetServiceAsyncClient: The constructed client. """ - return SharedSetServiceClient.from_service_account_info.__func__(SharedSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SharedSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SharedSetServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SharedSetServiceAsyncClient: The constructed client. """ - return SharedSetServiceClient.from_service_account_file.__func__(SharedSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SharedSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SharedSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/shared_set_service/client.py b/google/ads/googleads/v20/services/services/shared_set_service/client.py index d9b470886..a68caeac8 100644 --- a/google/ads/googleads/v20/services/services/shared_set_service/client.py +++ b/google/ads/googleads/v20/services/services/shared_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import SharedSetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SharedSetServiceGrpcTransport from .transports.grpc_asyncio import SharedSetServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = SharedSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = SharedSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/shared_set_service/transports/base.py b/google/ads/googleads/v20/services/services/shared_set_service/transports/base.py index 22889a6bf..6b050ed47 100644 --- a/google/ads/googleads/v20/services/services/shared_set_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/shared_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/shared_set_service/transports/grpc.py b/google/ads/googleads/v20/services/services/shared_set_service/transports/grpc.py index a875c780a..fb9460bf7 100644 --- a/google/ads/googleads/v20/services/services/shared_set_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/shared_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/shared_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/shared_set_service/transports/grpc_asyncio.py index 6d0509974..66760e6ec 100644 --- a/google/ads/googleads/v20/services/services/shared_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/shared_set_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/async_client.py b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/async_client.py index 5b94a8deb..635c37c9f 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/async_client.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( smart_campaign_setting_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SmartCampaignSettingServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SmartCampaignSettingServiceAsyncClient: The constructed client. """ - return SmartCampaignSettingServiceClient.from_service_account_info.__func__(SmartCampaignSettingServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SmartCampaignSettingServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SmartCampaignSettingServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SmartCampaignSettingServiceAsyncClient: The constructed client. """ - return SmartCampaignSettingServiceClient.from_service_account_file.__func__(SmartCampaignSettingServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SmartCampaignSettingServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SmartCampaignSettingServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/client.py b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/client.py index 2da3cb7e3..0077f91f1 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/client.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( smart_campaign_setting_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SmartCampaignSettingServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -366,14 +394,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + SmartCampaignSettingServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -381,7 +405,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -413,22 +437,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + SmartCampaignSettingServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/base.py b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/base.py index 04e18234f..40463ff10 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/grpc.py b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/grpc.py index 43301df22..e481b525c 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/grpc_asyncio.py index 25c5daa96..5f999d71a 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_setting_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/async_client.py b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/async_client.py index 1f73e7ff2..2c347176b 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/async_client.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SmartCampaignSuggestServiceAsyncClient: The constructed client. """ - return SmartCampaignSuggestServiceClient.from_service_account_info.__func__(SmartCampaignSuggestServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SmartCampaignSuggestServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SmartCampaignSuggestServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SmartCampaignSuggestServiceAsyncClient: The constructed client. """ - return SmartCampaignSuggestServiceClient.from_service_account_file.__func__(SmartCampaignSuggestServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SmartCampaignSuggestServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SmartCampaignSuggestServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -530,13 +539,13 @@ async def suggest_keyword_themes( Required. Information to get keyword theme suggestions. Required fields: - - suggestion_info.final_url - - suggestion_info.language_code - - suggestion_info.geo_target + - suggestion_info.final_url + - suggestion_info.language_code + - suggestion_info.geo_target Recommended fields: - - suggestion_info.business_setting + - suggestion_info.business_setting This corresponds to the ``suggestion_info`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/client.py b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/client.py index 8b81f5782..ad1dbb0bf 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/client.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -355,14 +383,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + SmartCampaignSuggestServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -370,7 +394,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -402,22 +426,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + SmartCampaignSuggestServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -991,13 +1011,13 @@ def suggest_keyword_themes( Required. Information to get keyword theme suggestions. Required fields: - - suggestion_info.final_url - - suggestion_info.language_code - - suggestion_info.geo_target + - suggestion_info.final_url + - suggestion_info.language_code + - suggestion_info.geo_target Recommended fields: - - suggestion_info.business_setting + - suggestion_info.business_setting This corresponds to the ``suggestion_info`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/base.py b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/base.py index e24a64650..4de2ff2f1 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/grpc.py b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/grpc.py index 14afc94b7..69db9dc2f 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/grpc_asyncio.py index 68821a2bb..9a7fb4263 100644 --- a/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/smart_campaign_suggest_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/async_client.py b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/async_client.py index 7e41da3a7..7ca976759 100644 --- a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/async_client.py +++ b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ThirdPartyAppAnalyticsLinkServiceAsyncClient: The constructed client. """ - return ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_info.__func__(ThirdPartyAppAnalyticsLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ThirdPartyAppAnalyticsLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ThirdPartyAppAnalyticsLinkServiceAsyncClient: The constructed client. """ - return ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_file.__func__(ThirdPartyAppAnalyticsLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ThirdPartyAppAnalyticsLinkServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/client.py b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/client.py index 8c5d94ab4..624c3e1b3 100644 --- a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/client.py +++ b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/client.py @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -337,14 +365,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ThirdPartyAppAnalyticsLinkServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -352,7 +376,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -384,22 +408,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ThirdPartyAppAnalyticsLinkServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/base.py b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/base.py index 37430fda3..fac343900 100644 --- a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/grpc.py b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/grpc.py index 5178dc280..87575cb54 100644 --- a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/grpc.py @@ -170,9 +170,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -313,9 +314,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/grpc_asyncio.py index e67a3f488..52f331983 100644 --- a/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/third_party_app_analytics_link_service/transports/grpc_asyncio.py @@ -160,8 +160,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -216,9 +217,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/async_client.py b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/async_client.py index 2d864f0ba..16e7c9193 100644 --- a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/async_client.py +++ b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -112,7 +111,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: TravelAssetSuggestionServiceAsyncClient: The constructed client. """ - return TravelAssetSuggestionServiceClient.from_service_account_info.__func__(TravelAssetSuggestionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + TravelAssetSuggestionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + TravelAssetSuggestionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -128,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: TravelAssetSuggestionServiceAsyncClient: The constructed client. """ - return TravelAssetSuggestionServiceClient.from_service_account_file.__func__(TravelAssetSuggestionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + TravelAssetSuggestionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + TravelAssetSuggestionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/client.py b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/client.py index 55a28b02d..a270686a0 100644 --- a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/client.py +++ b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -315,14 +343,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + TravelAssetSuggestionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -330,7 +354,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -362,22 +386,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + TravelAssetSuggestionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/base.py b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/base.py index c6bb129ed..e482339ed 100644 --- a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/grpc.py b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/grpc.py index 6ad8bdd04..103708f72 100644 --- a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/grpc_asyncio.py index 04edaa5cd..7295f2a6e 100644 --- a/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/travel_asset_suggestion_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/user_data_service/async_client.py b/google/ads/googleads/v20/services/services/user_data_service/async_client.py index 9fe366217..f859cf421 100644 --- a/google/ads/googleads/v20/services/services/user_data_service/async_client.py +++ b/google/ads/googleads/v20/services/services/user_data_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: UserDataServiceAsyncClient: The constructed client. """ - return UserDataServiceClient.from_service_account_info.__func__(UserDataServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + UserDataServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(UserDataServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +129,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserDataServiceAsyncClient: The constructed client. """ - return UserDataServiceClient.from_service_account_file.__func__(UserDataServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + UserDataServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + UserDataServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/user_data_service/client.py b/google/ads/googleads/v20/services/services/user_data_service/client.py index c4e236673..ed32e09e8 100644 --- a/google/ads/googleads/v20/services/services/user_data_service/client.py +++ b/google/ads/googleads/v20/services/services/user_data_service/client.py @@ -141,6 +141,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -312,14 +340,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = UserDataServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -327,7 +349,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -359,22 +381,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = UserDataServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/user_data_service/transports/base.py b/google/ads/googleads/v20/services/services/user_data_service/transports/base.py index 21517b7a0..b048a0344 100644 --- a/google/ads/googleads/v20/services/services/user_data_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/user_data_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/user_data_service/transports/grpc.py b/google/ads/googleads/v20/services/services/user_data_service/transports/grpc.py index 70212f1a0..927706227 100644 --- a/google/ads/googleads/v20/services/services/user_data_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/user_data_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/user_data_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/user_data_service/transports/grpc_asyncio.py index f97034d8a..d7030e21b 100644 --- a/google/ads/googleads/v20/services/services/user_data_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/user_data_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/user_list_customer_type_service/async_client.py b/google/ads/googleads/v20/services/services/user_list_customer_type_service/async_client.py index 50abd3a53..0308f916a 100644 --- a/google/ads/googleads/v20/services/services/user_list_customer_type_service/async_client.py +++ b/google/ads/googleads/v20/services/services/user_list_customer_type_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v20.services.types import ( user_list_customer_type_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( UserListCustomerTypeServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: UserListCustomerTypeServiceAsyncClient: The constructed client. """ - return UserListCustomerTypeServiceClient.from_service_account_info.__func__(UserListCustomerTypeServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + UserListCustomerTypeServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + UserListCustomerTypeServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserListCustomerTypeServiceAsyncClient: The constructed client. """ - return UserListCustomerTypeServiceClient.from_service_account_file.__func__(UserListCustomerTypeServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + UserListCustomerTypeServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + UserListCustomerTypeServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/user_list_customer_type_service/client.py b/google/ads/googleads/v20/services/services/user_list_customer_type_service/client.py index 5e872f4e5..4e9d583e8 100644 --- a/google/ads/googleads/v20/services/services/user_list_customer_type_service/client.py +++ b/google/ads/googleads/v20/services/services/user_list_customer_type_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v20.services.types import ( user_list_customer_type_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( UserListCustomerTypeServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + UserListCustomerTypeServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + UserListCustomerTypeServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/base.py b/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/base.py index b89d64e60..9876d2445 100644 --- a/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/grpc.py b/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/grpc.py index d5587fddb..289592d1a 100644 --- a/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/grpc_asyncio.py index 568948cfe..04f5b229b 100644 --- a/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/user_list_customer_type_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/user_list_service/async_client.py b/google/ads/googleads/v20/services/services/user_list_service/async_client.py index 5c39358ee..b94b46cfc 100644 --- a/google/ads/googleads/v20/services/services/user_list_service/async_client.py +++ b/google/ads/googleads/v20/services/services/user_list_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v20.services.types import user_list_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import UserListServiceTransport, DEFAULT_CLIENT_INFO from .client import UserListServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: UserListServiceAsyncClient: The constructed client. """ - return UserListServiceClient.from_service_account_info.__func__(UserListServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + UserListServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(UserListServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserListServiceAsyncClient: The constructed client. """ - return UserListServiceClient.from_service_account_file.__func__(UserListServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + UserListServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + UserListServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v20/services/services/user_list_service/client.py b/google/ads/googleads/v20/services/services/user_list_service/client.py index 08654ef4d..381698ce1 100644 --- a/google/ads/googleads/v20/services/services/user_list_service/client.py +++ b/google/ads/googleads/v20/services/services/user_list_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v20.services.types import user_list_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import UserListServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import UserListServiceGrpcTransport from .transports.grpc_asyncio import UserListServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = UserListServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = UserListServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v20/services/services/user_list_service/transports/base.py b/google/ads/googleads/v20/services/services/user_list_service/transports/base.py index 53fe6ca6e..95b228103 100644 --- a/google/ads/googleads/v20/services/services/user_list_service/transports/base.py +++ b/google/ads/googleads/v20/services/services/user_list_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v20/services/services/user_list_service/transports/grpc.py b/google/ads/googleads/v20/services/services/user_list_service/transports/grpc.py index b02044e11..9dc9a220c 100644 --- a/google/ads/googleads/v20/services/services/user_list_service/transports/grpc.py +++ b/google/ads/googleads/v20/services/services/user_list_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/services/user_list_service/transports/grpc_asyncio.py b/google/ads/googleads/v20/services/services/user_list_service/transports/grpc_asyncio.py index 413ad5751..337907e20 100644 --- a/google/ads/googleads/v20/services/services/user_list_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v20/services/services/user_list_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v20/services/types/account_budget_proposal_service.py b/google/ads/googleads/v20/services/types/account_budget_proposal_service.py index 53957e547..4c96dcdc3 100644 --- a/google/ads/googleads/v20/services/types/account_budget_proposal_service.py +++ b/google/ads/googleads/v20/services/types/account_budget_proposal_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import account_budget_proposal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/account_link_service.py b/google/ads/googleads/v20/services/types/account_link_service.py index 8d5e9f685..e6e2fbb77 100644 --- a/google/ads/googleads/v20/services/types/account_link_service.py +++ b/google/ads/googleads/v20/services/types/account_link_service.py @@ -21,9 +21,8 @@ from google.ads.googleads.v20.resources.types import ( account_link as gagr_account_link, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_ad_label_service.py b/google/ads/googleads/v20/services/types/ad_group_ad_label_service.py index 43c12b2dd..8811bb4c6 100644 --- a/google/ads/googleads/v20/services/types/ad_group_ad_label_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_ad_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import ad_group_ad_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_ad_service.py b/google/ads/googleads/v20/services/types/ad_group_ad_service.py index 79af8beb9..e7e40f1e5 100644 --- a/google/ads/googleads/v20/services/types/ad_group_ad_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_ad_service.py @@ -29,9 +29,8 @@ from google.ads.googleads.v20.resources.types import ( ad_group_ad as gagr_ad_group_ad, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", @@ -216,7 +215,7 @@ class MutateAdGroupAdResult(proto.Message): class RemoveAutomaticallyCreatedAssetsRequest(proto.Message): r"""Request message for - [AdGroupAdService.RemoveAutomaticallyCreatedAssetsRequest][]. + [AdGroupAdService.RemoveAutomaticallyCreatedAssets][google.ads.googleads.v20.services.AdGroupAdService.RemoveAutomaticallyCreatedAssets]. Attributes: ad_group_ad (str): diff --git a/google/ads/googleads/v20/services/types/ad_group_asset_service.py b/google/ads/googleads/v20/services/types/ad_group_asset_service.py index 924d7e629..75cca9ac0 100644 --- a/google/ads/googleads/v20/services/types/ad_group_asset_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_asset_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( ad_group_asset as gagr_ad_group_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_asset_set_service.py b/google/ads/googleads/v20/services/types/ad_group_asset_set_service.py index d91aa9e42..01dfeacf9 100644 --- a/google/ads/googleads/v20/services/types/ad_group_asset_set_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_asset_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( ad_group_asset_set as gagr_ad_group_asset_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_bid_modifier_service.py b/google/ads/googleads/v20/services/types/ad_group_bid_modifier_service.py index 58a229691..e18f44895 100644 --- a/google/ads/googleads/v20/services/types/ad_group_bid_modifier_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_bid_modifier_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( ad_group_bid_modifier as gagr_ad_group_bid_modifier, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_criterion_customizer_service.py b/google/ads/googleads/v20/services/types/ad_group_criterion_customizer_service.py index d025aa2e2..f95a5c108 100644 --- a/google/ads/googleads/v20/services/types/ad_group_criterion_customizer_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_criterion_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( ad_group_criterion_customizer as gagr_ad_group_criterion_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_criterion_label_service.py b/google/ads/googleads/v20/services/types/ad_group_criterion_label_service.py index 5606ef167..5e4edb5ab 100644 --- a/google/ads/googleads/v20/services/types/ad_group_criterion_label_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_criterion_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import ad_group_criterion_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_criterion_service.py b/google/ads/googleads/v20/services/types/ad_group_criterion_service.py index 12d0384d2..81764a08f 100644 --- a/google/ads/googleads/v20/services/types/ad_group_criterion_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_criterion_service.py @@ -26,9 +26,8 @@ from google.ads.googleads.v20.resources.types import ( ad_group_criterion as gagr_ad_group_criterion, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_customizer_service.py b/google/ads/googleads/v20/services/types/ad_group_customizer_service.py index 7cf3f5727..7fb2d2a0e 100644 --- a/google/ads/googleads/v20/services/types/ad_group_customizer_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( ad_group_customizer as gagr_ad_group_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_label_service.py b/google/ads/googleads/v20/services/types/ad_group_label_service.py index 7ae1c20b0..4a9871618 100644 --- a/google/ads/googleads/v20/services/types/ad_group_label_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import ad_group_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_group_service.py b/google/ads/googleads/v20/services/types/ad_group_service.py index 5c8458c5a..860d5c5c0 100644 --- a/google/ads/googleads/v20/services/types/ad_group_service.py +++ b/google/ads/googleads/v20/services/types/ad_group_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v20.resources.types import ad_group as gagr_ad_group -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_parameter_service.py b/google/ads/googleads/v20/services/types/ad_parameter_service.py index 20b61ee7d..e5f9cac3a 100644 --- a/google/ads/googleads/v20/services/types/ad_parameter_service.py +++ b/google/ads/googleads/v20/services/types/ad_parameter_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( ad_parameter as gagr_ad_parameter, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/ad_service.py b/google/ads/googleads/v20/services/types/ad_service.py index 310656c10..8e869d567 100644 --- a/google/ads/googleads/v20/services/types/ad_service.py +++ b/google/ads/googleads/v20/services/types/ad_service.py @@ -24,9 +24,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v20.resources.types import ad as gagr_ad -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/asset_group_asset_service.py b/google/ads/googleads/v20/services/types/asset_group_asset_service.py index 91219b408..a58a40aa5 100644 --- a/google/ads/googleads/v20/services/types/asset_group_asset_service.py +++ b/google/ads/googleads/v20/services/types/asset_group_asset_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import asset_group_asset -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/asset_group_listing_group_filter_service.py b/google/ads/googleads/v20/services/types/asset_group_listing_group_filter_service.py index 2a968e958..4276e4004 100644 --- a/google/ads/googleads/v20/services/types/asset_group_listing_group_filter_service.py +++ b/google/ads/googleads/v20/services/types/asset_group_listing_group_filter_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( asset_group_listing_group_filter as gagr_asset_group_listing_group_filter, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/asset_group_service.py b/google/ads/googleads/v20/services/types/asset_group_service.py index e840f57ae..06c7ff834 100644 --- a/google/ads/googleads/v20/services/types/asset_group_service.py +++ b/google/ads/googleads/v20/services/types/asset_group_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import asset_group -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/asset_group_signal_service.py b/google/ads/googleads/v20/services/types/asset_group_signal_service.py index c5dd1bfbb..8c5ceaf9e 100644 --- a/google/ads/googleads/v20/services/types/asset_group_signal_service.py +++ b/google/ads/googleads/v20/services/types/asset_group_signal_service.py @@ -26,8 +26,7 @@ from google.ads.googleads.v20.resources.types import ( asset_group_signal as gagr_asset_group_signal, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/asset_service.py b/google/ads/googleads/v20/services/types/asset_service.py index 6175d7b43..bc4af578e 100644 --- a/google/ads/googleads/v20/services/types/asset_service.py +++ b/google/ads/googleads/v20/services/types/asset_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v20.resources.types import asset as gagr_asset -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/asset_set_asset_service.py b/google/ads/googleads/v20/services/types/asset_set_asset_service.py index ba7e0f60a..6f4f8ba96 100644 --- a/google/ads/googleads/v20/services/types/asset_set_asset_service.py +++ b/google/ads/googleads/v20/services/types/asset_set_asset_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( asset_set_asset as gagr_asset_set_asset, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/asset_set_service.py b/google/ads/googleads/v20/services/types/asset_set_service.py index fc56fefae..ab2816268 100644 --- a/google/ads/googleads/v20/services/types/asset_set_service.py +++ b/google/ads/googleads/v20/services/types/asset_set_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v20.resources.types import asset_set as gagr_asset_set -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/audience_insights_service.py b/google/ads/googleads/v20/services/types/audience_insights_service.py index 6b9c9dd09..caf3be782 100644 --- a/google/ads/googleads/v20/services/types/audience_insights_service.py +++ b/google/ads/googleads/v20/services/types/audience_insights_service.py @@ -28,7 +28,6 @@ audience_insights_marketing_objective, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.services", marshal="google.ads.googleads.v20", @@ -729,7 +728,7 @@ class GenerateTargetingSuggestionMetricsResponse(proto.Message): suggestions (MutableSequence[google.ads.googleads.v20.services.types.TargetingSuggestionMetrics]): Suggested targetable audiences. There will be one suggestion for each - [GenerateTargetingSuggestionMetricsRequest.audiences] + [GenerateTargetingSuggestionMetricsRequest.audiences][google.ads.googleads.v20.services.GenerateTargetingSuggestionMetricsRequest.audiences] requested, matching the order requested. """ diff --git a/google/ads/googleads/v20/services/types/audience_service.py b/google/ads/googleads/v20/services/types/audience_service.py index 498c34264..e6ad5a460 100644 --- a/google/ads/googleads/v20/services/types/audience_service.py +++ b/google/ads/googleads/v20/services/types/audience_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v20.resources.types import audience as gagr_audience -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/batch_job_service.py b/google/ads/googleads/v20/services/types/batch_job_service.py index 8131908f0..1bc6c167a 100644 --- a/google/ads/googleads/v20/services/types/batch_job_service.py +++ b/google/ads/googleads/v20/services/types/batch_job_service.py @@ -24,8 +24,7 @@ ) from google.ads.googleads.v20.resources.types import batch_job from google.ads.googleads.v20.services.types import google_ads_service -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/bidding_data_exclusion_service.py b/google/ads/googleads/v20/services/types/bidding_data_exclusion_service.py index 0bac6e909..8bab24666 100644 --- a/google/ads/googleads/v20/services/types/bidding_data_exclusion_service.py +++ b/google/ads/googleads/v20/services/types/bidding_data_exclusion_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( bidding_data_exclusion as gagr_bidding_data_exclusion, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/bidding_seasonality_adjustment_service.py b/google/ads/googleads/v20/services/types/bidding_seasonality_adjustment_service.py index d4b838f2d..7b6e15993 100644 --- a/google/ads/googleads/v20/services/types/bidding_seasonality_adjustment_service.py +++ b/google/ads/googleads/v20/services/types/bidding_seasonality_adjustment_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( bidding_seasonality_adjustment as gagr_bidding_seasonality_adjustment, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/bidding_strategy_service.py b/google/ads/googleads/v20/services/types/bidding_strategy_service.py index 57618b375..5f41d8dae 100644 --- a/google/ads/googleads/v20/services/types/bidding_strategy_service.py +++ b/google/ads/googleads/v20/services/types/bidding_strategy_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( bidding_strategy as gagr_bidding_strategy, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_asset_service.py b/google/ads/googleads/v20/services/types/campaign_asset_service.py index 31d65c350..5690fc65f 100644 --- a/google/ads/googleads/v20/services/types/campaign_asset_service.py +++ b/google/ads/googleads/v20/services/types/campaign_asset_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( campaign_asset as gagr_campaign_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_asset_set_service.py b/google/ads/googleads/v20/services/types/campaign_asset_set_service.py index 078021d1f..e8b691988 100644 --- a/google/ads/googleads/v20/services/types/campaign_asset_set_service.py +++ b/google/ads/googleads/v20/services/types/campaign_asset_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( campaign_asset_set as gagr_campaign_asset_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_bid_modifier_service.py b/google/ads/googleads/v20/services/types/campaign_bid_modifier_service.py index c430998bf..37017556f 100644 --- a/google/ads/googleads/v20/services/types/campaign_bid_modifier_service.py +++ b/google/ads/googleads/v20/services/types/campaign_bid_modifier_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( campaign_bid_modifier as gagr_campaign_bid_modifier, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_budget_service.py b/google/ads/googleads/v20/services/types/campaign_budget_service.py index 98a404a9a..0ea3f289b 100644 --- a/google/ads/googleads/v20/services/types/campaign_budget_service.py +++ b/google/ads/googleads/v20/services/types/campaign_budget_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( campaign_budget as gagr_campaign_budget, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_conversion_goal_service.py b/google/ads/googleads/v20/services/types/campaign_conversion_goal_service.py index 7a52fb831..edcc371fb 100644 --- a/google/ads/googleads/v20/services/types/campaign_conversion_goal_service.py +++ b/google/ads/googleads/v20/services/types/campaign_conversion_goal_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import campaign_conversion_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_criterion_service.py b/google/ads/googleads/v20/services/types/campaign_criterion_service.py index 7a1e2383d..701f0edf7 100644 --- a/google/ads/googleads/v20/services/types/campaign_criterion_service.py +++ b/google/ads/googleads/v20/services/types/campaign_criterion_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( campaign_criterion as gagr_campaign_criterion, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_customizer_service.py b/google/ads/googleads/v20/services/types/campaign_customizer_service.py index 230bc0ec0..1e648e184 100644 --- a/google/ads/googleads/v20/services/types/campaign_customizer_service.py +++ b/google/ads/googleads/v20/services/types/campaign_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( campaign_customizer as gagr_campaign_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_draft_service.py b/google/ads/googleads/v20/services/types/campaign_draft_service.py index 6965bc545..d6433bea3 100644 --- a/google/ads/googleads/v20/services/types/campaign_draft_service.py +++ b/google/ads/googleads/v20/services/types/campaign_draft_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( campaign_draft as gagr_campaign_draft, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_group_service.py b/google/ads/googleads/v20/services/types/campaign_group_service.py index 82968c3d7..b05601199 100644 --- a/google/ads/googleads/v20/services/types/campaign_group_service.py +++ b/google/ads/googleads/v20/services/types/campaign_group_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( campaign_group as gagr_campaign_group, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_label_service.py b/google/ads/googleads/v20/services/types/campaign_label_service.py index d5a553f4b..b124db0a0 100644 --- a/google/ads/googleads/v20/services/types/campaign_label_service.py +++ b/google/ads/googleads/v20/services/types/campaign_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import campaign_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_lifecycle_goal_service.py b/google/ads/googleads/v20/services/types/campaign_lifecycle_goal_service.py index ad6e3560a..8bd588d08 100644 --- a/google/ads/googleads/v20/services/types/campaign_lifecycle_goal_service.py +++ b/google/ads/googleads/v20/services/types/campaign_lifecycle_goal_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import campaign_lifecycle_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", @@ -36,7 +35,7 @@ class ConfigureCampaignLifecycleGoalsRequest(proto.Message): r"""Request message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v20.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. Attributes: customer_id (str): @@ -115,7 +114,7 @@ class CampaignLifecycleGoalOperation(proto.Message): class ConfigureCampaignLifecycleGoalsResponse(proto.Message): r"""Response message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v20.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. Attributes: result (google.ads.googleads.v20.services.types.ConfigureCampaignLifecycleGoalsResult): diff --git a/google/ads/googleads/v20/services/types/campaign_service.py b/google/ads/googleads/v20/services/types/campaign_service.py index 58dda7b30..fe81c7d90 100644 --- a/google/ads/googleads/v20/services/types/campaign_service.py +++ b/google/ads/googleads/v20/services/types/campaign_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v20.resources.types import campaign as gagr_campaign -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/campaign_shared_set_service.py b/google/ads/googleads/v20/services/types/campaign_shared_set_service.py index 5088f6aac..1da5b3f17 100644 --- a/google/ads/googleads/v20/services/types/campaign_shared_set_service.py +++ b/google/ads/googleads/v20/services/types/campaign_shared_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( campaign_shared_set as gagr_campaign_shared_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/content_creator_insights_service.py b/google/ads/googleads/v20/services/types/content_creator_insights_service.py index 376f29fbb..bdda72f02 100644 --- a/google/ads/googleads/v20/services/types/content_creator_insights_service.py +++ b/google/ads/googleads/v20/services/types/content_creator_insights_service.py @@ -24,7 +24,6 @@ from google.ads.googleads.v20.common.types import criteria from google.ads.googleads.v20.enums.types import insights_trend - __protobuf__ = proto.module( package="google.ads.googleads.v20.services", marshal="google.ads.googleads.v20", @@ -69,24 +68,28 @@ class GenerateCreatorInsightsRequest(proto.Message): to the criteria. sub_country_locations (MutableSequence[google.ads.googleads.v20.common.types.LocationInfo]): The sub-country geographic locations to search that apply to - the criteria. Only supported for [SearchAttributes] + the criteria. Only supported for + [SearchAttributes][google.ads.googleads.v20.services.GenerateCreatorInsightsRequest.SearchAttributes] criteria. search_attributes (google.ads.googleads.v20.services.types.GenerateCreatorInsightsRequest.SearchAttributes): The attributes used to identify top creators. Data fetched is based on the list of countries or sub-country locations - specified in [country_locations] or [sub_country_locations]. + specified in + [country_locations][google.ads.googleads.v20.services.GenerateCreatorInsightsRequest.country_locations] + or + [sub_country_locations][google.ads.googleads.v20.services.GenerateCreatorInsightsRequest.sub_country_locations]. This field is a member of `oneof`_ ``criteria``. search_brand (google.ads.googleads.v20.services.types.GenerateCreatorInsightsRequest.SearchBrand): A brand used to search for top creators. Data fetched is based on the list of countries specified in - [country_locations]. + [country_locations][google.ads.googleads.v20.services.GenerateCreatorInsightsRequest.country_locations]. This field is a member of `oneof`_ ``criteria``. search_channels (google.ads.googleads.v20.services.types.GenerateCreatorInsightsRequest.YouTubeChannels): YouTube Channel IDs for Creator Insights. Data fetched for channels is based on the list of countries specified in - [country_locations]. + [country_locations][google.ads.googleads.v20.services.GenerateCreatorInsightsRequest.country_locations]. This field is a member of `oneof`_ ``criteria``. """ @@ -109,7 +112,7 @@ class SearchAttributes(proto.Message): types of content. This is used to search for creators whose content matches the input creator attributes. Attribute entity tagged with - [InsightsKnowledgeGraphEntityCapabilities.CREATOR_ATTRIBUTE][] + [CREATOR_ATTRIBUTE][google.ads.googleads.v20.enums.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities.CREATOR_ATTRIBUTE] is supported. Other attributes including location are not supported. """ @@ -139,9 +142,10 @@ class SearchBrand(proto.Message): find insights. include_related_topics (bool): Optional. When true, we will expand the search to beyond - just the entities specified in [brand_entities] to other - related knowledge graph entities similar to the brand. The - default value is ``false``. + just the entities specified in + [brand_entities][google.ads.googleads.v20.services.GenerateCreatorInsightsRequest.SearchBrand.brand_entities] + to other related knowledge graph entities similar to the + brand. The default value is ``false``. """ brand_entities: MutableSequence[ @@ -244,7 +248,7 @@ class GenerateCreatorInsightsResponse(proto.Message): class GenerateTrendingInsightsRequest(proto.Message): r"""Request message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v20.services.ContentCreatorInsightsService.GenerateTrendingInsights]. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -312,7 +316,7 @@ class GenerateTrendingInsightsRequest(proto.Message): class GenerateTrendingInsightsResponse(proto.Message): r"""Response message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v20.services.ContentCreatorInsightsService.GenerateTrendingInsights]. Attributes: trend_insights (MutableSequence[google.ads.googleads.v20.services.types.TrendInsight]): @@ -373,7 +377,7 @@ class YouTubeMetrics(proto.Message): The lifetime engagement rate of this channel. The value is computed as the total number of likes, shares, and comments across all videos - divided by the total number of videos. + divided by the total number of video views. average_views_per_video (float): The average number of views per video in the last 28 days. @@ -577,7 +581,10 @@ class SearchTopics(proto.Message): entities (MutableSequence[google.ads.googleads.v20.common.types.AudienceInsightsEntity]): Required. A list of knowledge graph entities to retrieve trend information for. Supported entities are tagged with - [InsightsKnowledgeGraphEntityCapabilities.CONTENT_TRENDING_INSIGHTS][]. + [CONTENT_TRENDING_INSIGHTS][google.ads.googleads.v20.enums.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities.CONTENT_TRENDING_INSIGHTS]. + Use + [AudienceInsightsService.ListAudienceInsightsAttributes][google.ads.googleads.v20.services.AudienceInsightsService.ListAudienceInsightsAttributes] + to get the list of supported entities. """ entities: MutableSequence[ @@ -596,7 +603,9 @@ class TrendInsight(proto.Message): trend_attribute (google.ads.googleads.v20.common.types.AudienceInsightsAttributeMetadata): The attribute this trend is for. trend_metrics (google.ads.googleads.v20.services.types.TrendInsightMetrics): - Metrics associated with this trend. + Metrics associated with this trend. These + metrics are for the latest available month and + the comparison period is 3 months. trend (google.ads.googleads.v20.enums.types.InsightsTrendEnum.InsightsTrend): The direction of trend (such as RISING or DECLINING). diff --git a/google/ads/googleads/v20/services/types/conversion_action_service.py b/google/ads/googleads/v20/services/types/conversion_action_service.py index 7a87da470..a6d57de2c 100644 --- a/google/ads/googleads/v20/services/types/conversion_action_service.py +++ b/google/ads/googleads/v20/services/types/conversion_action_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( conversion_action as gagr_conversion_action, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/conversion_adjustment_upload_service.py b/google/ads/googleads/v20/services/types/conversion_adjustment_upload_service.py index 1632cf036..eb810007d 100644 --- a/google/ads/googleads/v20/services/types/conversion_adjustment_upload_service.py +++ b/google/ads/googleads/v20/services/types/conversion_adjustment_upload_service.py @@ -21,8 +21,7 @@ from google.ads.googleads.v20.common.types import offline_user_data from google.ads.googleads.v20.enums.types import conversion_adjustment_type -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", @@ -174,7 +173,7 @@ class ConversionAdjustment(proto.Message): adjustment_date_time (str): The date time at which the adjustment occurred. Must be after the conversion_date_time. The timezone must be - specified. The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for + specified. The format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_adjustment_date_time``. @@ -314,7 +313,7 @@ class GclidDateTimePair(proto.Message): conversion_date_time (str): The date time at which the original conversion for this adjustment occurred. The timezone must be specified. The - format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, + format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. @@ -353,7 +352,7 @@ class ConversionAdjustmentResult(proto.Message): This field is a member of `oneof`_ ``_conversion_action``. adjustment_date_time (str): The date time at which the adjustment occurred. The format - is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, "2019-01-01 + is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_adjustment_date_time``. diff --git a/google/ads/googleads/v20/services/types/conversion_custom_variable_service.py b/google/ads/googleads/v20/services/types/conversion_custom_variable_service.py index 3ca049570..72d37a7e1 100644 --- a/google/ads/googleads/v20/services/types/conversion_custom_variable_service.py +++ b/google/ads/googleads/v20/services/types/conversion_custom_variable_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( conversion_custom_variable as gagr_conversion_custom_variable, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/conversion_goal_campaign_config_service.py b/google/ads/googleads/v20/services/types/conversion_goal_campaign_config_service.py index 59536e235..7c430f7a5 100644 --- a/google/ads/googleads/v20/services/types/conversion_goal_campaign_config_service.py +++ b/google/ads/googleads/v20/services/types/conversion_goal_campaign_config_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( conversion_goal_campaign_config as gagr_conversion_goal_campaign_config, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/conversion_upload_service.py b/google/ads/googleads/v20/services/types/conversion_upload_service.py index c198334fd..4a34b2313 100644 --- a/google/ads/googleads/v20/services/types/conversion_upload_service.py +++ b/google/ads/googleads/v20/services/types/conversion_upload_service.py @@ -23,8 +23,7 @@ from google.ads.googleads.v20.common.types import offline_user_data from google.ads.googleads.v20.enums.types import conversion_customer_type from google.ads.googleads.v20.enums.types import conversion_environment_enum -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", @@ -83,11 +82,11 @@ class UploadClickConversionsRequest(proto.Message): This setting only affects Enhanced conversions for leads uploads that use ``user_identifiers`` instead of ``GCLID``, - ``GBRAID``, or ``WBRAID``. When uploading enhanced - conversions for leads, you should upload all conversion - events to the API, including those that may not come from - Google Ads campaigns. The upload of an event that is not - from a Google Ads campaign will result in a + or the ``GBRAID`` or ``WBRAID`` URL parameters. When + uploading enhanced conversions for leads, you should upload + all conversion events to the API, including those that may + not come from Google Ads campaigns. The upload of an event + that is not from a Google Ads campaign will result in a ``CLICK_NOT_FOUND`` error if this field is set to ``true``. Since these errors are expected for such events, set this field to ``false`` so you can confirm your uploads are @@ -268,13 +267,11 @@ class ClickConversion(proto.Message): This field is a member of `oneof`_ ``_gclid``. gbraid (str): - The click identifier for clicks associated - with app conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + app conversions. wbraid (str): - The click identifier for clicks associated - with web conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + web conversions. conversion_action (str): Resource name of the conversion action associated with this conversion. Note: Although @@ -287,7 +284,7 @@ class ClickConversion(proto.Message): conversion_date_time (str): The date time at which the conversion occurred. Must be after the click time. The timezone must be specified. The - format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, + format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. @@ -351,7 +348,10 @@ class ClickConversion(proto.Message): consent where required by law or any applicable Google policies. See the https://support.google.com/google-ads/answer/2998031 - page for more details. + page for more details. This field is only + available to allowlisted users. To include this + field in conversion imports, upgrade to the Data + Manager API. This field is a member of `oneof`_ ``_user_ip_address``. session_attributes_encoded (bytes): @@ -359,12 +359,17 @@ class ClickConversion(proto.Message): base64-encoded JSON string. The content should be generated by Google-provided library. To set session attributes individually, use session_attributes_key_value_pairs - instead. + instead. This field is only available to allowlisted users. + To include this field in conversion imports, upgrade to the + Data Manager API. This field is a member of `oneof`_ ``session_attributes``. session_attributes_key_value_pairs (google.ads.googleads.v20.services.types.SessionAttributesKeyValuePairs): The session attributes for the event, - represented as key-value pairs. + represented as key-value pairs. This field is + only available to allowlisted users. To include + this field in conversion imports, upgrade to the + Data Manager API. This field is a member of `oneof`_ ``session_attributes``. """ @@ -483,7 +488,7 @@ class CallConversion(proto.Message): This field is a member of `oneof`_ ``_caller_id``. call_start_date_time (str): The date time at which the call occurred. The timezone must - be specified. The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", + be specified. The format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_call_start_date_time``. @@ -499,7 +504,7 @@ class CallConversion(proto.Message): conversion_date_time (str): The date time at which the conversion occurred. Must be after the call time. The timezone must be specified. The - format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, + format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. @@ -608,13 +613,11 @@ class ClickConversionResult(proto.Message): This field is a member of `oneof`_ ``_gclid``. gbraid (str): - The click identifier for clicks associated - with app conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + app conversions. wbraid (str): - The click identifier for clicks associated - with web conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + web conversions. conversion_action (str): Resource name of the conversion action associated with this conversion. @@ -622,7 +625,7 @@ class ClickConversionResult(proto.Message): This field is a member of `oneof`_ ``_conversion_action``. conversion_date_time (str): The date time at which the conversion occurred. The format - is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, "2019-01-01 + is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. @@ -681,7 +684,7 @@ class CallConversionResult(proto.Message): This field is a member of `oneof`_ ``_caller_id``. call_start_date_time (str): The date time at which the call occurred. The format is - "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, "2019-01-01 + "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_call_start_date_time``. @@ -692,7 +695,7 @@ class CallConversionResult(proto.Message): This field is a member of `oneof`_ ``_conversion_action``. conversion_date_time (str): The date time at which the conversion occurred. The format - is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, "2019-01-01 + is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. diff --git a/google/ads/googleads/v20/services/types/conversion_value_rule_service.py b/google/ads/googleads/v20/services/types/conversion_value_rule_service.py index 1e0b5cc56..5b7253c60 100644 --- a/google/ads/googleads/v20/services/types/conversion_value_rule_service.py +++ b/google/ads/googleads/v20/services/types/conversion_value_rule_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( conversion_value_rule as gagr_conversion_value_rule, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/conversion_value_rule_set_service.py b/google/ads/googleads/v20/services/types/conversion_value_rule_set_service.py index 2b3cd81a5..1ae220d8a 100644 --- a/google/ads/googleads/v20/services/types/conversion_value_rule_set_service.py +++ b/google/ads/googleads/v20/services/types/conversion_value_rule_set_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( conversion_value_rule_set as gagr_conversion_value_rule_set, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/custom_audience_service.py b/google/ads/googleads/v20/services/types/custom_audience_service.py index b08110692..5d8a6471f 100644 --- a/google/ads/googleads/v20/services/types/custom_audience_service.py +++ b/google/ads/googleads/v20/services/types/custom_audience_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import custom_audience -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/custom_conversion_goal_service.py b/google/ads/googleads/v20/services/types/custom_conversion_goal_service.py index 6ec332d09..c8270a7d7 100644 --- a/google/ads/googleads/v20/services/types/custom_conversion_goal_service.py +++ b/google/ads/googleads/v20/services/types/custom_conversion_goal_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( custom_conversion_goal as gagr_custom_conversion_goal, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/custom_interest_service.py b/google/ads/googleads/v20/services/types/custom_interest_service.py index 661559f4f..cb9913077 100644 --- a/google/ads/googleads/v20/services/types/custom_interest_service.py +++ b/google/ads/googleads/v20/services/types/custom_interest_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import custom_interest -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_asset_service.py b/google/ads/googleads/v20/services/types/customer_asset_service.py index 9722d6733..0c40dc5d5 100644 --- a/google/ads/googleads/v20/services/types/customer_asset_service.py +++ b/google/ads/googleads/v20/services/types/customer_asset_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( customer_asset as gagr_customer_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_asset_set_service.py b/google/ads/googleads/v20/services/types/customer_asset_set_service.py index 6dedcba4c..6e738bf93 100644 --- a/google/ads/googleads/v20/services/types/customer_asset_set_service.py +++ b/google/ads/googleads/v20/services/types/customer_asset_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( customer_asset_set as gagr_customer_asset_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_client_link_service.py b/google/ads/googleads/v20/services/types/customer_client_link_service.py index c97ea5c67..bf3c0d07d 100644 --- a/google/ads/googleads/v20/services/types/customer_client_link_service.py +++ b/google/ads/googleads/v20/services/types/customer_client_link_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import customer_client_link -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_conversion_goal_service.py b/google/ads/googleads/v20/services/types/customer_conversion_goal_service.py index 5639ffdd9..de3c9500c 100644 --- a/google/ads/googleads/v20/services/types/customer_conversion_goal_service.py +++ b/google/ads/googleads/v20/services/types/customer_conversion_goal_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import customer_conversion_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_customizer_service.py b/google/ads/googleads/v20/services/types/customer_customizer_service.py index ea77f7d80..a9e457861 100644 --- a/google/ads/googleads/v20/services/types/customer_customizer_service.py +++ b/google/ads/googleads/v20/services/types/customer_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( customer_customizer as gagr_customer_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_label_service.py b/google/ads/googleads/v20/services/types/customer_label_service.py index 7caea47ba..4c1dca2d2 100644 --- a/google/ads/googleads/v20/services/types/customer_label_service.py +++ b/google/ads/googleads/v20/services/types/customer_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import customer_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_lifecycle_goal_service.py b/google/ads/googleads/v20/services/types/customer_lifecycle_goal_service.py index 372a31e5d..03db30552 100644 --- a/google/ads/googleads/v20/services/types/customer_lifecycle_goal_service.py +++ b/google/ads/googleads/v20/services/types/customer_lifecycle_goal_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import customer_lifecycle_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", @@ -36,7 +35,7 @@ class ConfigureCustomerLifecycleGoalsRequest(proto.Message): r"""Request message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v20.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. Attributes: customer_id (str): @@ -113,7 +112,7 @@ class CustomerLifecycleGoalOperation(proto.Message): class ConfigureCustomerLifecycleGoalsResponse(proto.Message): r"""Response message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v20.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. Attributes: result (google.ads.googleads.v20.services.types.ConfigureCustomerLifecycleGoalsResult): diff --git a/google/ads/googleads/v20/services/types/customer_manager_link_service.py b/google/ads/googleads/v20/services/types/customer_manager_link_service.py index 5ab7acc15..620f26e30 100644 --- a/google/ads/googleads/v20/services/types/customer_manager_link_service.py +++ b/google/ads/googleads/v20/services/types/customer_manager_link_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import customer_manager_link -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_negative_criterion_service.py b/google/ads/googleads/v20/services/types/customer_negative_criterion_service.py index 59dd7e283..990d5d31e 100644 --- a/google/ads/googleads/v20/services/types/customer_negative_criterion_service.py +++ b/google/ads/googleads/v20/services/types/customer_negative_criterion_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( customer_negative_criterion as gagr_customer_negative_criterion, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_service.py b/google/ads/googleads/v20/services/types/customer_service.py index e3719138b..c452f609b 100644 --- a/google/ads/googleads/v20/services/types/customer_service.py +++ b/google/ads/googleads/v20/services/types/customer_service.py @@ -24,8 +24,7 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v20.resources.types import customer as gagr_customer -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_sk_ad_network_conversion_value_schema_service.py b/google/ads/googleads/v20/services/types/customer_sk_ad_network_conversion_value_schema_service.py index 2000dcd08..1ebb03dd5 100644 --- a/google/ads/googleads/v20/services/types/customer_sk_ad_network_conversion_value_schema_service.py +++ b/google/ads/googleads/v20/services/types/customer_sk_ad_network_conversion_value_schema_service.py @@ -21,8 +21,7 @@ from google.ads.googleads.v20.resources.types import ( customer_sk_ad_network_conversion_value_schema, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customer_user_access_service.py b/google/ads/googleads/v20/services/types/customer_user_access_service.py index f36adfbd4..1521e2085 100644 --- a/google/ads/googleads/v20/services/types/customer_user_access_service.py +++ b/google/ads/googleads/v20/services/types/customer_user_access_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import customer_user_access -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/customizer_attribute_service.py b/google/ads/googleads/v20/services/types/customizer_attribute_service.py index cf2b11ba0..1c903103f 100644 --- a/google/ads/googleads/v20/services/types/customizer_attribute_service.py +++ b/google/ads/googleads/v20/services/types/customizer_attribute_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( customizer_attribute as gagr_customizer_attribute, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/experiment_arm_service.py b/google/ads/googleads/v20/services/types/experiment_arm_service.py index 202463622..da804bcc2 100644 --- a/google/ads/googleads/v20/services/types/experiment_arm_service.py +++ b/google/ads/googleads/v20/services/types/experiment_arm_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( experiment_arm as gagr_experiment_arm, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/experiment_service.py b/google/ads/googleads/v20/services/types/experiment_service.py index a15197fc0..1b66322a1 100644 --- a/google/ads/googleads/v20/services/types/experiment_service.py +++ b/google/ads/googleads/v20/services/types/experiment_service.py @@ -22,9 +22,8 @@ from google.ads.googleads.v20.resources.types import ( experiment as gagr_experiment, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/google_ads_service.py b/google/ads/googleads/v20/services/types/google_ads_service.py index a5e2cbb06..3c64e5758 100644 --- a/google/ads/googleads/v20/services/types/google_ads_service.py +++ b/google/ads/googleads/v20/services/types/google_ads_service.py @@ -606,9 +606,8 @@ smart_campaign_setting_service, ) from google.ads.googleads.v20.services.types import user_list_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/identity_verification_service.py b/google/ads/googleads/v20/services/types/identity_verification_service.py index 8fc3c71a0..001bf0b0f 100644 --- a/google/ads/googleads/v20/services/types/identity_verification_service.py +++ b/google/ads/googleads/v20/services/types/identity_verification_service.py @@ -24,7 +24,6 @@ identity_verification_program_status, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.services", marshal="google.ads.googleads.v20", @@ -41,7 +40,7 @@ class StartIdentityVerificationRequest(proto.Message): r"""Request message for - [IdentityVerificationService.StartIdentityVerification]. + [StartIdentityVerification][google.ads.googleads.v20.services.IdentityVerificationService.StartIdentityVerification]. Attributes: customer_id (str): @@ -67,7 +66,7 @@ class StartIdentityVerificationRequest(proto.Message): class GetIdentityVerificationRequest(proto.Message): r"""Request message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v20.services.IdentityVerificationService.GetIdentityVerification]. Attributes: customer_id (str): @@ -83,7 +82,7 @@ class GetIdentityVerificationRequest(proto.Message): class GetIdentityVerificationResponse(proto.Message): r"""Response message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v20.services.IdentityVerificationService.GetIdentityVerification]. Attributes: identity_verification (MutableSequence[google.ads.googleads.v20.services.types.IdentityVerification]): diff --git a/google/ads/googleads/v20/services/types/keyword_plan_ad_group_keyword_service.py b/google/ads/googleads/v20/services/types/keyword_plan_ad_group_keyword_service.py index 58a102a0c..6230243ed 100644 --- a/google/ads/googleads/v20/services/types/keyword_plan_ad_group_keyword_service.py +++ b/google/ads/googleads/v20/services/types/keyword_plan_ad_group_keyword_service.py @@ -22,9 +22,8 @@ from google.ads.googleads.v20.resources.types import ( keyword_plan_ad_group_keyword, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/keyword_plan_ad_group_service.py b/google/ads/googleads/v20/services/types/keyword_plan_ad_group_service.py index b44d9545d..2e05537e6 100644 --- a/google/ads/googleads/v20/services/types/keyword_plan_ad_group_service.py +++ b/google/ads/googleads/v20/services/types/keyword_plan_ad_group_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import keyword_plan_ad_group -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/keyword_plan_campaign_keyword_service.py b/google/ads/googleads/v20/services/types/keyword_plan_campaign_keyword_service.py index e5ea4ae5c..2435e8264 100644 --- a/google/ads/googleads/v20/services/types/keyword_plan_campaign_keyword_service.py +++ b/google/ads/googleads/v20/services/types/keyword_plan_campaign_keyword_service.py @@ -22,9 +22,8 @@ from google.ads.googleads.v20.resources.types import ( keyword_plan_campaign_keyword, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/keyword_plan_campaign_service.py b/google/ads/googleads/v20/services/types/keyword_plan_campaign_service.py index c8943ea60..5c256ec88 100644 --- a/google/ads/googleads/v20/services/types/keyword_plan_campaign_service.py +++ b/google/ads/googleads/v20/services/types/keyword_plan_campaign_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import keyword_plan_campaign -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/keyword_plan_idea_service.py b/google/ads/googleads/v20/services/types/keyword_plan_idea_service.py index 5714d76f2..fef8dd986 100644 --- a/google/ads/googleads/v20/services/types/keyword_plan_idea_service.py +++ b/google/ads/googleads/v20/services/types/keyword_plan_idea_service.py @@ -28,7 +28,6 @@ keyword_plan_network as gage_keyword_plan_network, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.services", marshal="google.ads.googleads.v20", @@ -664,8 +663,8 @@ class UnusableAdGroup(proto.Message): AdGroups may not be usable if the AdGroup - - belongs to a Campaign that is not ENABLED or PAUSED - - is itself not ENABLED + - belongs to a Campaign that is not ENABLED or PAUSED + - is itself not ENABLED Attributes: ad_group (str): @@ -688,7 +687,7 @@ class UnusableAdGroup(proto.Message): class GenerateKeywordForecastMetricsRequest(proto.Message): r"""Request message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v20.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -1049,7 +1048,7 @@ class MaximizeConversionsBiddingStrategy(proto.Message): class GenerateKeywordForecastMetricsResponse(proto.Message): r"""Response message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v20.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v20/services/types/keyword_plan_service.py b/google/ads/googleads/v20/services/types/keyword_plan_service.py index d3686c498..9b1bc0065 100644 --- a/google/ads/googleads/v20/services/types/keyword_plan_service.py +++ b/google/ads/googleads/v20/services/types/keyword_plan_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import keyword_plan -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/label_service.py b/google/ads/googleads/v20/services/types/label_service.py index 386dfc491..35de38679 100644 --- a/google/ads/googleads/v20/services/types/label_service.py +++ b/google/ads/googleads/v20/services/types/label_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v20.resources.types import label as gagr_label -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/local_services_lead_service.py b/google/ads/googleads/v20/services/types/local_services_lead_service.py index 8022c467f..c0c86c02d 100644 --- a/google/ads/googleads/v20/services/types/local_services_lead_service.py +++ b/google/ads/googleads/v20/services/types/local_services_lead_service.py @@ -31,8 +31,7 @@ from google.ads.googleads.v20.enums.types import ( local_services_lead_survey_satisfied_reason, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/offline_user_data_job_service.py b/google/ads/googleads/v20/services/types/offline_user_data_job_service.py index 817b4043a..e2f907a16 100644 --- a/google/ads/googleads/v20/services/types/offline_user_data_job_service.py +++ b/google/ads/googleads/v20/services/types/offline_user_data_job_service.py @@ -21,8 +21,7 @@ from google.ads.googleads.v20.common.types import offline_user_data from google.ads.googleads.v20.resources.types import offline_user_data_job -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/product_link_invitation_service.py b/google/ads/googleads/v20/services/types/product_link_invitation_service.py index 0dbf18c74..169a92c90 100644 --- a/google/ads/googleads/v20/services/types/product_link_invitation_service.py +++ b/google/ads/googleads/v20/services/types/product_link_invitation_service.py @@ -25,7 +25,6 @@ product_link_invitation as gagr_product_link_invitation, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.services", marshal="google.ads.googleads.v20", @@ -129,7 +128,7 @@ class UpdateProductLinkInvitationResponse(proto.Message): class RemoveProductLinkInvitationRequest(proto.Message): r"""Request message for - [ProductLinkinvitationService.RemoveProductLinkInvitation][]. + [ProductLinkInvitationService.RemoveProductLinkInvitation][google.ads.googleads.v20.services.ProductLinkInvitationService.RemoveProductLinkInvitation]. Attributes: customer_id (str): @@ -139,7 +138,7 @@ class RemoveProductLinkInvitationRequest(proto.Message): Required. The resource name of the product link invitation being removed. expected, in this format: - ```` + ``customers/{customer_id}/productLinkInvitations/{product_link_invitation_id}`` """ customer_id: str = proto.Field( diff --git a/google/ads/googleads/v20/services/types/reach_plan_service.py b/google/ads/googleads/v20/services/types/reach_plan_service.py index 825fd899c..69ac94831 100644 --- a/google/ads/googleads/v20/services/types/reach_plan_service.py +++ b/google/ads/googleads/v20/services/types/reach_plan_service.py @@ -37,7 +37,6 @@ user_list_type as gage_user_list_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.services", marshal="google.ads.googleads.v20", @@ -1309,10 +1308,10 @@ class OnTargetAudienceMetrics(proto.Message): r"""Audience metrics for the planned products. These metrics consider the following targeting dimensions: - - Location - - PlannableAgeRange - - Gender - - AudienceTargeting (only for youtube_audience_size) + - Location + - PlannableAgeRange + - Gender + - AudienceTargeting (only for youtube_audience_size) .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v20/services/types/recommendation_service.py b/google/ads/googleads/v20/services/types/recommendation_service.py index eed199a0c..08f2eeb37 100644 --- a/google/ads/googleads/v20/services/types/recommendation_service.py +++ b/google/ads/googleads/v20/services/types/recommendation_service.py @@ -39,8 +39,7 @@ from google.ads.googleads.v20.resources.types import ad as gagr_ad from google.ads.googleads.v20.resources.types import asset from google.ads.googleads.v20.resources.types import recommendation -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/recommendation_subscription_service.py b/google/ads/googleads/v20/services/types/recommendation_subscription_service.py index 4aa03b05e..af011302f 100644 --- a/google/ads/googleads/v20/services/types/recommendation_subscription_service.py +++ b/google/ads/googleads/v20/services/types/recommendation_subscription_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( recommendation_subscription as gagr_recommendation_subscription, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", @@ -43,7 +42,7 @@ class MutateRecommendationSubscriptionRequest(proto.Message): r"""Request message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v20.services.RecommendationSubscriptionService.MutateRecommendationSubscription] Attributes: customer_id (str): @@ -100,7 +99,7 @@ class MutateRecommendationSubscriptionRequest(proto.Message): class RecommendationSubscriptionOperation(proto.Message): r"""A single operation (create, update) on a recommendation subscription. - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v20.services.RecommendationSubscriptionService.MutateRecommendationSubscription] This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -150,7 +149,7 @@ class RecommendationSubscriptionOperation(proto.Message): class MutateRecommendationSubscriptionResponse(proto.Message): r"""Response message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v20.services.RecommendationSubscriptionService.MutateRecommendationSubscription] Attributes: results (MutableSequence[google.ads.googleads.v20.services.types.MutateRecommendationSubscriptionResult]): @@ -179,7 +178,7 @@ class MutateRecommendationSubscriptionResponse(proto.Message): class MutateRecommendationSubscriptionResult(proto.Message): r"""Result message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v20.services.RecommendationSubscriptionService.MutateRecommendationSubscription] Attributes: resource_name (str): diff --git a/google/ads/googleads/v20/services/types/remarketing_action_service.py b/google/ads/googleads/v20/services/types/remarketing_action_service.py index fe9a57db0..d7dafe8f5 100644 --- a/google/ads/googleads/v20/services/types/remarketing_action_service.py +++ b/google/ads/googleads/v20/services/types/remarketing_action_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import remarketing_action -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/shareable_preview_service.py b/google/ads/googleads/v20/services/types/shareable_preview_service.py index 6a29f31da..e8539d1ea 100644 --- a/google/ads/googleads/v20/services/types/shareable_preview_service.py +++ b/google/ads/googleads/v20/services/types/shareable_preview_service.py @@ -19,8 +19,7 @@ import proto # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/shared_criterion_service.py b/google/ads/googleads/v20/services/types/shared_criterion_service.py index 56fd5e07d..9004deea2 100644 --- a/google/ads/googleads/v20/services/types/shared_criterion_service.py +++ b/google/ads/googleads/v20/services/types/shared_criterion_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v20.resources.types import ( shared_criterion as gagr_shared_criterion, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/shared_set_service.py b/google/ads/googleads/v20/services/types/shared_set_service.py index 1cbedf175..8e29bc71d 100644 --- a/google/ads/googleads/v20/services/types/shared_set_service.py +++ b/google/ads/googleads/v20/services/types/shared_set_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v20.resources.types import ( shared_set as gagr_shared_set, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/smart_campaign_setting_service.py b/google/ads/googleads/v20/services/types/smart_campaign_setting_service.py index ddacb552b..680f628b7 100644 --- a/google/ads/googleads/v20/services/types/smart_campaign_setting_service.py +++ b/google/ads/googleads/v20/services/types/smart_campaign_setting_service.py @@ -31,9 +31,8 @@ from google.ads.googleads.v20.resources.types import ( smart_campaign_setting as gagr_smart_campaign_setting, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/smart_campaign_suggest_service.py b/google/ads/googleads/v20/services/types/smart_campaign_suggest_service.py index a3efdb87a..776ae5d82 100644 --- a/google/ads/googleads/v20/services/types/smart_campaign_suggest_service.py +++ b/google/ads/googleads/v20/services/types/smart_campaign_suggest_service.py @@ -25,7 +25,6 @@ keyword_theme_constant as gagr_keyword_theme_constant, ) - __protobuf__ = proto.module( package="google.ads.googleads.v20.services", marshal="google.ads.googleads.v20", @@ -355,13 +354,13 @@ class SuggestKeywordThemesRequest(proto.Message): Required. Information to get keyword theme suggestions. Required fields: - - suggestion_info.final_url - - suggestion_info.language_code - - suggestion_info.geo_target + - suggestion_info.final_url + - suggestion_info.language_code + - suggestion_info.geo_target Recommended fields: - - suggestion_info.business_setting + - suggestion_info.business_setting """ customer_id: str = proto.Field( diff --git a/google/ads/googleads/v20/services/types/user_data_service.py b/google/ads/googleads/v20/services/types/user_data_service.py index 4ba50f1bf..ac9c86484 100644 --- a/google/ads/googleads/v20/services/types/user_data_service.py +++ b/google/ads/googleads/v20/services/types/user_data_service.py @@ -21,7 +21,6 @@ from google.ads.googleads.v20.common.types import offline_user_data - __protobuf__ = proto.module( package="google.ads.googleads.v20.services", marshal="google.ads.googleads.v20", @@ -122,7 +121,7 @@ class UploadUserDataResponse(proto.Message): Attributes: upload_date_time (str): The date time at which the request was received by API, - formatted as "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, + formatted as "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_upload_date_time``. diff --git a/google/ads/googleads/v20/services/types/user_list_customer_type_service.py b/google/ads/googleads/v20/services/types/user_list_customer_type_service.py index 1201c6076..1449ea2c7 100644 --- a/google/ads/googleads/v20/services/types/user_list_customer_type_service.py +++ b/google/ads/googleads/v20/services/types/user_list_customer_type_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import user_list_customer_type -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v20/services/types/user_list_service.py b/google/ads/googleads/v20/services/types/user_list_service.py index 9e639f937..855a94747 100644 --- a/google/ads/googleads/v20/services/types/user_list_service.py +++ b/google/ads/googleads/v20/services/types/user_list_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v20.resources.types import user_list -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v20.services", diff --git a/google/ads/googleads/v21/__init__.py b/google/ads/googleads/v21/__init__.py index 17f81efcf..e140eaddb 100644 --- a/google/ads/googleads/v21/__init__.py +++ b/google/ads/googleads/v21/__init__.py @@ -15,14 +15,117 @@ # from google.ads.googleads.v21 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from . import common from . import enums from . import errors from . import resources from . import services +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v21") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v21") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v21" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( "common", diff --git a/google/ads/googleads/v21/common/__init__.py b/google/ads/googleads/v21/common/__init__.py index 258d0c4e3..b80a2c8a1 100644 --- a/google/ads/googleads/v21/common/__init__.py +++ b/google/ads/googleads/v21/common/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v21 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.ad_asset import AdAppDeepLinkAsset from .types.ad_asset import AdCallToActionAsset @@ -377,6 +387,100 @@ from .types.user_lists import UserListStringRuleItemInfo from .types.value import Value +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v21") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v21") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v21" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "ActivityCityInfo", "ActivityCountryInfo", diff --git a/google/ads/googleads/v21/common/types/additional_application_info.py b/google/ads/googleads/v21/common/types/additional_application_info.py index 64edccb65..999c49439 100644 --- a/google/ads/googleads/v21/common/types/additional_application_info.py +++ b/google/ads/googleads/v21/common/types/additional_application_info.py @@ -22,7 +22,6 @@ application_instance as gage_application_instance, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.common", marshal="google.ads.googleads.v21", @@ -34,8 +33,12 @@ class AdditionalApplicationInfo(proto.Message): r"""Additional information about the application/tool issuing the - request. This field is only used by [ContentCreatorInsightsService], - [AudienceInsightsService], and [ReachPlanService] APIs. + request. This field is only used by + [ContentCreatorInsightsService][google.ads.googleads.v21.services.ContentCreatorInsightsService], + [AudienceInsightsService][google.ads.googleads.v21.services.AudienceInsightsService], + and + [ReachPlanService][google.ads.googleads.v21.services.ReachPlanService] + APIs. Attributes: application_id (str): diff --git a/google/ads/googleads/v21/common/types/asset_types.py b/google/ads/googleads/v21/common/types/asset_types.py index ce5d3cfdc..14a667056 100644 --- a/google/ads/googleads/v21/common/types/asset_types.py +++ b/google/ads/googleads/v21/common/types/asset_types.py @@ -52,7 +52,6 @@ ) from google.ads.googleads.v21.enums.types import promotion_extension_occasion - __protobuf__ = proto.module( package="google.ads.googleads.v21.common", marshal="google.ads.googleads.v21", @@ -1781,7 +1780,7 @@ class DynamicFlightsAsset(proto.Message): PAR,LON. custom_mapping (str): A custom field which can be multiple key to values mapping - separated by delimiters (",", "|" and ":"), in the forms of + separated by delimiters (",", "\|" and ":"), in the forms of ": , , ... , \| : , ... , \| ... \| : , ... ," for example, wifi: most \| aircraft: 320, 77W \| diff --git a/google/ads/googleads/v21/common/types/audience_insights_attribute.py b/google/ads/googleads/v21/common/types/audience_insights_attribute.py index 4c3df4090..2575d2296 100644 --- a/google/ads/googleads/v21/common/types/audience_insights_attribute.py +++ b/google/ads/googleads/v21/common/types/audience_insights_attribute.py @@ -28,7 +28,6 @@ user_list_type as gage_user_list_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.common", marshal="google.ads.googleads.v21", @@ -206,7 +205,7 @@ class AudienceInsightsAttributeMetadata(proto.Message): class AudienceInsightsAttribute(proto.Message): r"""An audience attribute that can be used to request insights about the audience. Valid inputs for these fields are available from - [AudienceInsightsService.ListAudienceInsightsAttributes][]. + [AudienceInsightsService.ListAudienceInsightsAttributes][google.ads.googleads.v21.services.AudienceInsightsService.ListAudienceInsightsAttributes]. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -612,7 +611,7 @@ class KnowledgeGraphAttributeMetadata(proto.Message): Attributes: entity_capabilities (MutableSequence[google.ads.googleads.v21.enums.types.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities]): The capabilities of the entity used in - [ContentCreatorInsightsService][]. + [ContentCreatorInsightsService][google.ads.googleads.v21.services.ContentCreatorInsightsService]. related_categories (MutableSequence[google.ads.googleads.v21.common.types.AudienceInsightsAttributeMetadata]): A list of CATEGORY attributes related to this entity. diff --git a/google/ads/googleads/v21/common/types/criteria.py b/google/ads/googleads/v21/common/types/criteria.py index 43b75bcc6..2d7081002 100644 --- a/google/ads/googleads/v21/common/types/criteria.py +++ b/google/ads/googleads/v21/common/types/criteria.py @@ -51,7 +51,6 @@ from google.ads.googleads.v21.enums.types import webpage_condition_operand from google.ads.googleads.v21.enums.types import webpage_condition_operator - __protobuf__ = proto.module( package="google.ads.googleads.v21.common", marshal="google.ads.googleads.v21", @@ -1648,19 +1647,37 @@ class LanguageInfo(proto.Message): class IpBlockInfo(proto.Message): - r"""An IpBlock criterion used for IP exclusions. We allow: + r"""An IpBlock criterion used for excluding IP addresses. + + We support excluding individual IP addresses or CIDR blocks. Create + one IpBlockInfo criterion for each individual IP address or CIDR + block you want to exclude. You can exclude up to 500 IP addresses + per campaign. For more details, see `Exclude IP + addresses `__. + + IPv4 examples: + + - Individual address: 192.168.0.1 + + - Individual address as CIDR block: 192.168.0.1/32 + + - CIDR block: 192.168.0.0/24 + + IPv6 examples: + + - Individual address: 2001:db8:a0b:12f0::1 + + - Individual address as CIDR block: 2001:db8:a0b:12f0::1/128 - - IPv4 and IPv6 addresses - - individual addresses (192.168.0.1) - - masks for individual addresses (192.168.0.1/32) - - masks for Class C networks (192.168.0.1/24) + - CIDR block: 2001:db8::/48 .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: ip_address (str): - The IP address of this IP block. + The IP address or the CIDR block to be + excluded. This field is a member of `oneof`_ ``_ip_address``. """ diff --git a/google/ads/googleads/v21/common/types/metrics.py b/google/ads/googleads/v21/common/types/metrics.py index 5392b0ab4..91cc8b8b8 100644 --- a/google/ads/googleads/v21/common/types/metrics.py +++ b/google/ads/googleads/v21/common/types/metrics.py @@ -22,7 +22,6 @@ from google.ads.googleads.v21.enums.types import interaction_event_type from google.ads.googleads.v21.enums.types import quality_score_bucket - __protobuf__ = proto.module( package="google.ads.googleads.v21.common", marshal="google.ads.googleads.v21", @@ -140,18 +139,18 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_value_per_cost``. all_conversions_from_click_to_call (float): The number of times people clicked the "Call" - button to call a store during or after clicking - an ad. This number doesn't include whether or - not calls were connected, or the duration of any - calls. + button to call a business during or after + clicking an ad. This number doesn't include + whether or not calls were connected, or the + duration of any calls. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_click_to_call``. all_conversions_from_directions (float): The number of times people clicked a "Get - directions" button to navigate to a store after - clicking an ad. + directions" button to navigate to a business + after clicking an ad. This metric applies to feed items only. @@ -164,34 +163,36 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_from_interactions_value_per_interaction``. all_conversions_from_menu (float): The number of times people clicked a link to - view a store's menu after clicking an ad. + view a business's menu after clicking an ad. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_menu``. all_conversions_from_order (float): The number of times people placed an order at - a store after clicking an ad. + a business after clicking an ad. + This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_order``. all_conversions_from_other_engagement (float): The number of other conversions (for example, posting a review or saving a location for a - store) that occurred after people clicked an ad. + business) that occurred after people clicked an + ad. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_other_engagement``. all_conversions_from_store_visit (float): Estimated number of times people visited a - store after clicking an ad. + business after clicking an ad. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_store_visit``. all_conversions_from_store_website (float): The number of times that people were taken to - a store's URL after clicking an ad. + a business's URL after clicking an ad. This metric applies to feed items only. @@ -638,8 +639,8 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_gmail_secondary_clicks``. impressions_from_store_reach (int): - The number of times a store's location-based - ad was shown. + The number of times a business's + location-based ad was shown. This metric applies to feed items only. This field is a member of `oneof`_ ``_impressions_from_store_reach``. @@ -1091,10 +1092,10 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_from_location_asset_other_engagement``. all_conversions_from_location_asset_store_visits (float): - Estimated number of visits to the store after - a chargeable ad event (click or impression). - This measure is coming from Asset based - location. + Estimated number of visits to the business + after a chargeable ad event (click or + impression). This measure is coming from Asset + based location. This field is a member of `oneof`_ ``_all_conversions_from_location_asset_store_visits``. all_conversions_from_location_asset_website (float): @@ -1105,7 +1106,7 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_from_location_asset_website``. eligible_impressions_from_location_asset_store_reach (int): - Number of impressions in which the store + Number of impressions in which the business location was shown or the location was used for targeting. This measure is coming from Asset based location. @@ -1143,9 +1144,9 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_view_through_conversions_from_location_asset_other_engagement``. view_through_conversions_from_location_asset_store_visits (float): - Estimated number of visits to the store after - an impression. This measure is coming from Asset - based location. + Estimated number of visits to the business + after an impression. This measure is coming from + Asset based location. This field is a member of `oneof`_ ``_view_through_conversions_from_location_asset_store_visits``. view_through_conversions_from_location_asset_website (float): @@ -1684,8 +1685,8 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_asset_unrated_performance_cost_percentage``. store_visits_last_click_model_attributed_conversions (float): - The amount of store visits attributed by the - last click model. + The amount of business visits attributed by + the last click model. This field is a member of `oneof`_ ``_store_visits_last_click_model_attributed_conversions``. results_conversions_purchase (float): diff --git a/google/ads/googleads/v21/common/types/policy.py b/google/ads/googleads/v21/common/types/policy.py index 94b8d3339..49eb91e19 100644 --- a/google/ads/googleads/v21/common/types/policy.py +++ b/google/ads/googleads/v21/common/types/policy.py @@ -30,7 +30,6 @@ policy_topic_evidence_destination_not_working_dns_error_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.common", marshal="google.ads.googleads.v21", @@ -84,27 +83,32 @@ class PolicyValidationParameter(proto.Message): Attributes: ignorable_policy_topics (MutableSequence[str]): - The list of policy topics that should not - cause a PolicyFindingError to be reported. This - field is currently only compatible with Enhanced - Text Ad. It corresponds to the - PolicyTopicEntry.topic field. - - Resources violating these policies will be - saved, but will not be eligible to serve. They - may begin serving at a later time due to a - change in policies, re-review of the resource, - or a change in advertiser certificates. + The list of policy topics that should not cause a + ``PolicyFindingError`` to be reported. This field is used + for ad policy exemptions. It corresponds to the + ``PolicyTopicEntry.topic`` field. + + If this field is populated, then + ``exempt_policy_violation_keys`` must be empty. + + Resources that violate these policies will be saved, but + will not be eligible to serve. They may begin serving at a + later time due to a change in policies, re-review of the + resource, or a change in advertiser certificates. exempt_policy_violation_keys (MutableSequence[google.ads.googleads.v21.common.types.PolicyViolationKey]): The list of policy violation keys that should not cause a - PolicyViolationError to be reported. Not all policy - violations are exemptable, refer to the is_exemptible field - in the returned PolicyViolationError. - - Resources violating these polices will be saved, but will - not be eligible to serve. They may begin serving at a later - time due to a change in policies, re-review of the resource, - or a change in advertiser certificates. + ``PolicyViolationError`` to be reported. Not all policy + violations are exemptable. Refer to the ``is_exemptible`` + field in the returned ``PolicyViolationError``. This field + is used for keyword policy exemptions. + + If this field is populated, then ``ignorable_policy_topics`` + must be empty. + + Resources that violate these policies will be saved, but + will not be eligible to serve. They may begin serving at a + later time due to a change in policies, re-review of the + resource, or a change in advertiser certificates. """ ignorable_policy_topics: MutableSequence[str] = proto.RepeatedField( diff --git a/google/ads/googleads/v21/common/types/third_party_integration_partners.py b/google/ads/googleads/v21/common/types/third_party_integration_partners.py index 0fbce952f..1ae142f64 100644 --- a/google/ads/googleads/v21/common/types/third_party_integration_partners.py +++ b/google/ads/googleads/v21/common/types/third_party_integration_partners.py @@ -32,7 +32,6 @@ third_party_viewability_integration_partner, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.common", marshal="google.ads.googleads.v21", @@ -54,7 +53,7 @@ class CustomerThirdPartyIntegrationPartners(proto.Message): r"""Container for Customer level third party integration - partners. Next Id = 5 + partners. Attributes: viewability_integration_partners (MutableSequence[google.ads.googleads.v21.common.types.CustomerThirdPartyViewabilityIntegrationPartner]): @@ -103,7 +102,7 @@ class CustomerThirdPartyIntegrationPartners(proto.Message): class CustomerThirdPartyViewabilityIntegrationPartner(proto.Message): r"""Container for third party viewability integration data for - Customer. Next Id = 3 + Customer. Attributes: viewability_integration_partner (google.ads.googleads.v21.enums.types.ThirdPartyViewabilityIntegrationPartnerEnum.ThirdPartyViewabilityIntegrationPartner): @@ -129,7 +128,7 @@ class CustomerThirdPartyViewabilityIntegrationPartner(proto.Message): class CustomerThirdPartyBrandSafetyIntegrationPartner(proto.Message): r"""Container for third party brand safety integration data for - Customer. Next Id = 2 + Customer. Attributes: brand_safety_integration_partner (google.ads.googleads.v21.enums.types.ThirdPartyBrandSafetyIntegrationPartnerEnum.ThirdPartyBrandSafetyIntegrationPartner): @@ -148,7 +147,7 @@ class CustomerThirdPartyBrandSafetyIntegrationPartner(proto.Message): class CustomerThirdPartyBrandLiftIntegrationPartner(proto.Message): r"""Container for third party Brand Lift integration data for - Customer. Next Id = 3 + Customer. Attributes: brand_lift_integration_partner (google.ads.googleads.v21.enums.types.ThirdPartyBrandLiftIntegrationPartnerEnum.ThirdPartyBrandLiftIntegrationPartner): @@ -174,7 +173,7 @@ class CustomerThirdPartyBrandLiftIntegrationPartner(proto.Message): class CustomerThirdPartyReachIntegrationPartner(proto.Message): r"""Container for third party reach integration data for - Customer. Next Id = 3 + Customer. Attributes: reach_integration_partner (google.ads.googleads.v21.enums.types.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner): @@ -200,7 +199,7 @@ class CustomerThirdPartyReachIntegrationPartner(proto.Message): class CampaignThirdPartyIntegrationPartners(proto.Message): r"""Container for Campaign level third party integration - partners. Next Id = 5 + partners. Attributes: viewability_integration_partners (MutableSequence[google.ads.googleads.v21.common.types.CampaignThirdPartyViewabilityIntegrationPartner]): @@ -249,7 +248,7 @@ class CampaignThirdPartyIntegrationPartners(proto.Message): class CampaignThirdPartyViewabilityIntegrationPartner(proto.Message): r"""Container for third party viewability integration data for - Campaign. Next Id = 4 + Campaign. Attributes: viewability_integration_partner (google.ads.googleads.v21.enums.types.ThirdPartyViewabilityIntegrationPartnerEnum.ThirdPartyViewabilityIntegrationPartner): @@ -287,7 +286,7 @@ class CampaignThirdPartyViewabilityIntegrationPartner(proto.Message): class CampaignThirdPartyBrandSafetyIntegrationPartner(proto.Message): r"""Container for third party brand safety integration data for - Campaign. Next Id = 3 + Campaign. Attributes: brand_safety_integration_partner (google.ads.googleads.v21.enums.types.ThirdPartyBrandSafetyIntegrationPartnerEnum.ThirdPartyBrandSafetyIntegrationPartner): @@ -318,7 +317,7 @@ class CampaignThirdPartyBrandSafetyIntegrationPartner(proto.Message): class CampaignThirdPartyBrandLiftIntegrationPartner(proto.Message): r"""Container for third party Brand Lift integration data for - Campaign. Next Id = 4 + Campaign. Attributes: brand_lift_integration_partner (google.ads.googleads.v21.enums.types.ThirdPartyBrandLiftIntegrationPartnerEnum.ThirdPartyBrandLiftIntegrationPartner): @@ -356,7 +355,7 @@ class CampaignThirdPartyBrandLiftIntegrationPartner(proto.Message): class CampaignThirdPartyReachIntegrationPartner(proto.Message): r"""Container for third party reach integration data for - Campaign. Next Id = 4 + Campaign. Attributes: reach_integration_partner (google.ads.googleads.v21.enums.types.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner): @@ -394,7 +393,7 @@ class CampaignThirdPartyReachIntegrationPartner(proto.Message): class ThirdPartyIntegrationPartnerData(proto.Message): r"""Contains third party measurement partner related data for - video campaigns. Next Id = 3 + video campaigns. Attributes: client_id (str): diff --git a/google/ads/googleads/v21/common/types/user_lists.py b/google/ads/googleads/v21/common/types/user_lists.py index 14dbc98f3..9cdbfd1aa 100644 --- a/google/ads/googleads/v21/common/types/user_lists.py +++ b/google/ads/googleads/v21/common/types/user_lists.py @@ -38,7 +38,6 @@ user_list_string_rule_item_operator, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.common", marshal="google.ads.googleads.v21", @@ -243,9 +242,9 @@ class UserListRuleItemInfo(proto.Message): letters or underscore or UTF8 code that is greater than 127 and consist of US-ascii letters or digits or underscore or UTF8 code that is greater than 127. For websites, there are - two built-in variable URL (name = 'url__') and referrer URL - (name = 'ref_url__'). This field must be populated when - creating a new rule item. + two built-in variable URL (name = 'url\_\_') and referrer + URL (name = 'ref_url\_\_'). This field must be populated + when creating a new rule item. This field is a member of `oneof`_ ``_name``. number_rule_item (google.ads.googleads.v21.common.types.UserListNumberRuleItemInfo): diff --git a/google/ads/googleads/v21/enums/__init__.py b/google/ads/googleads/v21/enums/__init__.py index c15cc4e39..251940be9 100644 --- a/google/ads/googleads/v21/enums/__init__.py +++ b/google/ads/googleads/v21/enums/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v21 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.access_invitation_status import AccessInvitationStatusEnum from .types.access_reason import AccessReasonEnum @@ -571,6 +581,100 @@ from .types.webpage_condition_operand import WebpageConditionOperandEnum from .types.webpage_condition_operator import WebpageConditionOperatorEnum +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v21") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v21") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v21" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "AccessInvitationStatusEnum", "AccessReasonEnum", diff --git a/google/ads/googleads/v21/enums/types/ad_type.py b/google/ads/googleads/v21/enums/types/ad_type.py index 51d5e0f65..2382f835c 100644 --- a/google/ads/googleads/v21/enums/types/ad_type.py +++ b/google/ads/googleads/v21/enums/types/ad_type.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.enums", marshal="google.ads.googleads.v21", @@ -74,7 +73,7 @@ class AdType(proto.Enum): product type. DYNAMIC_HTML5_AD (22): The ad is a display upload ad with one of the - DYNAMIC_HTML5_\* product types. + DYNAMIC_HTML5\_\* product types. APP_ENGAGEMENT_AD (23): The ad is an app engagement ad. SHOPPING_COMPARISON_LISTING_AD (24): diff --git a/google/ads/googleads/v21/enums/types/asset_automation_type.py b/google/ads/googleads/v21/enums/types/asset_automation_type.py index 56ec73e7f..67783383e 100644 --- a/google/ads/googleads/v21/enums/types/asset_automation_type.py +++ b/google/ads/googleads/v21/enums/types/asset_automation_type.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.enums", marshal="google.ads.googleads.v21", @@ -75,8 +74,9 @@ class AssetAutomationType(proto.Enum): automatically creating dynamic landing pages from the final URL and generating text assets from the content of those landing pages. This - setting only applies to Search campaigns, and - advertisers are opted-out by default. + setting is turned OFF by default for Search + campaigns, but it is turned ON by default for + Performance Max campaigns. """ UNSPECIFIED = 0 diff --git a/google/ads/googleads/v21/enums/types/bidding_strategy_system_status.py b/google/ads/googleads/v21/enums/types/bidding_strategy_system_status.py index d82eb3836..79a883907 100644 --- a/google/ads/googleads/v21/enums/types/bidding_strategy_system_status.py +++ b/google/ads/googleads/v21/enums/types/bidding_strategy_system_status.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.enums", marshal="google.ads.googleads.v21", @@ -117,13 +116,13 @@ class BiddingStrategySystemStatus(proto.Enum): This bid strategy currently does not support status reporting. MULTIPLE_LEARNING (23): - There were multiple LEARNING_\* system statuses for this bid - strategy during the time in question. + There were multiple LEARNING\_\* system statuses for this + bid strategy during the time in question. MULTIPLE_LIMITED (24): - There were multiple LIMITED_\* system statuses for this bid + There were multiple LIMITED\_\* system statuses for this bid strategy during the time in question. MULTIPLE_MISCONFIGURED (25): - There were multiple MISCONFIGURED_\* system statuses for + There were multiple MISCONFIGURED\_\* system statuses for this bid strategy during the time in question. MULTIPLE (26): There were multiple system statuses for this diff --git a/google/ads/googleads/v21/enums/types/insights_knowledge_graph_entity_capabilities.py b/google/ads/googleads/v21/enums/types/insights_knowledge_graph_entity_capabilities.py index 2ac4e6709..85e42b947 100644 --- a/google/ads/googleads/v21/enums/types/insights_knowledge_graph_entity_capabilities.py +++ b/google/ads/googleads/v21/enums/types/insights_knowledge_graph_entity_capabilities.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.enums", marshal="google.ads.googleads.v21", @@ -44,10 +43,10 @@ class InsightsKnowledgeGraphEntityCapabilities(proto.Enum): The value is unknown in this version. CONTENT_TRENDING_INSIGHTS (2): An entity that is supported to use as a trending topic in - [ContentCreatorInsightsService.GenerateTrendingInsights]. + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v21.services.ContentCreatorInsightsService.GenerateTrendingInsights]. CREATOR_ATTRIBUTE (3): An entity that is supported to use as a creator attribute in - [ContentCreatorInsightsService.GenerateCreatorInsights]. + [ContentCreatorInsightsService.GenerateCreatorInsights][google.ads.googleads.v21.services.ContentCreatorInsightsService.GenerateCreatorInsights]. """ UNSPECIFIED = 0 diff --git a/google/ads/googleads/v21/enums/types/offline_user_data_job_status.py b/google/ads/googleads/v21/enums/types/offline_user_data_job_status.py index e01114f30..baa19e8d0 100644 --- a/google/ads/googleads/v21/enums/types/offline_user_data_job_status.py +++ b/google/ads/googleads/v21/enums/types/offline_user_data_job_status.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.enums", marshal="google.ads.googleads.v21", @@ -51,9 +50,15 @@ class OfflineUserDataJobStatus(proto.Enum): being processed. SUCCESS (4): Uploaded data has been successfully - processed. + processed. The job might have no operations, + which can happen if the job was run without any + operations added, or if all operations failed + validation individually when attempting to add + them to the job. FAILED (5): Uploaded data has failed to be processed. + Some operations may have been successfully + processed. """ UNSPECIFIED = 0 diff --git a/google/ads/googleads/v21/enums/types/served_asset_field_type.py b/google/ads/googleads/v21/enums/types/served_asset_field_type.py index 4ffcd8a7f..e42c80b0c 100644 --- a/google/ads/googleads/v21/enums/types/served_asset_field_type.py +++ b/google/ads/googleads/v21/enums/types/served_asset_field_type.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.enums", marshal="google.ads.googleads.v21", @@ -64,7 +63,7 @@ class ServedAssetFieldType(proto.Enum): DESCRIPTION (10): The asset was used in a description. Use this only if there is only one description in the ad. Otherwise, use the - DESCRIPTION_1 or DESCRIPTION_@ enums + DESCRIPTION_1 or DESCRIPTION\_@ enums DESCRIPTION_IN_PORTRAIT (11): The asset was used as description in portrait image. diff --git a/google/ads/googleads/v21/errors/__init__.py b/google/ads/googleads/v21/errors/__init__.py index 5f9691782..3f6a3ead4 100644 --- a/google/ads/googleads/v21/errors/__init__.py +++ b/google/ads/googleads/v21/errors/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v21 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.access_invitation_error import AccessInvitationErrorEnum from .types.account_budget_proposal_error import AccountBudgetProposalErrorEnum @@ -229,6 +239,100 @@ YoutubeVideoRegistrationErrorEnum, ) +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v21") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v21") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v21" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "AccessInvitationErrorEnum", "AccountBudgetProposalErrorEnum", diff --git a/google/ads/googleads/v21/errors/types/date_error.py b/google/ads/googleads/v21/errors/types/date_error.py index 881669880..65dbe112d 100644 --- a/google/ads/googleads/v21/errors/types/date_error.py +++ b/google/ads/googleads/v21/errors/types/date_error.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.errors", marshal="google.ads.googleads.v21", @@ -57,7 +56,7 @@ class DateError(proto.Enum): yyyy-mm-dd hh:mm:ss. INVALID_STRING_DATE_TIME_SECONDS_WITH_OFFSET (12): The string date time's format should be yyyy-mm-dd - hh:mm:ss+|-hh:mm. + hh:mm:ss+\|-hh:mm. EARLIER_THAN_MINIMUM_DATE (7): Date is before allowed minimum. LATER_THAN_MAXIMUM_DATE (8): diff --git a/google/ads/googleads/v21/errors/types/errors.py b/google/ads/googleads/v21/errors/types/errors.py index 6dc4085a9..19df6ab0a 100644 --- a/google/ads/googleads/v21/errors/types/errors.py +++ b/google/ads/googleads/v21/errors/types/errors.py @@ -488,8 +488,7 @@ from google.ads.googleads.v21.errors.types import ( youtube_video_registration_error as gage_youtube_video_registration_error, ) -from google.protobuf import duration_pb2 # type: ignore - +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.errors", @@ -2801,7 +2800,7 @@ class BudgetPerDayMinimumErrorDetails(proto.Message): The minimum budget required by the campaign per day, in micros of the advertiser currency. Applies to both daily and custom budgets. - minimum_bugdet_amount_micros (int): + minimum_budget_amount_micros (int): The minimum value for the budget's amount field required by the campaign, in micros of the advertiser currency. Only set if this error is @@ -2830,7 +2829,7 @@ class BudgetPerDayMinimumErrorDetails(proto.Message): proto.INT64, number=2, ) - minimum_bugdet_amount_micros: int = proto.Field( + minimum_budget_amount_micros: int = proto.Field( proto.INT64, number=3, ) diff --git a/google/ads/googleads/v21/errors/types/image_error.py b/google/ads/googleads/v21/errors/types/image_error.py index 5caa09399..11e2b6a1f 100644 --- a/google/ads/googleads/v21/errors/types/image_error.py +++ b/google/ads/googleads/v21/errors/types/image_error.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.errors", marshal="google.ads.googleads.v21", @@ -86,9 +85,9 @@ class ImageError(proto.Enum): FLASH_HAS_RANDOM_NUM (23): Flash cannot have a random number. FLASH_SELF_TARGETS (24): - Ad click target cannot be '_self'. + Ad click target cannot be '\_self'. FLASH_BAD_GETURL_TARGET (25): - GetUrl method should only use '_blank'. + GetUrl method should only use '\_blank'. FLASH_VERSION_NOT_SUPPORTED (26): Flash version is not supported. FLASH_WITHOUT_HARD_CODED_CLICK_URL (27): diff --git a/google/ads/googleads/v21/errors/types/mutate_error.py b/google/ads/googleads/v21/errors/types/mutate_error.py index 47baeb3f5..95b7a008e 100644 --- a/google/ads/googleads/v21/errors/types/mutate_error.py +++ b/google/ads/googleads/v21/errors/types/mutate_error.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.errors", marshal="google.ads.googleads.v21", @@ -62,6 +61,10 @@ class MutateError(proto.Enum): This operation cannot be used with "partial_failure". RESOURCE_READ_ONLY (13): Attempt to write to read-only fields. + EU_POLITICAL_ADVERTISING_DECLARATION_REQUIRED (17): + Mutates are generally not allowed if the + customer contains non-exempt campaigns without + the EU political advertising declaration. """ UNSPECIFIED = 0 @@ -75,6 +78,7 @@ class MutateError(proto.Enum): RESOURCE_DOES_NOT_SUPPORT_VALIDATE_ONLY = 12 OPERATION_DOES_NOT_SUPPORT_PARTIAL_FAILURE = 16 RESOURCE_READ_ONLY = 13 + EU_POLITICAL_ADVERTISING_DECLARATION_REQUIRED = 17 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v21/resources/__init__.py b/google/ads/googleads/v21/resources/__init__.py index e7fba3bdf..fe31400ef 100644 --- a/google/ads/googleads/v21/resources/__init__.py +++ b/google/ads/googleads/v21/resources/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v21 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.accessible_bidding_strategy import AccessibleBiddingStrategy from .types.account_budget import AccountBudget @@ -308,6 +318,100 @@ from .types.video import Video from .types.webpage_view import WebpageView +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v21") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v21") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v21" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "AccessibleBiddingStrategy", "AccountBudget", diff --git a/google/ads/googleads/v21/resources/types/account_budget.py b/google/ads/googleads/v21/resources/types/account_budget.py index 40127a032..7408197cc 100644 --- a/google/ads/googleads/v21/resources/types/account_budget.py +++ b/google/ads/googleads/v21/resources/types/account_budget.py @@ -25,7 +25,6 @@ ) from google.ads.googleads.v21.enums.types import time_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -41,11 +40,11 @@ class AccountBudget(proto.Message): and proposed changes that are pending approval. The proposed changes that are pending approval, if any, are found in 'pending_proposal'. Effective details about the budget are found in fields prefixed - 'approved_', 'adjusted_' and those without a prefix. Since some + 'approved\_', 'adjusted\_' and those without a prefix. Since some effective details may differ from what the user had originally requested (for example, spending limit), these differences are - juxtaposed through 'proposed_', 'approved_', and possibly - 'adjusted_' fields. + juxtaposed through 'proposed\_', 'approved\_', and possibly + 'adjusted\_' fields. This resource is mutated using AccountBudgetProposal and cannot be mutated directly. A budget may have at most one pending proposal at diff --git a/google/ads/googleads/v21/resources/types/ad_group.py b/google/ads/googleads/v21/resources/types/ad_group.py index 57c3bd812..8f3641470 100644 --- a/google/ads/googleads/v21/resources/types/ad_group.py +++ b/google/ads/googleads/v21/resources/types/ad_group.py @@ -35,7 +35,6 @@ from google.ads.googleads.v21.enums.types import demand_gen_channel_strategy from google.ads.googleads.v21.enums.types import targeting_dimension - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -109,7 +108,12 @@ class AdGroup(proto.Message): This field is a member of `oneof`_ ``_campaign``. cpc_bid_micros (int): - The maximum CPC (cost-per-click) bid. + The maximum CPC (cost-per-click) bid. This + field is used when the ad group's effective + bidding strategy is Manual CPC. This field is + not applicable and will be ignored if the ad + group's campaign is using a portfolio bidding + strategy. This field is a member of `oneof`_ ``_cpc_bid_micros``. effective_cpc_bid_micros (int): @@ -145,12 +149,24 @@ class AdGroup(proto.Message): This field is a member of `oneof`_ ``_target_cpm_micros``. target_roas (float): - The target ROAS (return-on-ad-spend) override. If the ad - group's campaign bidding strategy is TargetRoas or - MaximizeConversionValue (with its target_roas field set), - then this field overrides the target ROAS specified in the - campaign's bidding strategy. Otherwise, this value is - ignored. + The target ROAS (return-on-ad-spend) for this ad group. + + This field lets you override the target ROAS specified in + the campaign's bidding strategy, but only if the campaign is + using a standard (not portfolio) ``TargetRoas`` strategy or + a standard ``MaximizeConversionValue`` strategy with its + ``target_roas`` field set. + + If the campaign is using a portfolio bidding strategy, this + field cannot be set and attempting to do so will result in + an error. + + For any other bidding strategies, this value is ignored. + + To see the actual target ROAS being used by the ad group, + considering potential overrides, query the + ``effective_target_roas`` and + ``effective_target_roas_source`` fields. This field is a member of `oneof`_ ``_target_roas``. percent_cpc_bid_micros (int): @@ -182,7 +198,7 @@ class AdGroup(proto.Message): optimized_targeting_enabled is false, this field is ignored. Default is false. display_custom_bid_dimension (google.ads.googleads.v21.enums.types.TargetingDimensionEnum.TargetingDimension): - Allows advertisers to specify a targeting + Lets advertisers specify a targeting dimension on which to place absolute bids. This is only applicable for campaigns that target only the display network and not search. diff --git a/google/ads/googleads/v21/resources/types/ad_group_ad_asset_view.py b/google/ads/googleads/v21/resources/types/ad_group_ad_asset_view.py index 0eb3eb94d..3e31352dd 100644 --- a/google/ads/googleads/v21/resources/types/ad_group_ad_asset_view.py +++ b/google/ads/googleads/v21/resources/types/ad_group_ad_asset_view.py @@ -27,7 +27,6 @@ from google.ads.googleads.v21.enums.types import policy_review_status from google.ads.googleads.v21.enums.types import served_asset_field_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -39,9 +38,17 @@ class AdGroupAdAssetView(proto.Message): - r"""A link between an AdGroupAd and an Asset. AdGroupAdAssetView - supports AppAds, Demand Gen campaigns, and Responsive Search - Ads. + r"""Represents a link between an AdGroupAd and an Asset. This view + provides insights into the performance of assets within specific + ads. + + AdGroupAdAssetView supports the following ad types: + + - App Ads + - Demand Gen campaigns + - Responsive Search Ads + + It does not support Responsive Display Ads. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v21/resources/types/ad_group_bid_modifier.py b/google/ads/googleads/v21/resources/types/ad_group_bid_modifier.py index c14cb202c..c7ae925d1 100644 --- a/google/ads/googleads/v21/resources/types/ad_group_bid_modifier.py +++ b/google/ads/googleads/v21/resources/types/ad_group_bid_modifier.py @@ -23,7 +23,6 @@ bid_modifier_source as gage_bid_modifier_source, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -63,9 +62,7 @@ class AdGroupBidModifier(proto.Message): bid_modifier (float): The modifier for the bid when the criterion matches. The modifier must be in the range: 0.1 - - 10.0. The range is 1.0 - 6.0 for - PreferredContent. Use 0 to opt out of a Device - type. + - 10.0. Use 0 to opt out of a Device type. This field is a member of `oneof`_ ``_bid_modifier``. base_ad_group (str): diff --git a/google/ads/googleads/v21/resources/types/ad_group_simulation.py b/google/ads/googleads/v21/resources/types/ad_group_simulation.py index a1307cf00..a28941c84 100644 --- a/google/ads/googleads/v21/resources/types/ad_group_simulation.py +++ b/google/ads/googleads/v21/resources/types/ad_group_simulation.py @@ -22,7 +22,6 @@ from google.ads.googleads.v21.enums.types import simulation_modification_method from google.ads.googleads.v21.enums.types import simulation_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -38,11 +37,17 @@ class AdGroupSimulation(proto.Message): detailed below respectively. 1. SEARCH - CPC_BID - DEFAULT + 2. SEARCH - CPC_BID - UNIFORM + 3. SEARCH - TARGET_CPA - UNIFORM + 4. SEARCH - TARGET_ROAS - UNIFORM + 5. DISPLAY - CPC_BID - DEFAULT + 6. DISPLAY - CPC_BID - UNIFORM + 7. DISPLAY - TARGET_CPA - UNIFORM This message has `oneof`_ fields (mutually exclusive fields). diff --git a/google/ads/googleads/v21/resources/types/asset_set.py b/google/ads/googleads/v21/resources/types/asset_set.py index e1f95e048..8f6c69e16 100644 --- a/google/ads/googleads/v21/resources/types/asset_set.py +++ b/google/ads/googleads/v21/resources/types/asset_set.py @@ -22,7 +22,6 @@ from google.ads.googleads.v21.enums.types import asset_set_status from google.ads.googleads.v21.enums.types import asset_set_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -65,13 +64,13 @@ class AssetSet(proto.Message): Merchant ID and Feed Label from Google Merchant Center. location_group_parent_asset_set_id (int): - Immutable. Parent asset set id for the asset + Immutable. Parent asset set ID for the asset set where the elements of this asset set come from. For example: the sync level location - AssetSet id where the the elements in - LocationGroup AssetSet come from. This field is - required and only applicable for Location Group - typed AssetSet. + AssetSet id where the elements in LocationGroup + AssetSet come from. This field is required and + only applicable for Location Group typed + AssetSet. hotel_property_data (google.ads.googleads.v21.resources.types.AssetSet.HotelPropertyData): Output only. For Performance Max for travel goals campaigns with a Hotel Center account diff --git a/google/ads/googleads/v21/resources/types/campaign.py b/google/ads/googleads/v21/resources/types/campaign.py index 967463601..dac8b3e82 100644 --- a/google/ads/googleads/v21/resources/types/campaign.py +++ b/google/ads/googleads/v21/resources/types/campaign.py @@ -102,7 +102,6 @@ video_ad_sequence_minimum_duration, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -439,6 +438,15 @@ class Campaign(proto.Message): The advertiser should self-declare whether this campaign contains political advertising content targeted towards the European Union. + missing_eu_political_advertising_declaration (bool): + Output only. Indicates whether this campaign is missing a + declaration about whether it contains political advertising + targeted towards the EU and is ineligible for any + exemptions. If this field is true, use the + contains_eu_political_advertising field to add the required + declaration. + + This field is read-only. bidding_strategy (str): The resource name of the portfolio bidding strategy used by the campaign. @@ -707,11 +715,15 @@ class ShoppingSetting(proto.Message): This field is a member of `oneof`_ ``_merchant_id``. feed_label (str): - Feed label of products to include in the campaign. Only one - of feed_label or sales_country can be set. If used instead - of sales_country, the feed_label field accepts country codes - in the same format for example: 'XX'. Otherwise can be any - string used for feed label in Google Merchant Center. + Feed label of products to include in the campaign. Valid + feed labels may contain a maximum of 20 characters including + uppercase letters, numbers, hyphens, and underscores. If you + previously used the deprecated ``sales_country`` in the + two-letter country code (``XX``) format, the ``feed_label`` + field should be used instead. For more information see the + `feed + label `__ + support article. campaign_priority (int): Priority of the campaign. Campaigns with numerically higher priorities take precedence @@ -736,8 +748,8 @@ class ShoppingSetting(proto.Message): advertising partners cooperating within the campaign. This feature is currently available only for accounts having an advertising partner - link. - This feature is currently supported only for + link. Once set, the field is immutable. This + feature is currently supported only for Performance Max, Shopping, Search and Demand Gen campaign types. disable_product_feed (bool): @@ -1424,7 +1436,7 @@ class AiMaxSetting(proto.Message): Attributes: enable_ai_max (bool): - Controls whether or not AI Max features are serve for this + Controls whether or not AI Max features are served for this campaign. Individual AI Max features are enabled or disabled by their @@ -1823,6 +1835,10 @@ class AiMaxBundlingRequired(proto.Enum): number=102, enum=eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus, ) + missing_eu_political_advertising_declaration: bool = proto.Field( + proto.BOOL, + number=108, + ) bidding_strategy: str = proto.Field( proto.STRING, number=67, diff --git a/google/ads/googleads/v21/resources/types/campaign_budget.py b/google/ads/googleads/v21/resources/types/campaign_budget.py index 9e35b248e..feba968fe 100644 --- a/google/ads/googleads/v21/resources/types/campaign_budget.py +++ b/google/ads/googleads/v21/resources/types/campaign_budget.py @@ -23,7 +23,6 @@ from google.ads.googleads.v21.enums.types import budget_status from google.ads.googleads.v21.enums.types import budget_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -70,18 +69,32 @@ class CampaignBudget(proto.Message): This field is a member of `oneof`_ ``_name``. amount_micros (int): - The amount of the budget, in the local - currency for the account. Amount is specified in - micros, where one million is equivalent to one - currency unit. Monthly spend is capped at 30.4 - times this amount. + The average daily amount to be spent by the campaign. This + field is used when the CampaignBudget ``period`` is set to + ``DAILY``, which is the default. + + Amount is specified in micros in the account's local + currency. One million micros is equivalent to one currency + unit. The effective monthly spend is capped at 30.4 times + this daily amount. + + This field is mutually exclusive with 'total_amount_micros'. + Only one of 'amount_micros' or 'total_amount_micros' should + be set. This field is a member of `oneof`_ ``_amount_micros``. total_amount_micros (int): - The lifetime amount of the budget, in the - local currency for the account. Amount is - specified in micros, where one million is - equivalent to one currency unit. + The total amount to be spent by the campaign over its entire + duration. This field is used *only* when the CampaignBudget + ``period`` is set to ``CUSTOM_PERIOD``. It represents the + budget cap for the campaign's lifetime, rather than a daily + limit. The amount is specified in micros in the account's + local currency. One million micros is equivalent to one + currency unit. + + This field is mutually exclusive with 'amount_micros'. Only + one of 'total_amount_micros' or 'amount_micros' should be + set. This field is a member of `oneof`_ ``_total_amount_micros``. status (google.ads.googleads.v21.enums.types.BudgetStatusEnum.BudgetStatus): diff --git a/google/ads/googleads/v21/resources/types/campaign_criterion.py b/google/ads/googleads/v21/resources/types/campaign_criterion.py index ced4e0ab4..0ae4d83d2 100644 --- a/google/ads/googleads/v21/resources/types/campaign_criterion.py +++ b/google/ads/googleads/v21/resources/types/campaign_criterion.py @@ -22,7 +22,6 @@ from google.ads.googleads.v21.enums.types import campaign_criterion_status from google.ads.googleads.v21.enums.types import criterion_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -154,6 +153,9 @@ class CampaignCriterion(proto.Message): ip_block (google.ads.googleads.v21.common.types.IpBlockInfo): Immutable. IpBlock. + You can exclude up to 500 IP addresses per + campaign. + This field is a member of `oneof`_ ``criterion``. content_label (google.ads.googleads.v21.common.types.ContentLabelInfo): Immutable. ContentLabel. diff --git a/google/ads/googleads/v21/resources/types/campaign_search_term_view.py b/google/ads/googleads/v21/resources/types/campaign_search_term_view.py index 094ea4c76..3001a63ad 100644 --- a/google/ads/googleads/v21/resources/types/campaign_search_term_view.py +++ b/google/ads/googleads/v21/resources/types/campaign_search_term_view.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -31,7 +30,8 @@ class CampaignSearchTermView(proto.Message): r"""This report provides granular performance data, including cost metrics, for each individual search term that triggered - your ads. + your ads. If keyword-related segments are used, Performance Max + data will be excluded from the results. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v21/resources/types/campaign_simulation.py b/google/ads/googleads/v21/resources/types/campaign_simulation.py index c9533c5d2..03b30480a 100644 --- a/google/ads/googleads/v21/resources/types/campaign_simulation.py +++ b/google/ads/googleads/v21/resources/types/campaign_simulation.py @@ -22,7 +22,6 @@ from google.ads.googleads.v21.enums.types import simulation_modification_method from google.ads.googleads.v21.enums.types import simulation_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -37,22 +36,22 @@ class CampaignSimulation(proto.Message): type, simulation type and simulation modification method is detailed below respectively. - - SEARCH - CPC_BID - UNIFORM - - SEARCH - CPC_BID - SCALING - - SEARCH - TARGET_CPA - UNIFORM - - SEARCH - TARGET_CPA - SCALING - - SEARCH - TARGET_ROAS - UNIFORM - - SEARCH - TARGET_IMPRESSION_SHARE - UNIFORM - - SEARCH - BUDGET - UNIFORM - - SHOPPING - BUDGET - UNIFORM - - SHOPPING - TARGET_ROAS - UNIFORM - - MULTI_CHANNEL - TARGET_CPA - UNIFORM - - MULTI_CHANNEL - TARGET_ROAS - UNIFORM - - DEMAND_GEN - TARGET_CPA - DEFAULT - - DISPLAY - TARGET_CPA - UNIFORM - - PERFORMANCE_MAX - TARGET_CPA - UNIFORM - - PERFORMANCE_MAX - TARGET_ROAS - UNIFORM - - PERFORMANCE_MAX - BUDGET - UNIFORM + - SEARCH - CPC_BID - UNIFORM + - SEARCH - CPC_BID - SCALING + - SEARCH - TARGET_CPA - UNIFORM + - SEARCH - TARGET_CPA - SCALING + - SEARCH - TARGET_ROAS - UNIFORM + - SEARCH - TARGET_IMPRESSION_SHARE - UNIFORM + - SEARCH - BUDGET - UNIFORM + - SHOPPING - BUDGET - UNIFORM + - SHOPPING - TARGET_ROAS - UNIFORM + - MULTI_CHANNEL - TARGET_CPA - UNIFORM + - MULTI_CHANNEL - TARGET_ROAS - UNIFORM + - DEMAND_GEN - TARGET_CPA - DEFAULT + - DISPLAY - TARGET_CPA - UNIFORM + - PERFORMANCE_MAX - TARGET_CPA - UNIFORM + - PERFORMANCE_MAX - TARGET_ROAS - UNIFORM + - PERFORMANCE_MAX - BUDGET - UNIFORM This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. diff --git a/google/ads/googleads/v21/resources/types/change_event.py b/google/ads/googleads/v21/resources/types/change_event.py index 35014ac22..e083bc86a 100644 --- a/google/ads/googleads/v21/resources/types/change_event.py +++ b/google/ads/googleads/v21/resources/types/change_event.py @@ -58,8 +58,7 @@ from google.ads.googleads.v21.resources.types import ( customer_asset as gagr_customer_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", diff --git a/google/ads/googleads/v21/resources/types/click_view.py b/google/ads/googleads/v21/resources/types/click_view.py index c55c6af02..a99b6494e 100644 --- a/google/ads/googleads/v21/resources/types/click_view.py +++ b/google/ads/googleads/v21/resources/types/click_view.py @@ -21,7 +21,6 @@ from google.ads.googleads.v21.common.types import click_location from google.ads.googleads.v21.common.types import criteria - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -39,6 +38,9 @@ class ClickView(proto.Message): filter limiting the results to one day and can be requested for dates back to 90 days before the time of the request. + GCLIDs are not available in this report for App Campaigns for + Installs (ACi) and App Campaigns for Pre-registration (ACpre). + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v21/resources/types/conversion_value_rule_set.py b/google/ads/googleads/v21/resources/types/conversion_value_rule_set.py index 8f10cb208..c9936e2a1 100644 --- a/google/ads/googleads/v21/resources/types/conversion_value_rule_set.py +++ b/google/ads/googleads/v21/resources/types/conversion_value_rule_set.py @@ -26,7 +26,6 @@ from google.ads.googleads.v21.enums.types import value_rule_set_attachment_type from google.ads.googleads.v21.enums.types import value_rule_set_dimension - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -37,7 +36,9 @@ class ConversionValueRuleSet(proto.Message): - r"""A conversion value rule set + r"""A conversion value rule set is a collection of conversion value + rules that lets you adjust conversion values based on the dimensions + specified in the ``dimensions`` field. Attributes: resource_name (str): diff --git a/google/ads/googleads/v21/resources/types/customer.py b/google/ads/googleads/v21/resources/types/customer.py index de80f773f..709d2fe0c 100644 --- a/google/ads/googleads/v21/resources/types/customer.py +++ b/google/ads/googleads/v21/resources/types/customer.py @@ -28,11 +28,11 @@ customer_pay_per_conversion_eligibility_failure_reason, ) from google.ads.googleads.v21.enums.types import customer_status +from google.ads.googleads.v21.enums.types import eu_political_advertising_status from google.ads.googleads.v21.enums.types import ( local_services_verification_status, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -192,6 +192,14 @@ class Customer(proto.Message): https://support.google.com/google-ads/answer/7515513. video_customer (google.ads.googleads.v21.resources.types.VideoCustomer): Video specific information about a Customer. + contains_eu_political_advertising (google.ads.googleads.v21.enums.types.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus): + Output only. Returns the advertiser + self-declaration status of whether this customer + contains political advertising content targeted + towards the European Union. You can use the + Google Ads UI to update this account-level + declaration, or use the API to update the + self-declaration status of individual campaigns. """ resource_name: str = proto.Field( @@ -326,6 +334,13 @@ class Customer(proto.Message): number=54, message="VideoCustomer", ) + contains_eu_political_advertising: ( + eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus + ) = proto.Field( + proto.ENUM, + number=55, + enum=eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus, + ) class CallReportingSetting(proto.Message): diff --git a/google/ads/googleads/v21/resources/types/customer_negative_criterion.py b/google/ads/googleads/v21/resources/types/customer_negative_criterion.py index 7e056838d..f20777481 100644 --- a/google/ads/googleads/v21/resources/types/customer_negative_criterion.py +++ b/google/ads/googleads/v21/resources/types/customer_negative_criterion.py @@ -21,7 +21,6 @@ from google.ads.googleads.v21.common.types import criteria from google.ads.googleads.v21.enums.types import criterion_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -83,7 +82,10 @@ class CustomerNegativeCriterion(proto.Message): This field is a member of `oneof`_ ``criterion``. ip_block (google.ads.googleads.v21.common.types.IpBlockInfo): - Immutable. IPBLock + Immutable. IpBlock. + + You can exclude up to 500 IP addresses per + account. This field is a member of `oneof`_ ``criterion``. placement_list (google.ads.googleads.v21.common.types.PlacementListInfo): diff --git a/google/ads/googleads/v21/resources/types/detail_content_suitability_placement_view.py b/google/ads/googleads/v21/resources/types/detail_content_suitability_placement_view.py index c8a8c8c64..b6cad065b 100644 --- a/google/ads/googleads/v21/resources/types/detail_content_suitability_placement_view.py +++ b/google/ads/googleads/v21/resources/types/detail_content_suitability_placement_view.py @@ -22,7 +22,6 @@ placement_type as gage_placement_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -34,7 +33,6 @@ class DetailContentSuitabilityPlacementView(proto.Message): r"""A detail content suitability placement view. - {-- next tag to use: 6 --} Attributes: resource_name (str): diff --git a/google/ads/googleads/v21/resources/types/detail_placement_view.py b/google/ads/googleads/v21/resources/types/detail_placement_view.py index 4189240d6..f1898e237 100644 --- a/google/ads/googleads/v21/resources/types/detail_placement_view.py +++ b/google/ads/googleads/v21/resources/types/detail_placement_view.py @@ -22,7 +22,6 @@ placement_type as gage_placement_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -33,8 +32,14 @@ class DetailPlacementView(proto.Message): - r"""A view with metrics aggregated by ad group and URL or YouTube - video. + r"""A view with metrics aggregated by ad group and URL or YouTube video. + + This view primarily surfaces placement data from the Google Display + Network. While you can select segments like + ``segments.ad_network_type``, this view generally does not include + placement data from other networks, such as the Search Partners + network. To understand performance on Search Partners, consider + other reports and segmentations. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v21/resources/types/display_keyword_view.py b/google/ads/googleads/v21/resources/types/display_keyword_view.py index f465ad36c..6ecf3a321 100644 --- a/google/ads/googleads/v21/resources/types/display_keyword_view.py +++ b/google/ads/googleads/v21/resources/types/display_keyword_view.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -31,6 +30,22 @@ class DisplayKeywordView(proto.Message): r"""A display keyword view. + Provides performance data for keywords used in Display Network + campaigns. This view lets you analyze how your display keywords are + performing across various segments. + + This view is primarily used to track the effectiveness of keyword + targeting within your Display campaigns. To understand which network + the metrics apply to, you can select the + ``segments.ad_network_type`` field in your query. This field will + segment the data by networks such as the Google Display Network, + YouTube, Gmail, and so on. + + You can select fields from this resource along with metrics like + impressions, clicks, and conversions to gauge performance. + Attributed resources like ``ad_group`` and ``campaign`` can also be + selected without segmenting metrics. + Attributes: resource_name (str): Output only. The resource name of the display keyword view. diff --git a/google/ads/googleads/v21/resources/types/group_content_suitability_placement_view.py b/google/ads/googleads/v21/resources/types/group_content_suitability_placement_view.py index 2b523502e..1e3add23e 100644 --- a/google/ads/googleads/v21/resources/types/group_content_suitability_placement_view.py +++ b/google/ads/googleads/v21/resources/types/group_content_suitability_placement_view.py @@ -22,7 +22,6 @@ placement_type as gage_placement_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -34,7 +33,6 @@ class GroupContentSuitabilityPlacementView(proto.Message): r"""A group content suitability placement view. - {-- next tag to use: 6 --} Attributes: resource_name (str): diff --git a/google/ads/googleads/v21/resources/types/lead_form_submission_data.py b/google/ads/googleads/v21/resources/types/lead_form_submission_data.py index 002e792bf..443e812f9 100644 --- a/google/ads/googleads/v21/resources/types/lead_form_submission_data.py +++ b/google/ads/googleads/v21/resources/types/lead_form_submission_data.py @@ -21,7 +21,6 @@ from google.ads.googleads.v21.enums.types import lead_form_field_user_input_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -68,7 +67,7 @@ class LeadFormSubmissionData(proto.Message): the submissed lead form. submission_date_time (str): Output only. The date and time at which the lead form was - submitted. The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for + submitted. The format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". """ diff --git a/google/ads/googleads/v21/resources/types/local_services_lead.py b/google/ads/googleads/v21/resources/types/local_services_lead.py index a11db6e3e..829806737 100644 --- a/google/ads/googleads/v21/resources/types/local_services_lead.py +++ b/google/ads/googleads/v21/resources/types/local_services_lead.py @@ -24,7 +24,6 @@ from google.ads.googleads.v21.enums.types import local_services_lead_status from google.ads.googleads.v21.enums.types import local_services_lead_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -48,7 +47,7 @@ class LocalServicesLead(proto.Message): Attributes: resource_name (str): - Output only. The resource name of the local services lead + Immutable. The resource name of the local services lead data. Local Services Lead resource name have the form ``customers/{customer_id}/localServicesLead/{local_services_lead_id}`` @@ -168,8 +167,12 @@ class ContactDetails(proto.Message): Attributes: phone_number (str): - Output only. Consumer phone number in E164 - format. + Output only. Phone number of the consumer for + the lead. This can be a real phone number or a + tracking number. The phone number is returned in + E164 format. See + https://support.google.com/google-ads/answer/16355235?hl=en + to learn more. Example: +16504519489. email (str): Output only. Consumer email address. consumer_name (str): diff --git a/google/ads/googleads/v21/resources/types/shopping_performance_view.py b/google/ads/googleads/v21/resources/types/shopping_performance_view.py index 7fec9fbe3..d59218550 100644 --- a/google/ads/googleads/v21/resources/types/shopping_performance_view.py +++ b/google/ads/googleads/v21/resources/types/shopping_performance_view.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -30,12 +29,26 @@ class ShoppingPerformanceView(proto.Message): r"""Shopping performance view. - Provides Shopping campaign statistics aggregated at several - product dimension levels. Product dimension values from Merchant - Center such as brand, category, custom attributes, product - condition and product type will reflect the state of each - dimension as of the date and time when the corresponding event - was recorded. + + Provides Shopping campaign and Performance Max campaign statistics + aggregated at several product dimension levels. Product dimension + values from Merchant Center such as brand, category, custom + attributes, product condition, and product type will reflect the + state of each dimension as of the date and time when the + corresponding event was recorded. + + The number of impressions and clicks that + ``shopping_performance_view`` returns stats for may be different + from campaign reports. ``shopping_performance_view`` shows + impressions and clicks on products appearing in ads, while campaign + reports show impressions and clicks on the ads themselves. Depending + on the format, an ad can show from zero to several products, so the + numbers may not match. + + In Google Ads UI, you can query impressions and clicks of products + appearing in ads by selecting a column from "Product attributes" in + the report editor. For example, selecting the "Brand" column is + equivalent to selecting ``segments.product_brand``. Attributes: resource_name (str): diff --git a/google/ads/googleads/v21/resources/types/shopping_product.py b/google/ads/googleads/v21/resources/types/shopping_product.py index 21ab1d4a0..41865b259 100644 --- a/google/ads/googleads/v21/resources/types/shopping_product.py +++ b/google/ads/googleads/v21/resources/types/shopping_product.py @@ -26,7 +26,6 @@ from google.ads.googleads.v21.enums.types import product_issue_severity from google.ads.googleads.v21.enums.types import product_status - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -50,27 +49,31 @@ class ShoppingProduct(proto.Message): Queries to this resource specify a scope: Account: - - Filters on campaigns or ad groups are not specified. - - All products from the linked Google Merchant Center accounts are - returned. - - Metrics and some fields (see the per-field documentation) are - aggregated across all Shopping and Performance Max campaigns that - include a product. Campaign: - - An equality filter on ``campaign`` is specified. Supported - campaign types are Shopping, Performance Max, Demand Gen, Video. - - Only products that are included by the specified campaign are - returned. - - Metrics and some fields (see the per-field documentation) are - restricted to the specified campaign. Ad group: - - An equality filter on ``ad group`` and ``campaign`` is specified. - Supported campaign types are Shopping, Demand Gen, Video. - - Only products that are included by the specified campaign are - returned. - - Metrics and some fields (see the per-field documentation) are - restricted to the specified ad group. Note that segmentation by - date segments is not permitted and will return - UNSUPPORTED_DATE_SEGMENTATION error. On the other hand, filtering - on date segments is allowed. + - Filters on campaigns or ad groups are not specified. + - All products from the linked Google Merchant Center accounts are + returned. + - Metrics and some fields (see the per-field documentation) are + aggregated across all Shopping and Performance Max campaigns that + include a product. Campaign: + - An equality filter on ``campaign`` is specified. Supported + campaign types are Shopping, Performance Max, Demand Gen, Video. + - Only products that are included by the specified campaign are + returned. + - Metrics and some fields (see the per-field documentation) are + restricted to the specified campaign. + - Only the following metrics are supported for Demand Gen and Video + campaigns: impressions, clicks, ctr. Ad group: + - An equality filter on ``ad group`` and ``campaign`` is specified. + Supported campaign types are Shopping, Demand Gen, Video. + - Only products that are included by the specified campaign are + returned. + - Metrics and some fields (see the per-field documentation) are + restricted to the specified ad group. + - Only the following metrics are supported for Demand Gen and Video + campaigns: impressions, clicks, ctr. Note that segmentation by + date segments is not permitted and will return + UNSUPPORTED_DATE_SEGMENTATION error. On the other hand, filtering + on date segments is allowed. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v21/resources/types/user_list.py b/google/ads/googleads/v21/resources/types/user_list.py index d2a6a8820..9490d28ef 100644 --- a/google/ads/googleads/v21/resources/types/user_list.py +++ b/google/ads/googleads/v21/resources/types/user_list.py @@ -28,7 +28,6 @@ from google.ads.googleads.v21.enums.types import user_list_size_range from google.ads.googleads.v21.enums.types import user_list_type - __protobuf__ = proto.module( package="google.ads.googleads.v21.resources", marshal="google.ads.googleads.v21", @@ -39,7 +38,12 @@ class UserList(proto.Message): - r"""A user list. This is a list of users a customer may target. + r"""A user list. This is a list of users a customer may target. The + unique key of a user list consists of the following fields: ``id``. + Note that the ``name`` must also be unique for user lists owned by a + given customer, except in some cases where ``access_reason`` is set + to ``SHARED``. Violating the unique name constraint produces error: + ``UserListError.INVALID_NAME``. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -68,9 +72,9 @@ class UserList(proto.Message): This field is a member of `oneof`_ ``_read_only``. name (str): - Name of this user list. Depending on its access_reason, the - user list name may not be unique (for example, if - access_reason=SHARED) + Name of this user list. Unique per user list, except in some + cases where a user list of the same name has + ``access_reason`` set to ``SHARED``. This field is a member of `oneof`_ ``_name``. description (str): diff --git a/google/ads/googleads/v21/services/services/account_budget_proposal_service/async_client.py b/google/ads/googleads/v21/services/services/account_budget_proposal_service/async_client.py index f81d741db..b4e83f25d 100644 --- a/google/ads/googleads/v21/services/services/account_budget_proposal_service/async_client.py +++ b/google/ads/googleads/v21/services/services/account_budget_proposal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -140,7 +139,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AccountBudgetProposalServiceAsyncClient: The constructed client. """ - return AccountBudgetProposalServiceClient.from_service_account_info.__func__(AccountBudgetProposalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AccountBudgetProposalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AccountBudgetProposalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -156,7 +160,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountBudgetProposalServiceAsyncClient: The constructed client. """ - return AccountBudgetProposalServiceClient.from_service_account_file.__func__(AccountBudgetProposalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AccountBudgetProposalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AccountBudgetProposalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/account_budget_proposal_service/client.py b/google/ads/googleads/v21/services/services/account_budget_proposal_service/client.py index 18ae78cc6..fd7fd528d 100644 --- a/google/ads/googleads/v21/services/services/account_budget_proposal_service/client.py +++ b/google/ads/googleads/v21/services/services/account_budget_proposal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -389,14 +417,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AccountBudgetProposalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -404,7 +428,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -436,22 +460,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AccountBudgetProposalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/base.py b/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/base.py index cfba0476e..6d4121835 100644 --- a/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/grpc.py b/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/grpc.py index 2f49824d0..967c6ba44 100644 --- a/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/grpc.py @@ -175,9 +175,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -318,9 +319,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/grpc_asyncio.py index 7ff424933..49765acfa 100644 --- a/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/account_budget_proposal_service/transports/grpc_asyncio.py @@ -165,8 +165,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -221,9 +222,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/account_link_service/async_client.py b/google/ads/googleads/v21/services/services/account_link_service/async_client.py index 16ceef46f..cc08ee16e 100644 --- a/google/ads/googleads/v21/services/services/account_link_service/async_client.py +++ b/google/ads/googleads/v21/services/services/account_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,7 +36,7 @@ account_link as gagr_account_link, ) from google.ads.googleads.v21.services.types import account_link_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AccountLinkServiceTransport, DEFAULT_CLIENT_INFO from .client import AccountLinkServiceClient @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AccountLinkServiceAsyncClient: The constructed client. """ - return AccountLinkServiceClient.from_service_account_info.__func__(AccountLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AccountLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AccountLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountLinkServiceAsyncClient: The constructed client. """ - return AccountLinkServiceClient.from_service_account_file.__func__(AccountLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AccountLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AccountLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/account_link_service/client.py b/google/ads/googleads/v21/services/services/account_link_service/client.py index 42d23e371..4b4f5bbf9 100644 --- a/google/ads/googleads/v21/services/services/account_link_service/client.py +++ b/google/ads/googleads/v21/services/services/account_link_service/client.py @@ -53,7 +53,7 @@ account_link as gagr_account_link, ) from google.ads.googleads.v21.services.types import account_link_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AccountLinkServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AccountLinkServiceGrpcTransport from .transports.grpc_asyncio import AccountLinkServiceGrpcAsyncIOTransport @@ -139,6 +139,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -330,14 +358,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AccountLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -345,7 +367,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -377,22 +399,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AccountLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/account_link_service/transports/base.py b/google/ads/googleads/v21/services/services/account_link_service/transports/base.py index e56268542..ad500fa55 100644 --- a/google/ads/googleads/v21/services/services/account_link_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/account_link_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/account_link_service/transports/grpc.py b/google/ads/googleads/v21/services/services/account_link_service/transports/grpc.py index 1c697b246..ea555060f 100644 --- a/google/ads/googleads/v21/services/services/account_link_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/account_link_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/account_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/account_link_service/transports/grpc_asyncio.py index 95e494047..855d97ebc 100644 --- a/google/ads/googleads/v21/services/services/account_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/account_link_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/async_client.py index a34f62e58..ebce79c4c 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_group_ad_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupAdLabelServiceClient @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAdLabelServiceAsyncClient: The constructed client. """ - return AdGroupAdLabelServiceClient.from_service_account_info.__func__(AdGroupAdLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAdLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupAdLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAdLabelServiceAsyncClient: The constructed client. """ - return AdGroupAdLabelServiceClient.from_service_account_file.__func__(AdGroupAdLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAdLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAdLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/client.py b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/client.py index ad557351c..af5e784a9 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_group_ad_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupAdLabelServiceGrpcTransport from .transports.grpc_asyncio import AdGroupAdLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -384,14 +412,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupAdLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -399,7 +423,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -431,22 +455,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupAdLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/base.py index dc49de26b..bdba2f4ac 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/grpc.py index ac0e0cff0..c22792d2c 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/grpc_asyncio.py index 10fb971b9..1261594b1 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_ad_service/async_client.py index f3a17693c..876cf6479 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_group_ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupAdServiceClient @@ -122,7 +121,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAdServiceAsyncClient: The constructed client. """ - return AdGroupAdServiceClient.from_service_account_info.__func__(AdGroupAdServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAdServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdGroupAdServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAdServiceAsyncClient: The constructed client. """ - return AdGroupAdServiceClient.from_service_account_file.__func__(AdGroupAdServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAdServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAdServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -456,7 +463,7 @@ async def remove_automatically_created_assets( Args: request (Optional[Union[google.ads.googleads.v21.services.types.RemoveAutomaticallyCreatedAssetsRequest, dict]]): The request object. Request message for - [AdGroupAdService.RemoveAutomaticallyCreatedAssetsRequest][]. + [AdGroupAdService.RemoveAutomaticallyCreatedAssets][google.ads.googleads.v21.services.AdGroupAdService.RemoveAutomaticallyCreatedAssets]. ad_group_ad (:class:`str`): Required. The resource name of the AdGroupAd from which to remove diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_service/client.py b/google/ads/googleads/v21/services/services/ad_group_ad_service/client.py index 906b3915d..eb2d178f6 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_group_ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupAdServiceGrpcTransport from .transports.grpc_asyncio import AdGroupAdServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -421,14 +449,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupAdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -436,7 +458,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -468,22 +490,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupAdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -974,7 +990,7 @@ def remove_automatically_created_assets( Args: request (Union[google.ads.googleads.v21.services.types.RemoveAutomaticallyCreatedAssetsRequest, dict]): The request object. Request message for - [AdGroupAdService.RemoveAutomaticallyCreatedAssetsRequest][]. + [AdGroupAdService.RemoveAutomaticallyCreatedAssets][google.ads.googleads.v21.services.AdGroupAdService.RemoveAutomaticallyCreatedAssets]. ad_group_ad (str): Required. The resource name of the AdGroupAd from which to remove diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/base.py index e816b9d3a..b07d633b1 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/base.py @@ -27,7 +27,7 @@ import google.protobuf from google.ads.googleads.v21.services.types import ad_group_ad_service -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -67,9 +67,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -82,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/grpc.py index 9b74d8f75..333989d95 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/grpc.py @@ -30,7 +30,7 @@ import proto # type: ignore from google.ads.googleads.v21.services.types import ad_group_ad_service -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO try: @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/grpc_asyncio.py index 83e82d73e..ae635b267 100644 --- a/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_ad_service/transports/grpc_asyncio.py @@ -31,7 +31,7 @@ from grpc.experimental import aio # type: ignore from google.ads.googleads.v21.services.types import ad_group_ad_service -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO try: @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_asset_service/async_client.py index 2d0919eb0..46821ca8c 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupAssetServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAssetServiceAsyncClient: The constructed client. """ - return AdGroupAssetServiceClient.from_service_account_info.__func__(AdGroupAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAssetServiceAsyncClient: The constructed client. """ - return AdGroupAssetServiceClient.from_service_account_file.__func__(AdGroupAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_service/client.py b/google/ads/googleads/v21/services/services/ad_group_asset_service/client.py index 687d11453..0b052a88f 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupAssetServiceGrpcTransport from .transports.grpc_asyncio import AdGroupAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -380,14 +408,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupAssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -395,7 +417,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -427,22 +449,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupAssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/base.py index 1928bc493..b178d7f0b 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/grpc.py index 9c3a951f2..9209a30c6 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/grpc_asyncio.py index 610e2f144..eed332bbe 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/async_client.py index dcb83d018..0c4be0e9f 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_group_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAssetSetServiceAsyncClient: The constructed client. """ - return AdGroupAssetSetServiceClient.from_service_account_info.__func__(AdGroupAssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupAssetSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAssetSetServiceAsyncClient: The constructed client. """ - return AdGroupAssetSetServiceClient.from_service_account_file.__func__(AdGroupAssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/client.py b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/client.py index ecb9c9861..0c125b5a9 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_group_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -382,14 +410,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupAssetSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -397,7 +421,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -429,22 +453,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupAssetSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/base.py index d1034b6b8..6a20f41cf 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/grpc.py index 1ba782a77..915fbc6f5 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/grpc_asyncio.py index d89ddf2bf..03c3ae753 100644 --- a/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_asset_set_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/async_client.py index d1f71fcb6..5a60b939b 100644 --- a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( ad_group_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupBidModifierServiceAsyncClient: The constructed client. """ - return AdGroupBidModifierServiceClient.from_service_account_info.__func__(AdGroupBidModifierServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupBidModifierServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupBidModifierServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupBidModifierServiceAsyncClient: The constructed client. """ - return AdGroupBidModifierServiceClient.from_service_account_file.__func__(AdGroupBidModifierServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupBidModifierServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupBidModifierServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/client.py b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/client.py index bae498576..3795adacd 100644 --- a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( ad_group_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupBidModifierServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupBidModifierServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/base.py index 4134c2502..9e084044c 100644 --- a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/grpc.py index 764f8edc5..8ff7f26ad 100644 --- a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/grpc_asyncio.py index 66f9e5901..7db01bc67 100644 --- a/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_bid_modifier_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/async_client.py index 2bf4c0902..3be8505ef 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( ad_group_criterion_customizer_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -133,7 +132,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCriterionCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCriterionCustomizerServiceClient.from_service_account_info.__func__(AdGroupCriterionCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCriterionCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCriterionCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -149,7 +153,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCriterionCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCriterionCustomizerServiceClient.from_service_account_file.__func__(AdGroupCriterionCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCriterionCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCriterionCustomizerServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/client.py b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/client.py index 17666b8e2..80a27d5dc 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( ad_group_criterion_customizer_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -392,14 +420,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCriterionCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -407,7 +431,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -439,22 +463,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCriterionCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/base.py index 0fabaf2de..3aebd9415 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/grpc.py index 50c91bfb9..49ce3702c 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/grpc_asyncio.py index 5bf3efc60..68fcb5b7b 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_customizer_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/async_client.py index 23162df23..ed3b6dcb5 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( ad_group_criterion_label_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionLabelServiceTransport, DEFAULT_CLIENT_INFO, @@ -129,7 +128,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCriterionLabelServiceAsyncClient: The constructed client. """ - return AdGroupCriterionLabelServiceClient.from_service_account_info.__func__(AdGroupCriterionLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCriterionLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCriterionLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -145,7 +149,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCriterionLabelServiceAsyncClient: The constructed client. """ - return AdGroupCriterionLabelServiceClient.from_service_account_file.__func__(AdGroupCriterionLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCriterionLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCriterionLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/client.py b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/client.py index 699e97ff8..03502bee3 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( ad_group_criterion_label_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionLabelServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -391,14 +419,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCriterionLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -406,7 +430,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -438,22 +462,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCriterionLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/base.py index 8d3cef52c..cafcb3819 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/grpc.py index b3544b802..8fa349b10 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/grpc_asyncio.py index 73b034c94..4c1077e84 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_label_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_criterion_service/async_client.py index c199ae36b..691e24fb7 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_group_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -143,7 +142,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCriterionServiceAsyncClient: The constructed client. """ - return AdGroupCriterionServiceClient.from_service_account_info.__func__(AdGroupCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -159,7 +163,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCriterionServiceAsyncClient: The constructed client. """ - return AdGroupCriterionServiceClient.from_service_account_file.__func__(AdGroupCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCriterionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_service/client.py b/google/ads/googleads/v21/services/services/ad_group_criterion_service/client.py index 7d3b5cd9b..01d3dd97d 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_group_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -441,14 +469,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -456,7 +480,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -488,22 +512,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/base.py index 564a6b7a0..72f8cb9f8 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/grpc.py index a020e8f19..cb5a6718f 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/grpc_asyncio.py index f31dde3df..2b2ee0d56 100644 --- a/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_criterion_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_customizer_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_customizer_service/async_client.py index 6a6e57cc2..c198bf65a 100644 --- a/google/ads/googleads/v21/services/services/ad_group_customizer_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_group_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCustomizerServiceClient.from_service_account_info.__func__(AdGroupCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCustomizerServiceClient.from_service_account_file.__func__(AdGroupCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCustomizerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_customizer_service/client.py b/google/ads/googleads/v21/services/services/ad_group_customizer_service/client.py index 82200bc5e..37aa8918f 100644 --- a/google/ads/googleads/v21/services/services/ad_group_customizer_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_customizer_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_group_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/base.py index 835b2ae6f..1f0baa08d 100644 --- a/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/grpc.py index 78d073e07..9343aecc8 100644 --- a/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/grpc_asyncio.py index 5dd3058bf..e1240ba5d 100644 --- a/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_customizer_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_label_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_label_service/async_client.py index a9388737d..88696c4f1 100644 --- a/google/ads/googleads/v21/services/services/ad_group_label_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_group_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupLabelServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupLabelServiceAsyncClient: The constructed client. """ - return AdGroupLabelServiceClient.from_service_account_info.__func__(AdGroupLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupLabelServiceAsyncClient: The constructed client. """ - return AdGroupLabelServiceClient.from_service_account_file.__func__(AdGroupLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_label_service/client.py b/google/ads/googleads/v21/services/services/ad_group_label_service/client.py index 00f3ae8fc..c15a0f254 100644 --- a/google/ads/googleads/v21/services/services/ad_group_label_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_group_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupLabelServiceGrpcTransport from .transports.grpc_asyncio import AdGroupLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -378,14 +406,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupLabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -393,7 +415,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -425,22 +447,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupLabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_label_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_label_service/transports/base.py index b4ebc8ce9..dbbfe22a6 100644 --- a/google/ads/googleads/v21/services/services/ad_group_label_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_label_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_label_service/transports/grpc.py index 56dbcb8e8..f57a294b8 100644 --- a/google/ads/googleads/v21/services/services/ad_group_label_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_label_service/transports/grpc_asyncio.py index 94db1fe7f..bc04e9e96 100644 --- a/google/ads/googleads/v21/services/services/ad_group_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_service/async_client.py b/google/ads/googleads/v21/services/services/ad_group_service/async_client.py index 28e3f0844..83d1262d9 100644 --- a/google/ads/googleads/v21/services/services/ad_group_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupServiceAsyncClient: The constructed client. """ - return AdGroupServiceClient.from_service_account_info.__func__(AdGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdGroupServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupServiceAsyncClient: The constructed client. """ - return AdGroupServiceClient.from_service_account_file.__func__(AdGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_group_service/client.py b/google/ads/googleads/v21/services/services/ad_group_service/client.py index 76eb5e89e..aebe8edc7 100644 --- a/google/ads/googleads/v21/services/services/ad_group_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_group_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupServiceGrpcTransport from .transports.grpc_asyncio import AdGroupServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -377,14 +405,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -392,7 +414,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -424,22 +446,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_group_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_group_service/transports/base.py index 75dae6f15..861094633 100644 --- a/google/ads/googleads/v21/services/services/ad_group_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_group_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_group_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_group_service/transports/grpc.py index 6c10f5920..566b5d57d 100644 --- a/google/ads/googleads/v21/services/services/ad_group_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_group_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_group_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_group_service/transports/grpc_asyncio.py index a26652792..fee512ce7 100644 --- a/google/ads/googleads/v21/services/services/ad_group_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_group_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_parameter_service/async_client.py b/google/ads/googleads/v21/services/services/ad_parameter_service/async_client.py index 42f2f5075..ff6c05486 100644 --- a/google/ads/googleads/v21/services/services/ad_parameter_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_parameter_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_parameter_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdParameterServiceTransport, DEFAULT_CLIENT_INFO from .client import AdParameterServiceClient @@ -116,7 +115,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdParameterServiceAsyncClient: The constructed client. """ - return AdParameterServiceClient.from_service_account_info.__func__(AdParameterServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdParameterServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdParameterServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,7 +136,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdParameterServiceAsyncClient: The constructed client. """ - return AdParameterServiceClient.from_service_account_file.__func__(AdParameterServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdParameterServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdParameterServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_parameter_service/client.py b/google/ads/googleads/v21/services/services/ad_parameter_service/client.py index 3b514096e..ba530ef0e 100644 --- a/google/ads/googleads/v21/services/services/ad_parameter_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_parameter_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_parameter_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdParameterServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdParameterServiceGrpcTransport from .transports.grpc_asyncio import AdParameterServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -361,14 +389,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdParameterServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -376,7 +398,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -408,22 +430,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdParameterServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_parameter_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_parameter_service/transports/base.py index a1cd1a6fe..df45d6d43 100644 --- a/google/ads/googleads/v21/services/services/ad_parameter_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_parameter_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_parameter_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_parameter_service/transports/grpc.py index 5125a665a..161cac207 100644 --- a/google/ads/googleads/v21/services/services/ad_parameter_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_parameter_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_parameter_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_parameter_service/transports/grpc_asyncio.py index 2d8a472a5..0f441e5f8 100644 --- a/google/ads/googleads/v21/services/services/ad_parameter_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_parameter_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_service/async_client.py b/google/ads/googleads/v21/services/services/ad_service/async_client.py index 17e685418..740df0ac9 100644 --- a/google/ads/googleads/v21/services/services/ad_service/async_client.py +++ b/google/ads/googleads/v21/services/services/ad_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdServiceTransport, DEFAULT_CLIENT_INFO from .client import AdServiceClient @@ -100,7 +99,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdServiceAsyncClient: The constructed client. """ - return AdServiceClient.from_service_account_info.__func__(AdServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -116,7 +118,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdServiceAsyncClient: The constructed client. """ - return AdServiceClient.from_service_account_file.__func__(AdServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AdServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/ad_service/client.py b/google/ads/googleads/v21/services/services/ad_service/client.py index a9f16ce05..7221f2a83 100644 --- a/google/ads/googleads/v21/services/services/ad_service/client.py +++ b/google/ads/googleads/v21/services/services/ad_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdServiceGrpcTransport from .transports.grpc_asyncio import AdServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -334,14 +362,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -349,7 +371,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -381,22 +403,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/ad_service/transports/base.py b/google/ads/googleads/v21/services/services/ad_service/transports/base.py index 89ecce31e..e9d07e66f 100644 --- a/google/ads/googleads/v21/services/services/ad_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/ad_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/ad_service/transports/grpc.py b/google/ads/googleads/v21/services/services/ad_service/transports/grpc.py index 81093deee..d1e9f57f2 100644 --- a/google/ads/googleads/v21/services/services/ad_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/ad_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/ad_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/ad_service/transports/grpc_asyncio.py index 914c96516..cb19ca6bd 100644 --- a/google/ads/googleads/v21/services/services/ad_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/ad_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_group_asset_service/async_client.py b/google/ads/googleads/v21/services/services/asset_group_asset_service/async_client.py index 60247b8a4..69a431c0a 100644 --- a/google/ads/googleads/v21/services/services/asset_group_asset_service/async_client.py +++ b/google/ads/googleads/v21/services/services/asset_group_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import asset_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupAssetServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupAssetServiceAsyncClient: The constructed client. """ - return AssetGroupAssetServiceClient.from_service_account_info.__func__(AssetGroupAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGroupAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupAssetServiceAsyncClient: The constructed client. """ - return AssetGroupAssetServiceClient.from_service_account_file.__func__(AssetGroupAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/asset_group_asset_service/client.py b/google/ads/googleads/v21/services/services/asset_group_asset_service/client.py index a03a72a2d..ce2cb33ba 100644 --- a/google/ads/googleads/v21/services/services/asset_group_asset_service/client.py +++ b/google/ads/googleads/v21/services/services/asset_group_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import asset_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupAssetServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -383,14 +411,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGroupAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -398,7 +422,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -430,22 +454,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGroupAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/base.py b/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/base.py index d7e60ee17..b110ecffd 100644 --- a/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/grpc.py b/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/grpc.py index 09454829c..04cf6ddfb 100644 --- a/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/grpc_asyncio.py index 0c8e4ba6f..3094e8c71 100644 --- a/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/asset_group_asset_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/async_client.py b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/async_client.py index 9aad621dc..6e9175131 100644 --- a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/async_client.py +++ b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -128,7 +127,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupListingGroupFilterServiceAsyncClient: The constructed client. """ - return AssetGroupListingGroupFilterServiceClient.from_service_account_info.__func__(AssetGroupListingGroupFilterServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupListingGroupFilterServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGroupListingGroupFilterServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -144,7 +151,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupListingGroupFilterServiceAsyncClient: The constructed client. """ - return AssetGroupListingGroupFilterServiceClient.from_service_account_file.__func__(AssetGroupListingGroupFilterServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupListingGroupFilterServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupListingGroupFilterServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/client.py b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/client.py index 229776f2e..f826c2f16 100644 --- a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/client.py +++ b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/client.py @@ -156,6 +156,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -371,14 +399,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGroupListingGroupFilterServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -386,7 +410,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -418,22 +442,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGroupListingGroupFilterServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/base.py b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/base.py index d17612381..900d3ae3b 100644 --- a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/grpc.py b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/grpc.py index 5b932079e..53a38578b 100644 --- a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/grpc_asyncio.py index 2b0e7ff75..5b5233739 100644 --- a/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/asset_group_listing_group_filter_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_group_service/async_client.py b/google/ads/googleads/v21/services/services/asset_group_service/async_client.py index 84eec645a..c6cc37be0 100644 --- a/google/ads/googleads/v21/services/services/asset_group_service/async_client.py +++ b/google/ads/googleads/v21/services/services/asset_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import asset_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetGroupServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetGroupServiceClient @@ -114,7 +113,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupServiceAsyncClient: The constructed client. """ - return AssetGroupServiceClient.from_service_account_info.__func__(AssetGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssetGroupServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupServiceAsyncClient: The constructed client. """ - return AssetGroupServiceClient.from_service_account_file.__func__(AssetGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/asset_group_service/client.py b/google/ads/googleads/v21/services/services/asset_group_service/client.py index b9ca37095..edc1b05c7 100644 --- a/google/ads/googleads/v21/services/services/asset_group_service/client.py +++ b/google/ads/googleads/v21/services/services/asset_group_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import asset_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetGroupServiceGrpcTransport from .transports.grpc_asyncio import AssetGroupServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -355,14 +383,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AssetGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -370,7 +392,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -402,22 +424,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AssetGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/asset_group_service/transports/base.py b/google/ads/googleads/v21/services/services/asset_group_service/transports/base.py index e2801464f..b51a56b56 100644 --- a/google/ads/googleads/v21/services/services/asset_group_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/asset_group_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/asset_group_service/transports/grpc.py b/google/ads/googleads/v21/services/services/asset_group_service/transports/grpc.py index 3fd43a331..d84609d8d 100644 --- a/google/ads/googleads/v21/services/services/asset_group_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/asset_group_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_group_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/asset_group_service/transports/grpc_asyncio.py index 74ece4298..e299402b3 100644 --- a/google/ads/googleads/v21/services/services/asset_group_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/asset_group_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_group_signal_service/async_client.py b/google/ads/googleads/v21/services/services/asset_group_signal_service/async_client.py index 4fca7c488..c83544497 100644 --- a/google/ads/googleads/v21/services/services/asset_group_signal_service/async_client.py +++ b/google/ads/googleads/v21/services/services/asset_group_signal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import asset_group_signal_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupSignalServiceTransport, DEFAULT_CLIENT_INFO, @@ -121,7 +120,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupSignalServiceAsyncClient: The constructed client. """ - return AssetGroupSignalServiceClient.from_service_account_info.__func__(AssetGroupSignalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupSignalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGroupSignalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -137,7 +141,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupSignalServiceAsyncClient: The constructed client. """ - return AssetGroupSignalServiceClient.from_service_account_file.__func__(AssetGroupSignalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupSignalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupSignalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/asset_group_signal_service/client.py b/google/ads/googleads/v21/services/services/asset_group_signal_service/client.py index fd9946ad5..2d616eefb 100644 --- a/google/ads/googleads/v21/services/services/asset_group_signal_service/client.py +++ b/google/ads/googleads/v21/services/services/asset_group_signal_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import asset_group_signal_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupSignalServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -364,14 +392,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGroupSignalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -379,7 +403,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -411,22 +435,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGroupSignalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/base.py b/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/base.py index 72ce10d94..7cf488b99 100644 --- a/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/grpc.py b/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/grpc.py index e6da9f756..0b09b0c98 100644 --- a/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/grpc_asyncio.py index d17e8a156..2766de2de 100644 --- a/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/asset_group_signal_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_service/async_client.py b/google/ads/googleads/v21/services/services/asset_service/async_client.py index 05e840b69..51564396a 100644 --- a/google/ads/googleads/v21/services/services/asset_service/async_client.py +++ b/google/ads/googleads/v21/services/services/asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetServiceClient @@ -109,7 +108,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetServiceAsyncClient: The constructed client. """ - return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssetServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -125,7 +127,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetServiceAsyncClient: The constructed client. """ - return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AssetServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/asset_service/client.py b/google/ads/googleads/v21/services/services/asset_service/client.py index 00f042562..6584efd73 100644 --- a/google/ads/googleads/v21/services/services/asset_service/client.py +++ b/google/ads/googleads/v21/services/services/asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport @@ -147,6 +147,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -357,14 +385,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -372,7 +394,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -404,22 +426,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/asset_service/transports/base.py b/google/ads/googleads/v21/services/services/asset_service/transports/base.py index 3abaa3947..6e0773895 100644 --- a/google/ads/googleads/v21/services/services/asset_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/asset_service/transports/grpc.py b/google/ads/googleads/v21/services/services/asset_service/transports/grpc.py index c240317ed..18efc4a46 100644 --- a/google/ads/googleads/v21/services/services/asset_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/asset_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/asset_service/transports/grpc_asyncio.py index 51d84ee84..5f31d4be1 100644 --- a/google/ads/googleads/v21/services/services/asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/asset_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_set_asset_service/async_client.py b/google/ads/googleads/v21/services/services/asset_set_asset_service/async_client.py index fc62e1708..64615e4c3 100644 --- a/google/ads/googleads/v21/services/services/asset_set_asset_service/async_client.py +++ b/google/ads/googleads/v21/services/services/asset_set_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import asset_set_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetSetAssetServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetSetAssetServiceAsyncClient: The constructed client. """ - return AssetSetAssetServiceClient.from_service_account_info.__func__(AssetSetAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetSetAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetSetAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetSetAssetServiceAsyncClient: The constructed client. """ - return AssetSetAssetServiceClient.from_service_account_file.__func__(AssetSetAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetSetAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetSetAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/asset_set_asset_service/client.py b/google/ads/googleads/v21/services/services/asset_set_asset_service/client.py index 248942fcc..756191740 100644 --- a/google/ads/googleads/v21/services/services/asset_set_asset_service/client.py +++ b/google/ads/googleads/v21/services/services/asset_set_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import asset_set_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetSetAssetServiceGrpcTransport from .transports.grpc_asyncio import AssetSetAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -378,14 +406,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetSetAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -393,7 +417,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -425,22 +449,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetSetAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/base.py b/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/base.py index bcfe6b8e6..3b3a70f93 100644 --- a/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/grpc.py b/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/grpc.py index 8ff568295..6bec565c3 100644 --- a/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/grpc_asyncio.py index bdeb2e04c..d6653cc1e 100644 --- a/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/asset_set_asset_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_set_service/async_client.py b/google/ads/googleads/v21/services/services/asset_set_service/async_client.py index bf36f95c5..26ea48be7 100644 --- a/google/ads/googleads/v21/services/services/asset_set_service/async_client.py +++ b/google/ads/googleads/v21/services/services/asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetSetServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetSetServiceAsyncClient: The constructed client. """ - return AssetSetServiceClient.from_service_account_info.__func__(AssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssetSetServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetSetServiceAsyncClient: The constructed client. """ - return AssetSetServiceClient.from_service_account_file.__func__(AssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/asset_set_service/client.py b/google/ads/googleads/v21/services/services/asset_set_service/client.py index e24c029ee..fe9335915 100644 --- a/google/ads/googleads/v21/services/services/asset_set_service/client.py +++ b/google/ads/googleads/v21/services/services/asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetSetServiceGrpcTransport from .transports.grpc_asyncio import AssetSetServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AssetSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AssetSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/asset_set_service/transports/base.py b/google/ads/googleads/v21/services/services/asset_set_service/transports/base.py index 1d9bd00ad..7864ab561 100644 --- a/google/ads/googleads/v21/services/services/asset_set_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/asset_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/asset_set_service/transports/grpc.py b/google/ads/googleads/v21/services/services/asset_set_service/transports/grpc.py index 4da97aa5c..eede0aeac 100644 --- a/google/ads/googleads/v21/services/services/asset_set_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/asset_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/asset_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/asset_set_service/transports/grpc_asyncio.py index ef7408472..0162f88cc 100644 --- a/google/ads/googleads/v21/services/services/asset_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/asset_set_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/audience_insights_service/async_client.py b/google/ads/googleads/v21/services/services/audience_insights_service/async_client.py index 49bcaf1e4..f8c235d48 100644 --- a/google/ads/googleads/v21/services/services/audience_insights_service/async_client.py +++ b/google/ads/googleads/v21/services/services/audience_insights_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -114,7 +113,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AudienceInsightsServiceAsyncClient: The constructed client. """ - return AudienceInsightsServiceClient.from_service_account_info.__func__(AudienceInsightsServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AudienceInsightsServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AudienceInsightsServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +134,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AudienceInsightsServiceAsyncClient: The constructed client. """ - return AudienceInsightsServiceClient.from_service_account_file.__func__(AudienceInsightsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AudienceInsightsServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AudienceInsightsServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/audience_insights_service/client.py b/google/ads/googleads/v21/services/services/audience_insights_service/client.py index a01e3dd5a..b53957daa 100644 --- a/google/ads/googleads/v21/services/services/audience_insights_service/client.py +++ b/google/ads/googleads/v21/services/services/audience_insights_service/client.py @@ -156,6 +156,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -327,14 +355,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AudienceInsightsServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -342,7 +366,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -374,22 +398,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AudienceInsightsServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/audience_insights_service/transports/base.py b/google/ads/googleads/v21/services/services/audience_insights_service/transports/base.py index 2a3c6a28b..48dfe599a 100644 --- a/google/ads/googleads/v21/services/services/audience_insights_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/audience_insights_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/audience_insights_service/transports/grpc.py b/google/ads/googleads/v21/services/services/audience_insights_service/transports/grpc.py index a30e73ee6..6307f7d77 100644 --- a/google/ads/googleads/v21/services/services/audience_insights_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/audience_insights_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/audience_insights_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/audience_insights_service/transports/grpc_asyncio.py index 0577d9cd0..c5f38481b 100644 --- a/google/ads/googleads/v21/services/services/audience_insights_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/audience_insights_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/audience_service/async_client.py b/google/ads/googleads/v21/services/services/audience_service/async_client.py index fcf8c659f..f9eea95a4 100644 --- a/google/ads/googleads/v21/services/services/audience_service/async_client.py +++ b/google/ads/googleads/v21/services/services/audience_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import audience_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AudienceServiceTransport, DEFAULT_CLIENT_INFO from .client import AudienceServiceClient @@ -122,7 +121,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AudienceServiceAsyncClient: The constructed client. """ - return AudienceServiceClient.from_service_account_info.__func__(AudienceServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AudienceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AudienceServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AudienceServiceAsyncClient: The constructed client. """ - return AudienceServiceClient.from_service_account_file.__func__(AudienceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AudienceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AudienceServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/audience_service/client.py b/google/ads/googleads/v21/services/services/audience_service/client.py index 564039181..f35786194 100644 --- a/google/ads/googleads/v21/services/services/audience_service/client.py +++ b/google/ads/googleads/v21/services/services/audience_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import audience_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AudienceServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AudienceServiceGrpcTransport from .transports.grpc_asyncio import AudienceServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -395,14 +423,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AudienceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -410,7 +432,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -442,22 +464,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AudienceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/audience_service/transports/base.py b/google/ads/googleads/v21/services/services/audience_service/transports/base.py index 86320baed..0ef921a90 100644 --- a/google/ads/googleads/v21/services/services/audience_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/audience_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/audience_service/transports/grpc.py b/google/ads/googleads/v21/services/services/audience_service/transports/grpc.py index 96b28c13a..2762dc00c 100644 --- a/google/ads/googleads/v21/services/services/audience_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/audience_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/audience_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/audience_service/transports/grpc_asyncio.py index 7b9a3800e..aa92c5a0b 100644 --- a/google/ads/googleads/v21/services/services/audience_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/audience_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/async_client.py b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/async_client.py index fc17fd718..4d9831f5d 100644 --- a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/async_client.py +++ b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( automatically_created_asset_removal_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AutomaticallyCreatedAssetRemovalServiceTransport, DEFAULT_CLIENT_INFO, @@ -117,7 +116,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AutomaticallyCreatedAssetRemovalServiceAsyncClient: The constructed client. """ - return AutomaticallyCreatedAssetRemovalServiceClient.from_service_account_info.__func__(AutomaticallyCreatedAssetRemovalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AutomaticallyCreatedAssetRemovalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AutomaticallyCreatedAssetRemovalServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -133,7 +140,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AutomaticallyCreatedAssetRemovalServiceAsyncClient: The constructed client. """ - return AutomaticallyCreatedAssetRemovalServiceClient.from_service_account_file.__func__(AutomaticallyCreatedAssetRemovalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AutomaticallyCreatedAssetRemovalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AutomaticallyCreatedAssetRemovalServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/client.py b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/client.py index cfb0da908..215ad4a69 100644 --- a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/client.py +++ b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( automatically_created_asset_removal_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AutomaticallyCreatedAssetRemovalServiceTransport, DEFAULT_CLIENT_INFO, @@ -159,6 +159,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -330,14 +358,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AutomaticallyCreatedAssetRemovalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -345,7 +369,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -377,22 +401,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AutomaticallyCreatedAssetRemovalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/base.py b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/base.py index b76261889..cedcdb47f 100644 --- a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/grpc.py b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/grpc.py index ca3a4d282..ab9100d60 100644 --- a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/grpc_asyncio.py index 14b26d900..bf0221b6e 100644 --- a/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/automatically_created_asset_removal_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/batch_job_service/async_client.py b/google/ads/googleads/v21/services/services/batch_job_service/async_client.py index e3e2267a6..89b83b003 100644 --- a/google/ads/googleads/v21/services/services/batch_job_service/async_client.py +++ b/google/ads/googleads/v21/services/services/batch_job_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,9 +36,9 @@ from google.ads.googleads.v21.services.services.batch_job_service import pagers from google.ads.googleads.v21.services.types import batch_job_service from google.ads.googleads.v21.services.types import google_ads_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .transports.base import BatchJobServiceTransport, DEFAULT_CLIENT_INFO from .client import BatchJobServiceClient @@ -523,7 +522,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BatchJobServiceAsyncClient: The constructed client. """ - return BatchJobServiceClient.from_service_account_info.__func__(BatchJobServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BatchJobServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(BatchJobServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -539,7 +541,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BatchJobServiceAsyncClient: The constructed client. """ - return BatchJobServiceClient.from_service_account_file.__func__(BatchJobServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BatchJobServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BatchJobServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/batch_job_service/client.py b/google/ads/googleads/v21/services/services/batch_job_service/client.py index 55f64f37d..cb484cb6d 100644 --- a/google/ads/googleads/v21/services/services/batch_job_service/client.py +++ b/google/ads/googleads/v21/services/services/batch_job_service/client.py @@ -63,9 +63,9 @@ from google.ads.googleads.v21.services.services.batch_job_service import pagers from google.ads.googleads.v21.services.types import batch_job_service from google.ads.googleads.v21.services.types import google_ads_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .transports.base import BatchJobServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import BatchJobServiceGrpcTransport from .transports.grpc_asyncio import BatchJobServiceGrpcAsyncIOTransport @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -1882,14 +1910,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = BatchJobServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -1897,7 +1919,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -1929,22 +1951,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = BatchJobServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/batch_job_service/transports/base.py b/google/ads/googleads/v21/services/services/batch_job_service/transports/base.py index 78a6b995d..f63db9426 100644 --- a/google/ads/googleads/v21/services/services/batch_job_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/batch_job_service/transports/base.py @@ -67,9 +67,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -82,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/batch_job_service/transports/grpc.py b/google/ads/googleads/v21/services/services/batch_job_service/transports/grpc.py index bad4859df..b1c59bc35 100644 --- a/google/ads/googleads/v21/services/services/batch_job_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/batch_job_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -308,9 +309,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/batch_job_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/batch_job_service/transports/grpc_asyncio.py index 6f86ca970..57a05a539 100644 --- a/google/ads/googleads/v21/services/services/batch_job_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/batch_job_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/async_client.py b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/async_client.py index 98b351483..5ae3c085f 100644 --- a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/async_client.py +++ b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( bidding_data_exclusion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingDataExclusionServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BiddingDataExclusionServiceAsyncClient: The constructed client. """ - return BiddingDataExclusionServiceClient.from_service_account_info.__func__(BiddingDataExclusionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BiddingDataExclusionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BiddingDataExclusionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BiddingDataExclusionServiceAsyncClient: The constructed client. """ - return BiddingDataExclusionServiceClient.from_service_account_file.__func__(BiddingDataExclusionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BiddingDataExclusionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BiddingDataExclusionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/client.py b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/client.py index e693371ed..b7398f925 100644 --- a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/client.py +++ b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( bidding_data_exclusion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingDataExclusionServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -366,14 +394,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BiddingDataExclusionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -381,7 +405,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -413,22 +437,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BiddingDataExclusionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/base.py b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/base.py index f7630407a..28d5fae96 100644 --- a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/grpc.py b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/grpc.py index 371c7e5ca..288146e41 100644 --- a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/grpc_asyncio.py index 311842d00..a48b87f06 100644 --- a/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/bidding_data_exclusion_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/async_client.py b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/async_client.py index 770f45b30..e8fcccc4e 100644 --- a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/async_client.py +++ b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( bidding_seasonality_adjustment_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingSeasonalityAdjustmentServiceTransport, DEFAULT_CLIENT_INFO, @@ -129,7 +128,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BiddingSeasonalityAdjustmentServiceAsyncClient: The constructed client. """ - return BiddingSeasonalityAdjustmentServiceClient.from_service_account_info.__func__(BiddingSeasonalityAdjustmentServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BiddingSeasonalityAdjustmentServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BiddingSeasonalityAdjustmentServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -145,7 +152,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BiddingSeasonalityAdjustmentServiceAsyncClient: The constructed client. """ - return BiddingSeasonalityAdjustmentServiceClient.from_service_account_file.__func__(BiddingSeasonalityAdjustmentServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BiddingSeasonalityAdjustmentServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BiddingSeasonalityAdjustmentServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/client.py b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/client.py index 527890364..c9d419406 100644 --- a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/client.py +++ b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( bidding_seasonality_adjustment_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingSeasonalityAdjustmentServiceTransport, DEFAULT_CLIENT_INFO, @@ -157,6 +157,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BiddingSeasonalityAdjustmentServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BiddingSeasonalityAdjustmentServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/base.py b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/base.py index 082ce5726..d3adf143b 100644 --- a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/grpc.py b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/grpc.py index 8b0facbd2..12f59d9ac 100644 --- a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/grpc_asyncio.py index 330f8d417..8552aa0bc 100644 --- a/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/bidding_seasonality_adjustment_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/bidding_strategy_service/async_client.py b/google/ads/googleads/v21/services/services/bidding_strategy_service/async_client.py index 837caf966..c185eada1 100644 --- a/google/ads/googleads/v21/services/services/bidding_strategy_service/async_client.py +++ b/google/ads/googleads/v21/services/services/bidding_strategy_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import bidding_strategy_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingStrategyServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BiddingStrategyServiceAsyncClient: The constructed client. """ - return BiddingStrategyServiceClient.from_service_account_info.__func__(BiddingStrategyServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BiddingStrategyServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BiddingStrategyServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BiddingStrategyServiceAsyncClient: The constructed client. """ - return BiddingStrategyServiceClient.from_service_account_file.__func__(BiddingStrategyServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BiddingStrategyServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BiddingStrategyServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/bidding_strategy_service/client.py b/google/ads/googleads/v21/services/services/bidding_strategy_service/client.py index 6a715effc..fa82fc483 100644 --- a/google/ads/googleads/v21/services/services/bidding_strategy_service/client.py +++ b/google/ads/googleads/v21/services/services/bidding_strategy_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import bidding_strategy_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingStrategyServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -340,14 +368,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BiddingStrategyServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -355,7 +379,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -387,22 +411,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BiddingStrategyServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/base.py b/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/base.py index f97404221..d41f85d43 100644 --- a/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/grpc.py b/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/grpc.py index f448314d6..adb3c3b87 100644 --- a/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/grpc_asyncio.py index ddb57f705..e42efc48f 100644 --- a/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/bidding_strategy_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/billing_setup_service/async_client.py b/google/ads/googleads/v21/services/services/billing_setup_service/async_client.py index 1a79edd6b..0b4066ad7 100644 --- a/google/ads/googleads/v21/services/services/billing_setup_service/async_client.py +++ b/google/ads/googleads/v21/services/services/billing_setup_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -128,7 +127,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BillingSetupServiceAsyncClient: The constructed client. """ - return BillingSetupServiceClient.from_service_account_info.__func__(BillingSetupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BillingSetupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BillingSetupServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -144,7 +148,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BillingSetupServiceAsyncClient: The constructed client. """ - return BillingSetupServiceClient.from_service_account_file.__func__(BillingSetupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BillingSetupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BillingSetupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/billing_setup_service/client.py b/google/ads/googleads/v21/services/services/billing_setup_service/client.py index bb0f3ea95..96846e286 100644 --- a/google/ads/googleads/v21/services/services/billing_setup_service/client.py +++ b/google/ads/googleads/v21/services/services/billing_setup_service/client.py @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -359,14 +387,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = BillingSetupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -374,7 +396,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -406,22 +428,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = BillingSetupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/billing_setup_service/transports/base.py b/google/ads/googleads/v21/services/services/billing_setup_service/transports/base.py index 2b55b513f..4b847d2e2 100644 --- a/google/ads/googleads/v21/services/services/billing_setup_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/billing_setup_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/billing_setup_service/transports/grpc.py b/google/ads/googleads/v21/services/services/billing_setup_service/transports/grpc.py index 20be74588..bfa3bd790 100644 --- a/google/ads/googleads/v21/services/services/billing_setup_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/billing_setup_service/transports/grpc.py @@ -172,9 +172,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -315,9 +316,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/billing_setup_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/billing_setup_service/transports/grpc_asyncio.py index 0b7c6668f..1e1566f2f 100644 --- a/google/ads/googleads/v21/services/services/billing_setup_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/billing_setup_service/transports/grpc_asyncio.py @@ -162,8 +162,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -218,9 +219,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/brand_suggestion_service/async_client.py b/google/ads/googleads/v21/services/services/brand_suggestion_service/async_client.py index a36971b28..e7367ea60 100644 --- a/google/ads/googleads/v21/services/services/brand_suggestion_service/async_client.py +++ b/google/ads/googleads/v21/services/services/brand_suggestion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -108,7 +107,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BrandSuggestionServiceAsyncClient: The constructed client. """ - return BrandSuggestionServiceClient.from_service_account_info.__func__(BrandSuggestionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BrandSuggestionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BrandSuggestionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +128,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BrandSuggestionServiceAsyncClient: The constructed client. """ - return BrandSuggestionServiceClient.from_service_account_file.__func__(BrandSuggestionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BrandSuggestionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BrandSuggestionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/brand_suggestion_service/client.py b/google/ads/googleads/v21/services/services/brand_suggestion_service/client.py index 19767b5e6..3c394d278 100644 --- a/google/ads/googleads/v21/services/services/brand_suggestion_service/client.py +++ b/google/ads/googleads/v21/services/services/brand_suggestion_service/client.py @@ -138,6 +138,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -309,14 +337,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BrandSuggestionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -324,7 +348,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -356,22 +380,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BrandSuggestionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/base.py b/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/base.py index c630c864e..af28d1197 100644 --- a/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/grpc.py b/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/grpc.py index b12f7459e..9c936f0da 100644 --- a/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/grpc_asyncio.py index d51248b3d..031f423ad 100644 --- a/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/brand_suggestion_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_asset_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_asset_service/async_client.py index 52e1c2896..aa25fd535 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignAssetServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignAssetServiceAsyncClient: The constructed client. """ - return CampaignAssetServiceClient.from_service_account_info.__func__(CampaignAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignAssetServiceAsyncClient: The constructed client. """ - return CampaignAssetServiceClient.from_service_account_file.__func__(CampaignAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_asset_service/client.py b/google/ads/googleads/v21/services/services/campaign_asset_service/client.py index 743e22aeb..59366f438 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import campaign_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignAssetServiceGrpcTransport from .transports.grpc_asyncio import CampaignAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -380,14 +408,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -395,7 +419,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -427,22 +451,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_asset_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_asset_service/transports/base.py index 4afc40c7b..29154f29a 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_asset_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_asset_service/transports/grpc.py index 56aee27f3..c9d5efe6f 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_asset_service/transports/grpc_asyncio.py index cddb153b3..7535a3c08 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_asset_set_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_asset_set_service/async_client.py index 008eb41a3..7f22e701c 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_set_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignAssetSetServiceAsyncClient: The constructed client. """ - return CampaignAssetSetServiceClient.from_service_account_info.__func__(CampaignAssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignAssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignAssetSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignAssetSetServiceAsyncClient: The constructed client. """ - return CampaignAssetSetServiceClient.from_service_account_file.__func__(CampaignAssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignAssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignAssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_asset_set_service/client.py b/google/ads/googleads/v21/services/services/campaign_asset_set_service/client.py index 439229bf7..9c980d5a1 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_set_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import campaign_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -384,14 +412,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignAssetSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -399,7 +423,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -431,22 +455,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignAssetSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/base.py index 698ca5a6a..b27d84e37 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/grpc.py index 31e5577e7..060be759f 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/grpc_asyncio.py index 85d5efba9..451166cd4 100644 --- a/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_asset_set_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/async_client.py index 31cc051d8..a03ca216d 100644 --- a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( campaign_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignBidModifierServiceAsyncClient: The constructed client. """ - return CampaignBidModifierServiceClient.from_service_account_info.__func__(CampaignBidModifierServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignBidModifierServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignBidModifierServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignBidModifierServiceAsyncClient: The constructed client. """ - return CampaignBidModifierServiceClient.from_service_account_file.__func__(CampaignBidModifierServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignBidModifierServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignBidModifierServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/client.py b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/client.py index a879eab9e..dc486404f 100644 --- a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( campaign_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignBidModifierServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignBidModifierServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/base.py index 32c50b805..e108d3c42 100644 --- a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/grpc.py index 255d03ef4..4075cda38 100644 --- a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/grpc_asyncio.py index 76a8a5b39..ceef6b1ef 100644 --- a/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_bid_modifier_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_budget_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_budget_service/async_client.py index 047b1ca7e..31c5c5da7 100644 --- a/google/ads/googleads/v21/services/services/campaign_budget_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_budget_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_budget_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignBudgetServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignBudgetServiceClient @@ -112,7 +111,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignBudgetServiceAsyncClient: The constructed client. """ - return CampaignBudgetServiceClient.from_service_account_info.__func__(CampaignBudgetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignBudgetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignBudgetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -128,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignBudgetServiceAsyncClient: The constructed client. """ - return CampaignBudgetServiceClient.from_service_account_file.__func__(CampaignBudgetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignBudgetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignBudgetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_budget_service/client.py b/google/ads/googleads/v21/services/services/campaign_budget_service/client.py index 3ebe86a14..af9aba68d 100644 --- a/google/ads/googleads/v21/services/services/campaign_budget_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_budget_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import campaign_budget_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignBudgetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignBudgetServiceGrpcTransport from .transports.grpc_asyncio import CampaignBudgetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -337,14 +365,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignBudgetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -352,7 +376,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -384,22 +408,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignBudgetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_budget_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_budget_service/transports/base.py index 10b8ec308..7f2537df2 100644 --- a/google/ads/googleads/v21/services/services/campaign_budget_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_budget_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_budget_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_budget_service/transports/grpc.py index 4bd6b10cb..022c739a0 100644 --- a/google/ads/googleads/v21/services/services/campaign_budget_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_budget_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_budget_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_budget_service/transports/grpc_asyncio.py index 842ff3e3b..59751b06f 100644 --- a/google/ads/googleads/v21/services/services/campaign_budget_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_budget_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/async_client.py index d5e09d959..e88b25674 100644 --- a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignConversionGoalServiceAsyncClient: The constructed client. """ - return CampaignConversionGoalServiceClient.from_service_account_info.__func__(CampaignConversionGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignConversionGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignConversionGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignConversionGoalServiceAsyncClient: The constructed client. """ - return CampaignConversionGoalServiceClient.from_service_account_file.__func__(CampaignConversionGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignConversionGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignConversionGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/client.py b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/client.py index d9ae60216..28fd70284 100644 --- a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -369,14 +397,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignConversionGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -384,7 +408,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -416,22 +440,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignConversionGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/base.py index 34459e7d5..88b37e645 100644 --- a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/grpc.py index 383270287..814a0a64b 100644 --- a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/grpc_asyncio.py index 7e735824c..0937f946d 100644 --- a/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_conversion_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_criterion_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_criterion_service/async_client.py index 9529d0b97..9fa63034a 100644 --- a/google/ads/googleads/v21/services/services/campaign_criterion_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -161,7 +160,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignCriterionServiceAsyncClient: The constructed client. """ - return CampaignCriterionServiceClient.from_service_account_info.__func__(CampaignCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -177,7 +181,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignCriterionServiceAsyncClient: The constructed client. """ - return CampaignCriterionServiceClient.from_service_account_file.__func__(CampaignCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignCriterionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_criterion_service/client.py b/google/ads/googleads/v21/services/services/campaign_criterion_service/client.py index 5f3d86943..2bf8b9c11 100644 --- a/google/ads/googleads/v21/services/services/campaign_criterion_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_criterion_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import campaign_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -488,14 +516,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -503,7 +527,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -535,22 +559,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/base.py index c145b8b0f..41fe7b695 100644 --- a/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/grpc.py index 24bf9bd04..79c1bea4c 100644 --- a/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/grpc_asyncio.py index 3555db6fe..16c7bf4c9 100644 --- a/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_criterion_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_customizer_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_customizer_service/async_client.py index c7e243efe..c6c211534 100644 --- a/google/ads/googleads/v21/services/services/campaign_customizer_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -127,7 +126,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignCustomizerServiceAsyncClient: The constructed client. """ - return CampaignCustomizerServiceClient.from_service_account_info.__func__(CampaignCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -143,7 +147,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignCustomizerServiceAsyncClient: The constructed client. """ - return CampaignCustomizerServiceClient.from_service_account_file.__func__(CampaignCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignCustomizerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_customizer_service/client.py b/google/ads/googleads/v21/services/services/campaign_customizer_service/client.py index ef013cf48..3783bfd3c 100644 --- a/google/ads/googleads/v21/services/services/campaign_customizer_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_customizer_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import campaign_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/base.py index b8ec44e67..d6cd879c4 100644 --- a/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/grpc.py index bd979ed1e..ff1cfbe29 100644 --- a/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/grpc_asyncio.py index 7c4532725..386a3f09a 100644 --- a/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_customizer_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_draft_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_draft_service/async_client.py index 40833f4e8..80562c72f 100644 --- a/google/ads/googleads/v21/services/services/campaign_draft_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_draft_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,10 +36,10 @@ pagers, ) from google.ads.googleads.v21.services.types import campaign_draft_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignDraftServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignDraftServiceClient @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignDraftServiceAsyncClient: The constructed client. """ - return CampaignDraftServiceClient.from_service_account_info.__func__(CampaignDraftServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignDraftServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignDraftServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignDraftServiceAsyncClient: The constructed client. """ - return CampaignDraftServiceClient.from_service_account_file.__func__(CampaignDraftServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignDraftServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignDraftServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -433,10 +442,11 @@ async def promote_campaign_draft( r"""Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v21.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v21/services/services/campaign_draft_service/client.py b/google/ads/googleads/v21/services/services/campaign_draft_service/client.py index d3d11458d..b15b62560 100644 --- a/google/ads/googleads/v21/services/services/campaign_draft_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_draft_service/client.py @@ -63,10 +63,10 @@ pagers, ) from google.ads.googleads.v21.services.types import campaign_draft_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignDraftServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignDraftServiceGrpcTransport from .transports.grpc_asyncio import CampaignDraftServiceGrpcAsyncIOTransport @@ -152,6 +152,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -365,14 +393,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignDraftServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -380,7 +404,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -412,22 +436,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignDraftServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -899,10 +919,11 @@ def promote_campaign_draft( r"""Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v21.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v21/services/services/campaign_draft_service/pagers.py b/google/ads/googleads/v21/services/services/campaign_draft_service/pagers.py index 812a5db64..a13705148 100644 --- a/google/ads/googleads/v21/services/services/campaign_draft_service/pagers.py +++ b/google/ads/googleads/v21/services/services/campaign_draft_service/pagers.py @@ -37,7 +37,7 @@ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_draft_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore class ListCampaignDraftAsyncErrorsPager: diff --git a/google/ads/googleads/v21/services/services/campaign_draft_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_draft_service/transports/base.py index 11ccc6c7c..dbf39f905 100644 --- a/google/ads/googleads/v21/services/services/campaign_draft_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_draft_service/transports/base.py @@ -67,9 +67,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -82,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_draft_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_draft_service/transports/grpc.py index 52586c5af..b3309fe56 100644 --- a/google/ads/googleads/v21/services/services/campaign_draft_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_draft_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -308,9 +309,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -408,10 +410,11 @@ def promote_campaign_draft( Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v21.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v21/services/services/campaign_draft_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_draft_service/transports/grpc_asyncio.py index c6aa39aea..d33dba097 100644 --- a/google/ads/googleads/v21/services/services/campaign_draft_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_draft_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -416,10 +418,11 @@ def promote_campaign_draft( Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v21.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v21/services/services/campaign_group_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_group_service/async_client.py index 46c0379f3..d14901cf4 100644 --- a/google/ads/googleads/v21/services/services/campaign_group_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignGroupServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignGroupServiceClient @@ -112,7 +111,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignGroupServiceAsyncClient: The constructed client. """ - return CampaignGroupServiceClient.from_service_account_info.__func__(CampaignGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignGroupServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -128,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignGroupServiceAsyncClient: The constructed client. """ - return CampaignGroupServiceClient.from_service_account_file.__func__(CampaignGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_group_service/client.py b/google/ads/googleads/v21/services/services/campaign_group_service/client.py index b07303252..168fd76e4 100644 --- a/google/ads/googleads/v21/services/services/campaign_group_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_group_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import campaign_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignGroupServiceGrpcTransport from .transports.grpc_asyncio import CampaignGroupServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -339,14 +367,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignGroupServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -354,7 +378,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -386,22 +410,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignGroupServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_group_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_group_service/transports/base.py index 8c4ccedc7..91c7cc21e 100644 --- a/google/ads/googleads/v21/services/services/campaign_group_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_group_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_group_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_group_service/transports/grpc.py index 7055b3541..7fa9016d6 100644 --- a/google/ads/googleads/v21/services/services/campaign_group_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_group_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_group_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_group_service/transports/grpc_asyncio.py index ff5a0a0de..bd2d30cce 100644 --- a/google/ads/googleads/v21/services/services/campaign_group_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_group_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_label_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_label_service/async_client.py index 187d9cb09..469011f26 100644 --- a/google/ads/googleads/v21/services/services/campaign_label_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignLabelServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignLabelServiceAsyncClient: The constructed client. """ - return CampaignLabelServiceClient.from_service_account_info.__func__(CampaignLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignLabelServiceAsyncClient: The constructed client. """ - return CampaignLabelServiceClient.from_service_account_file.__func__(CampaignLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_label_service/client.py b/google/ads/googleads/v21/services/services/campaign_label_service/client.py index 71503a76a..94edef134 100644 --- a/google/ads/googleads/v21/services/services/campaign_label_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import campaign_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignLabelServiceGrpcTransport from .transports.grpc_asyncio import CampaignLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -378,14 +406,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -393,7 +417,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -425,22 +449,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_label_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_label_service/transports/base.py index 1e9a109d8..2bc8280f3 100644 --- a/google/ads/googleads/v21/services/services/campaign_label_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_label_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_label_service/transports/grpc.py index 89881b57d..e4ef2057b 100644 --- a/google/ads/googleads/v21/services/services/campaign_label_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_label_service/transports/grpc_asyncio.py index b25d9c347..a5d5ee4e3 100644 --- a/google/ads/googleads/v21/services/services/campaign_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/async_client.py index feae6a347..361dc3d30 100644 --- a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignLifecycleGoalServiceAsyncClient: The constructed client. """ - return CampaignLifecycleGoalServiceClient.from_service_account_info.__func__(CampaignLifecycleGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignLifecycleGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignLifecycleGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignLifecycleGoalServiceAsyncClient: The constructed client. """ - return CampaignLifecycleGoalServiceClient.from_service_account_file.__func__(CampaignLifecycleGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignLifecycleGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignLifecycleGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -337,7 +346,7 @@ async def configure_campaign_lifecycle_goals( Args: request (Optional[Union[google.ads.googleads.v21.services.types.ConfigureCampaignLifecycleGoalsRequest, dict]]): The request object. Request message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v21.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. customer_id (:class:`str`): Required. The ID of the customer performing the upload. @@ -363,7 +372,7 @@ async def configure_campaign_lifecycle_goals( Returns: google.ads.googleads.v21.services.types.ConfigureCampaignLifecycleGoalsResponse: Response message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v21.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/client.py b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/client.py index 5de9d4a04..1a55afac3 100644 --- a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -355,14 +383,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignLifecycleGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -370,7 +394,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -402,22 +426,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignLifecycleGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -801,7 +821,7 @@ def configure_campaign_lifecycle_goals( Args: request (Union[google.ads.googleads.v21.services.types.ConfigureCampaignLifecycleGoalsRequest, dict]): The request object. Request message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v21.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. customer_id (str): Required. The ID of the customer performing the upload. @@ -827,7 +847,7 @@ def configure_campaign_lifecycle_goals( Returns: google.ads.googleads.v21.services.types.ConfigureCampaignLifecycleGoalsResponse: Response message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v21.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/base.py index a026ca3e6..5f02761f5 100644 --- a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/grpc.py index f7ff4286a..4da70bd86 100644 --- a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/grpc_asyncio.py index fdd632eff..4f76a8751 100644 --- a/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_lifecycle_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_service/async_client.py index a08e1a89e..7fc77fba3 100644 --- a/google/ads/googleads/v21/services/services/campaign_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignServiceClient @@ -148,7 +147,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignServiceAsyncClient: The constructed client. """ - return CampaignServiceClient.from_service_account_info.__func__(CampaignServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(CampaignServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -164,7 +166,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignServiceAsyncClient: The constructed client. """ - return CampaignServiceClient.from_service_account_file.__func__(CampaignServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_service/client.py b/google/ads/googleads/v21/services/services/campaign_service/client.py index 09f36dc50..2c6f3f89e 100644 --- a/google/ads/googleads/v21/services/services/campaign_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import campaign_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignServiceGrpcTransport from .transports.grpc_asyncio import CampaignServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -479,14 +507,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = CampaignServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -494,7 +516,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -526,22 +548,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = CampaignServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_service/transports/base.py index c0b719f7d..dfab35a2c 100644 --- a/google/ads/googleads/v21/services/services/campaign_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_service/transports/grpc.py index b69788f6d..802292b2f 100644 --- a/google/ads/googleads/v21/services/services/campaign_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_service/transports/grpc_asyncio.py index 7f857cc1e..e8cf86642 100644 --- a/google/ads/googleads/v21/services/services/campaign_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_shared_set_service/async_client.py b/google/ads/googleads/v21/services/services/campaign_shared_set_service/async_client.py index 1ad4f36c1..92afe903c 100644 --- a/google/ads/googleads/v21/services/services/campaign_shared_set_service/async_client.py +++ b/google/ads/googleads/v21/services/services/campaign_shared_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import campaign_shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignSharedSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignSharedSetServiceAsyncClient: The constructed client. """ - return CampaignSharedSetServiceClient.from_service_account_info.__func__(CampaignSharedSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignSharedSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignSharedSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignSharedSetServiceAsyncClient: The constructed client. """ - return CampaignSharedSetServiceClient.from_service_account_file.__func__(CampaignSharedSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignSharedSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignSharedSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/campaign_shared_set_service/client.py b/google/ads/googleads/v21/services/services/campaign_shared_set_service/client.py index a3aa9a3c1..a83c641d4 100644 --- a/google/ads/googleads/v21/services/services/campaign_shared_set_service/client.py +++ b/google/ads/googleads/v21/services/services/campaign_shared_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import campaign_shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignSharedSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignSharedSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignSharedSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/base.py b/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/base.py index 1dd0dc700..79051e409 100644 --- a/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/grpc.py b/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/grpc.py index 55a07ea7e..494cd46f6 100644 --- a/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/grpc_asyncio.py index 11f8c3922..613faac96 100644 --- a/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/campaign_shared_set_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/content_creator_insights_service/async_client.py b/google/ads/googleads/v21/services/services/content_creator_insights_service/async_client.py index 34a2bd6ae..0f22b15d6 100644 --- a/google/ads/googleads/v21/services/services/content_creator_insights_service/async_client.py +++ b/google/ads/googleads/v21/services/services/content_creator_insights_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -116,7 +115,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ContentCreatorInsightsServiceAsyncClient: The constructed client. """ - return ContentCreatorInsightsServiceClient.from_service_account_info.__func__(ContentCreatorInsightsServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ContentCreatorInsightsServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ContentCreatorInsightsServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,7 +136,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ContentCreatorInsightsServiceAsyncClient: The constructed client. """ - return ContentCreatorInsightsServiceClient.from_service_account_file.__func__(ContentCreatorInsightsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ContentCreatorInsightsServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ContentCreatorInsightsServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -405,7 +414,7 @@ async def generate_trending_insights( Args: request (Optional[Union[google.ads.googleads.v21.services.types.GenerateTrendingInsightsRequest, dict]]): The request object. Request message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v21.services.ContentCreatorInsightsService.GenerateTrendingInsights]. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -417,7 +426,7 @@ async def generate_trending_insights( Returns: google.ads.googleads.v21.services.types.GenerateTrendingInsightsResponse: Response message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v21.services.ContentCreatorInsightsService.GenerateTrendingInsights]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/content_creator_insights_service/client.py b/google/ads/googleads/v21/services/services/content_creator_insights_service/client.py index 3dae2433d..cd46baca9 100644 --- a/google/ads/googleads/v21/services/services/content_creator_insights_service/client.py +++ b/google/ads/googleads/v21/services/services/content_creator_insights_service/client.py @@ -148,6 +148,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -319,14 +347,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ContentCreatorInsightsServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -334,7 +358,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -366,22 +390,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ContentCreatorInsightsServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -839,7 +859,7 @@ def generate_trending_insights( Args: request (Union[google.ads.googleads.v21.services.types.GenerateTrendingInsightsRequest, dict]): The request object. Request message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v21.services.ContentCreatorInsightsService.GenerateTrendingInsights]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -851,7 +871,7 @@ def generate_trending_insights( Returns: google.ads.googleads.v21.services.types.GenerateTrendingInsightsResponse: Response message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v21.services.ContentCreatorInsightsService.GenerateTrendingInsights]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/base.py b/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/base.py index b25a4c8d8..e31442533 100644 --- a/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/grpc.py b/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/grpc.py index f01044b6e..c3c0d2e3c 100644 --- a/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/grpc_asyncio.py index 567164011..3417afe81 100644 --- a/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/content_creator_insights_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_action_service/async_client.py b/google/ads/googleads/v21/services/services/conversion_action_service/async_client.py index daee8eb5d..223d72ec5 100644 --- a/google/ads/googleads/v21/services/services/conversion_action_service/async_client.py +++ b/google/ads/googleads/v21/services/services/conversion_action_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import conversion_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -119,7 +118,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionActionServiceAsyncClient: The constructed client. """ - return ConversionActionServiceClient.from_service_account_info.__func__(ConversionActionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionActionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionActionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -135,7 +139,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionActionServiceAsyncClient: The constructed client. """ - return ConversionActionServiceClient.from_service_account_file.__func__(ConversionActionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionActionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionActionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/conversion_action_service/client.py b/google/ads/googleads/v21/services/services/conversion_action_service/client.py index fefda40d3..ae91567e6 100644 --- a/google/ads/googleads/v21/services/services/conversion_action_service/client.py +++ b/google/ads/googleads/v21/services/services/conversion_action_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import conversion_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -357,14 +385,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionActionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -372,7 +396,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -404,22 +428,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionActionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/conversion_action_service/transports/base.py b/google/ads/googleads/v21/services/services/conversion_action_service/transports/base.py index c3d4c1cac..ec42b4e65 100644 --- a/google/ads/googleads/v21/services/services/conversion_action_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/conversion_action_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/conversion_action_service/transports/grpc.py b/google/ads/googleads/v21/services/services/conversion_action_service/transports/grpc.py index 9f411e812..93a634028 100644 --- a/google/ads/googleads/v21/services/services/conversion_action_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/conversion_action_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_action_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/conversion_action_service/transports/grpc_asyncio.py index 63cdd4182..5e4e39258 100644 --- a/google/ads/googleads/v21/services/services/conversion_action_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/conversion_action_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/async_client.py b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/async_client.py index 474c0ac35..f409f38af 100644 --- a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/async_client.py +++ b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( conversion_adjustment_upload_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionAdjustmentUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionAdjustmentUploadServiceAsyncClient: The constructed client. """ - return ConversionAdjustmentUploadServiceClient.from_service_account_info.__func__(ConversionAdjustmentUploadServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionAdjustmentUploadServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionAdjustmentUploadServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionAdjustmentUploadServiceAsyncClient: The constructed client. """ - return ConversionAdjustmentUploadServiceClient.from_service_account_file.__func__(ConversionAdjustmentUploadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionAdjustmentUploadServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionAdjustmentUploadServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/client.py b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/client.py index d4e7d0865..588d7785d 100644 --- a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/client.py +++ b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( conversion_adjustment_upload_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionAdjustmentUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -326,14 +354,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionAdjustmentUploadServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -341,7 +365,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -373,22 +397,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionAdjustmentUploadServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/base.py b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/base.py index 917b2a128..345930eb7 100644 --- a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/grpc.py b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/grpc.py index c6df73971..0249ec0ea 100644 --- a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/grpc_asyncio.py index 7afe8af7e..54c830f8b 100644 --- a/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/conversion_adjustment_upload_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/async_client.py b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/async_client.py index ecda0717f..1e9bd7e25 100644 --- a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/async_client.py +++ b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( conversion_custom_variable_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionCustomVariableServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionCustomVariableServiceAsyncClient: The constructed client. """ - return ConversionCustomVariableServiceClient.from_service_account_info.__func__(ConversionCustomVariableServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionCustomVariableServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionCustomVariableServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionCustomVariableServiceAsyncClient: The constructed client. """ - return ConversionCustomVariableServiceClient.from_service_account_file.__func__(ConversionCustomVariableServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionCustomVariableServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionCustomVariableServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/client.py b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/client.py index 9a8fb21d5..07f485fb5 100644 --- a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/client.py +++ b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( conversion_custom_variable_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionCustomVariableServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -361,14 +389,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionCustomVariableServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -376,7 +400,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -408,22 +432,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionCustomVariableServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/base.py b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/base.py index 76a06a163..609f884ff 100644 --- a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/grpc.py b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/grpc.py index 53be62a06..83301e628 100644 --- a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/grpc_asyncio.py index 8a9593772..104f3d31f 100644 --- a/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/conversion_custom_variable_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/async_client.py b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/async_client.py index ab49a479f..031949127 100644 --- a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/async_client.py +++ b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -134,7 +133,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionGoalCampaignConfigServiceAsyncClient: The constructed client. """ - return ConversionGoalCampaignConfigServiceClient.from_service_account_info.__func__(ConversionGoalCampaignConfigServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionGoalCampaignConfigServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionGoalCampaignConfigServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -150,7 +157,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionGoalCampaignConfigServiceAsyncClient: The constructed client. """ - return ConversionGoalCampaignConfigServiceClient.from_service_account_file.__func__(ConversionGoalCampaignConfigServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionGoalCampaignConfigServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionGoalCampaignConfigServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/client.py b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/client.py index 4fb7fea2f..8d8b87200 100644 --- a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/client.py +++ b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/client.py @@ -156,6 +156,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -387,14 +415,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionGoalCampaignConfigServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -402,7 +426,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -434,22 +458,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionGoalCampaignConfigServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/base.py b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/base.py index 4e229ea3b..8448c2fc1 100644 --- a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/grpc.py b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/grpc.py index 63db111a7..c0fdc6320 100644 --- a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/grpc_asyncio.py index b63bfe7fd..691339e7e 100644 --- a/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/conversion_goal_campaign_config_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_upload_service/async_client.py b/google/ads/googleads/v21/services/services/conversion_upload_service/async_client.py index 65af75e47..fd6b613a7 100644 --- a/google/ads/googleads/v21/services/services/conversion_upload_service/async_client.py +++ b/google/ads/googleads/v21/services/services/conversion_upload_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import conversion_upload_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionUploadServiceAsyncClient: The constructed client. """ - return ConversionUploadServiceClient.from_service_account_info.__func__(ConversionUploadServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionUploadServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionUploadServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionUploadServiceAsyncClient: The constructed client. """ - return ConversionUploadServiceClient.from_service_account_file.__func__(ConversionUploadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionUploadServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionUploadServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/conversion_upload_service/client.py b/google/ads/googleads/v21/services/services/conversion_upload_service/client.py index d2ed08f53..0674bf730 100644 --- a/google/ads/googleads/v21/services/services/conversion_upload_service/client.py +++ b/google/ads/googleads/v21/services/services/conversion_upload_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import conversion_upload_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -342,14 +370,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionUploadServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -357,7 +381,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -389,22 +413,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionUploadServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/conversion_upload_service/transports/base.py b/google/ads/googleads/v21/services/services/conversion_upload_service/transports/base.py index 96d434779..5b1beec7b 100644 --- a/google/ads/googleads/v21/services/services/conversion_upload_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/conversion_upload_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/conversion_upload_service/transports/grpc.py b/google/ads/googleads/v21/services/services/conversion_upload_service/transports/grpc.py index 625d0c2e6..c091ae223 100644 --- a/google/ads/googleads/v21/services/services/conversion_upload_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/conversion_upload_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_upload_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/conversion_upload_service/transports/grpc_asyncio.py index 6b8a684e7..c1d58ddba 100644 --- a/google/ads/googleads/v21/services/services/conversion_upload_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/conversion_upload_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_service/async_client.py b/google/ads/googleads/v21/services/services/conversion_value_rule_service/async_client.py index 8ed8e891c..76d76dff7 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_service/async_client.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( conversion_value_rule_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleServiceTransport, DEFAULT_CLIENT_INFO, @@ -141,7 +140,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionValueRuleServiceAsyncClient: The constructed client. """ - return ConversionValueRuleServiceClient.from_service_account_info.__func__(ConversionValueRuleServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionValueRuleServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionValueRuleServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -157,7 +161,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionValueRuleServiceAsyncClient: The constructed client. """ - return ConversionValueRuleServiceClient.from_service_account_file.__func__(ConversionValueRuleServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionValueRuleServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionValueRuleServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_service/client.py b/google/ads/googleads/v21/services/services/conversion_value_rule_service/client.py index 91ede53d6..f1fc18967 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_service/client.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( conversion_value_rule_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -418,14 +446,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionValueRuleServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -433,7 +457,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -465,22 +489,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionValueRuleServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/base.py b/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/base.py index 44ae0af47..de3d346dc 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/grpc.py b/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/grpc.py index 3d8945641..24b521ef4 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/grpc_asyncio.py index 12a97910d..3bc3c18de 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/async_client.py b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/async_client.py index 18edc04f3..3b019ad4a 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/async_client.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( conversion_value_rule_set_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -137,7 +136,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionValueRuleSetServiceAsyncClient: The constructed client. """ - return ConversionValueRuleSetServiceClient.from_service_account_info.__func__(ConversionValueRuleSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionValueRuleSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionValueRuleSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -153,7 +157,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionValueRuleSetServiceAsyncClient: The constructed client. """ - return ConversionValueRuleSetServiceClient.from_service_account_file.__func__(ConversionValueRuleSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionValueRuleSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionValueRuleSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/client.py b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/client.py index 148b5595b..3cf5b3ee0 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/client.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( conversion_value_rule_set_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -401,14 +429,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionValueRuleSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -416,7 +440,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -448,22 +472,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionValueRuleSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/base.py b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/base.py index 811dcc64c..ba077a931 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/grpc.py b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/grpc.py index cd9a6d75e..212c0d753 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/grpc_asyncio.py index 3c2ba0a43..ae9606332 100644 --- a/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/conversion_value_rule_set_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/custom_audience_service/async_client.py b/google/ads/googleads/v21/services/services/custom_audience_service/async_client.py index 4406cc80f..2edb73ae1 100644 --- a/google/ads/googleads/v21/services/services/custom_audience_service/async_client.py +++ b/google/ads/googleads/v21/services/services/custom_audience_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomAudienceServiceAsyncClient: The constructed client. """ - return CustomAudienceServiceClient.from_service_account_info.__func__(CustomAudienceServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomAudienceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomAudienceServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomAudienceServiceAsyncClient: The constructed client. """ - return CustomAudienceServiceClient.from_service_account_file.__func__(CustomAudienceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomAudienceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomAudienceServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/custom_audience_service/client.py b/google/ads/googleads/v21/services/services/custom_audience_service/client.py index 7ae1106f8..daaab9d50 100644 --- a/google/ads/googleads/v21/services/services/custom_audience_service/client.py +++ b/google/ads/googleads/v21/services/services/custom_audience_service/client.py @@ -145,6 +145,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -336,14 +364,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomAudienceServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -351,7 +375,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -383,22 +407,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomAudienceServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/custom_audience_service/transports/base.py b/google/ads/googleads/v21/services/services/custom_audience_service/transports/base.py index 2c4adf757..92e93f5e1 100644 --- a/google/ads/googleads/v21/services/services/custom_audience_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/custom_audience_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/custom_audience_service/transports/grpc.py b/google/ads/googleads/v21/services/services/custom_audience_service/transports/grpc.py index 323d794c4..1720ac4f6 100644 --- a/google/ads/googleads/v21/services/services/custom_audience_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/custom_audience_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/custom_audience_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/custom_audience_service/transports/grpc_asyncio.py index ac9bad198..771b0c80c 100644 --- a/google/ads/googleads/v21/services/services/custom_audience_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/custom_audience_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/async_client.py b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/async_client.py index c5c567c86..fcbb742fa 100644 --- a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/async_client.py +++ b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomConversionGoalServiceAsyncClient: The constructed client. """ - return CustomConversionGoalServiceClient.from_service_account_info.__func__(CustomConversionGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomConversionGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomConversionGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomConversionGoalServiceAsyncClient: The constructed client. """ - return CustomConversionGoalServiceClient.from_service_account_file.__func__(CustomConversionGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomConversionGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomConversionGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/client.py b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/client.py index a3feb9af6..c78815c18 100644 --- a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/client.py +++ b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -365,14 +393,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomConversionGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -380,7 +404,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -412,22 +436,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomConversionGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/base.py b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/base.py index 5b936c450..5ca808ff7 100644 --- a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/grpc.py b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/grpc.py index 6dd02fee4..3315ff380 100644 --- a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/grpc_asyncio.py index d0a96b2d5..581e9eb7d 100644 --- a/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/custom_conversion_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/custom_interest_service/async_client.py b/google/ads/googleads/v21/services/services/custom_interest_service/async_client.py index eb03faeee..4eefbe229 100644 --- a/google/ads/googleads/v21/services/services/custom_interest_service/async_client.py +++ b/google/ads/googleads/v21/services/services/custom_interest_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomInterestServiceAsyncClient: The constructed client. """ - return CustomInterestServiceClient.from_service_account_info.__func__(CustomInterestServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomInterestServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomInterestServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomInterestServiceAsyncClient: The constructed client. """ - return CustomInterestServiceClient.from_service_account_file.__func__(CustomInterestServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomInterestServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomInterestServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/custom_interest_service/client.py b/google/ads/googleads/v21/services/services/custom_interest_service/client.py index c5bd03c2a..f550b88c4 100644 --- a/google/ads/googleads/v21/services/services/custom_interest_service/client.py +++ b/google/ads/googleads/v21/services/services/custom_interest_service/client.py @@ -145,6 +145,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -336,14 +364,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomInterestServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -351,7 +375,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -383,22 +407,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomInterestServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/custom_interest_service/transports/base.py b/google/ads/googleads/v21/services/services/custom_interest_service/transports/base.py index d4eb37ec7..db82cb46a 100644 --- a/google/ads/googleads/v21/services/services/custom_interest_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/custom_interest_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/custom_interest_service/transports/grpc.py b/google/ads/googleads/v21/services/services/custom_interest_service/transports/grpc.py index ab836343c..abf3ea4ed 100644 --- a/google/ads/googleads/v21/services/services/custom_interest_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/custom_interest_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/custom_interest_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/custom_interest_service/transports/grpc_asyncio.py index 1902bcad0..cd0afcc43 100644 --- a/google/ads/googleads/v21/services/services/custom_interest_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/custom_interest_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_asset_service/async_client.py b/google/ads/googleads/v21/services/services/customer_asset_service/async_client.py index 34235b424..4a11eab93 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import customer_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import CustomerAssetServiceClient @@ -114,7 +113,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerAssetServiceAsyncClient: The constructed client. """ - return CustomerAssetServiceClient.from_service_account_info.__func__(CustomerAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +134,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerAssetServiceAsyncClient: The constructed client. """ - return CustomerAssetServiceClient.from_service_account_file.__func__(CustomerAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_asset_service/client.py b/google/ads/googleads/v21/services/services/customer_asset_service/client.py index 1ff38fdb2..d08558745 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import customer_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CustomerAssetServiceGrpcTransport from .transports.grpc_asyncio import CustomerAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -358,14 +386,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -373,7 +397,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -405,22 +429,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_asset_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_asset_service/transports/base.py index f61fa985c..7b2eee0d9 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_asset_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_asset_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_asset_service/transports/grpc.py index e4c2ad088..fba445508 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_asset_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_asset_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_asset_service/transports/grpc_asyncio.py index 68cd8c617..2a0b3f04c 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_asset_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_asset_set_service/async_client.py b/google/ads/googleads/v21/services/services/customer_asset_set_service/async_client.py index c3c5f19ba..2317a573f 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_set_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import customer_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerAssetSetServiceAsyncClient: The constructed client. """ - return CustomerAssetSetServiceClient.from_service_account_info.__func__(CustomerAssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerAssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerAssetSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerAssetSetServiceAsyncClient: The constructed client. """ - return CustomerAssetSetServiceClient.from_service_account_file.__func__(CustomerAssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerAssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerAssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_asset_set_service/client.py b/google/ads/googleads/v21/services/services/customer_asset_set_service/client.py index ed109aed7..99488e4b0 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_set_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import customer_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -379,14 +407,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerAssetSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -394,7 +418,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -426,22 +450,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerAssetSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/base.py index 19c875075..6102398f0 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/grpc.py index 660955db4..38acba88c 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/grpc_asyncio.py index 706427f60..b61a2f33c 100644 --- a/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_asset_set_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_client_link_service/async_client.py b/google/ads/googleads/v21/services/services/customer_client_link_service/async_client.py index 3038a9af5..d84e278e9 100644 --- a/google/ads/googleads/v21/services/services/customer_client_link_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_client_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerClientLinkServiceAsyncClient: The constructed client. """ - return CustomerClientLinkServiceClient.from_service_account_info.__func__(CustomerClientLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerClientLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerClientLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerClientLinkServiceAsyncClient: The constructed client. """ - return CustomerClientLinkServiceClient.from_service_account_file.__func__(CustomerClientLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerClientLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerClientLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_client_link_service/client.py b/google/ads/googleads/v21/services/services/customer_client_link_service/client.py index 08432b837..2c596a173 100644 --- a/google/ads/googleads/v21/services/services/customer_client_link_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_client_link_service/client.py @@ -142,6 +142,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -350,14 +378,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerClientLinkServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -365,7 +389,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -397,22 +421,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerClientLinkServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_client_link_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_client_link_service/transports/base.py index 3763ba7be..056fed901 100644 --- a/google/ads/googleads/v21/services/services/customer_client_link_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_client_link_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_client_link_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_client_link_service/transports/grpc.py index 6b59a6c3b..b67c3929c 100644 --- a/google/ads/googleads/v21/services/services/customer_client_link_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_client_link_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_client_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_client_link_service/transports/grpc_asyncio.py index 1445259eb..557247ceb 100644 --- a/google/ads/googleads/v21/services/services/customer_client_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_client_link_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/async_client.py b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/async_client.py index 560a6aa8d..4c05f89b5 100644 --- a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerConversionGoalServiceAsyncClient: The constructed client. """ - return CustomerConversionGoalServiceClient.from_service_account_info.__func__(CustomerConversionGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerConversionGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerConversionGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerConversionGoalServiceAsyncClient: The constructed client. """ - return CustomerConversionGoalServiceClient.from_service_account_file.__func__(CustomerConversionGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerConversionGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerConversionGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/client.py b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/client.py index bec566b34..0545a4e03 100644 --- a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -347,14 +375,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerConversionGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -362,7 +386,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -394,22 +418,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerConversionGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/base.py index cc62fcb01..3b9e224b0 100644 --- a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/grpc.py index 1c996fb71..fdb9a576e 100644 --- a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/grpc_asyncio.py index 9a77cbcde..411ea0821 100644 --- a/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_conversion_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_customizer_service/async_client.py b/google/ads/googleads/v21/services/services/customer_customizer_service/async_client.py index 00de5cda3..b03ed783d 100644 --- a/google/ads/googleads/v21/services/services/customer_customizer_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import customer_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerCustomizerServiceAsyncClient: The constructed client. """ - return CustomerCustomizerServiceClient.from_service_account_info.__func__(CustomerCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerCustomizerServiceAsyncClient: The constructed client. """ - return CustomerCustomizerServiceClient.from_service_account_file.__func__(CustomerCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerCustomizerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_customizer_service/client.py b/google/ads/googleads/v21/services/services/customer_customizer_service/client.py index 79647edcb..91f7fefcb 100644 --- a/google/ads/googleads/v21/services/services/customer_customizer_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_customizer_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import customer_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -364,14 +392,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -379,7 +403,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -411,22 +435,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_customizer_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_customizer_service/transports/base.py index 37fecbc45..8df8b363a 100644 --- a/google/ads/googleads/v21/services/services/customer_customizer_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_customizer_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_customizer_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_customizer_service/transports/grpc.py index 9a1e87fd3..44f5e5f36 100644 --- a/google/ads/googleads/v21/services/services/customer_customizer_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_customizer_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_customizer_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_customizer_service/transports/grpc_asyncio.py index 859cb94ca..5291ab18c 100644 --- a/google/ads/googleads/v21/services/services/customer_customizer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_customizer_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_label_service/async_client.py b/google/ads/googleads/v21/services/services/customer_label_service/async_client.py index 425f90715..9aec1041e 100644 --- a/google/ads/googleads/v21/services/services/customer_label_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import customer_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import CustomerLabelServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerLabelServiceAsyncClient: The constructed client. """ - return CustomerLabelServiceClient.from_service_account_info.__func__(CustomerLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerLabelServiceAsyncClient: The constructed client. """ - return CustomerLabelServiceClient.from_service_account_file.__func__(CustomerLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_label_service/client.py b/google/ads/googleads/v21/services/services/customer_label_service/client.py index 5ef783020..811e238ac 100644 --- a/google/ads/googleads/v21/services/services/customer_label_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import customer_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CustomerLabelServiceGrpcTransport from .transports.grpc_asyncio import CustomerLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -371,14 +399,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -386,7 +410,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -418,22 +442,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_label_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_label_service/transports/base.py index ec4bbfd76..367c10ada 100644 --- a/google/ads/googleads/v21/services/services/customer_label_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_label_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_label_service/transports/grpc.py index 38425a8c5..2a9c5a4cc 100644 --- a/google/ads/googleads/v21/services/services/customer_label_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_label_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_label_service/transports/grpc_asyncio.py index 854b3a9af..3ca6e3af7 100644 --- a/google/ads/googleads/v21/services/services/customer_label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/async_client.py b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/async_client.py index 040efb91c..54bdbea9e 100644 --- a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerLifecycleGoalServiceAsyncClient: The constructed client. """ - return CustomerLifecycleGoalServiceClient.from_service_account_info.__func__(CustomerLifecycleGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerLifecycleGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerLifecycleGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerLifecycleGoalServiceAsyncClient: The constructed client. """ - return CustomerLifecycleGoalServiceClient.from_service_account_file.__func__(CustomerLifecycleGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerLifecycleGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerLifecycleGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -337,7 +346,7 @@ async def configure_customer_lifecycle_goals( Args: request (Optional[Union[google.ads.googleads.v21.services.types.ConfigureCustomerLifecycleGoalsRequest, dict]]): The request object. Request message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v21.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. customer_id (:class:`str`): Required. The ID of the customer performing the upload. @@ -363,7 +372,7 @@ async def configure_customer_lifecycle_goals( Returns: google.ads.googleads.v21.services.types.ConfigureCustomerLifecycleGoalsResponse: Response message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v21.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/client.py b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/client.py index f28ca26c5..9b894ef20 100644 --- a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -347,14 +375,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerLifecycleGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -362,7 +386,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -394,22 +418,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerLifecycleGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -793,7 +813,7 @@ def configure_customer_lifecycle_goals( Args: request (Union[google.ads.googleads.v21.services.types.ConfigureCustomerLifecycleGoalsRequest, dict]): The request object. Request message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v21.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. customer_id (str): Required. The ID of the customer performing the upload. @@ -819,7 +839,7 @@ def configure_customer_lifecycle_goals( Returns: google.ads.googleads.v21.services.types.ConfigureCustomerLifecycleGoalsResponse: Response message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v21.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/base.py index 2017d9701..59a4e8e86 100644 --- a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/grpc.py index 632399191..0677acc3d 100644 --- a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/grpc_asyncio.py index 0ac6dd7d1..6a0119b77 100644 --- a/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_lifecycle_goal_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_manager_link_service/async_client.py b/google/ads/googleads/v21/services/services/customer_manager_link_service/async_client.py index f353438d9..5354cbf1f 100644 --- a/google/ads/googleads/v21/services/services/customer_manager_link_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_manager_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerManagerLinkServiceAsyncClient: The constructed client. """ - return CustomerManagerLinkServiceClient.from_service_account_info.__func__(CustomerManagerLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerManagerLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerManagerLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerManagerLinkServiceAsyncClient: The constructed client. """ - return CustomerManagerLinkServiceClient.from_service_account_file.__func__(CustomerManagerLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerManagerLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerManagerLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_manager_link_service/client.py b/google/ads/googleads/v21/services/services/customer_manager_link_service/client.py index 0da842c1d..d59c9444b 100644 --- a/google/ads/googleads/v21/services/services/customer_manager_link_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_manager_link_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -362,14 +390,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerManagerLinkServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -377,7 +401,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -409,22 +433,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerManagerLinkServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/base.py index 9523a2622..67c489d34 100644 --- a/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/grpc.py index b36bea703..acb78ca2e 100644 --- a/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/grpc_asyncio.py index fc852f981..3c2314798 100644 --- a/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_manager_link_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/async_client.py b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/async_client.py index deed301d7..39e280573 100644 --- a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( customer_negative_criterion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerNegativeCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerNegativeCriterionServiceAsyncClient: The constructed client. """ - return CustomerNegativeCriterionServiceClient.from_service_account_info.__func__(CustomerNegativeCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerNegativeCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerNegativeCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerNegativeCriterionServiceAsyncClient: The constructed client. """ - return CustomerNegativeCriterionServiceClient.from_service_account_file.__func__(CustomerNegativeCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerNegativeCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerNegativeCriterionServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/client.py b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/client.py index c1e9d9e8e..e482b02f9 100644 --- a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( customer_negative_criterion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerNegativeCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -364,14 +392,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerNegativeCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -379,7 +403,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -411,22 +435,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerNegativeCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/base.py index 117083e81..8774c4c8a 100644 --- a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/grpc.py index 310777c40..103ba89e3 100644 --- a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/grpc_asyncio.py index 78c82a3d9..8389f5435 100644 --- a/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_negative_criterion_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_service/async_client.py b/google/ads/googleads/v21/services/services/customer_service/async_client.py index b43e9ed09..df83b5bc7 100644 --- a/google/ads/googleads/v21/services/services/customer_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -114,7 +113,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerServiceAsyncClient: The constructed client. """ - return CustomerServiceClient.from_service_account_info.__func__(CustomerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(CustomerServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerServiceAsyncClient: The constructed client. """ - return CustomerServiceClient.from_service_account_file.__func__(CustomerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_service/client.py b/google/ads/googleads/v21/services/services/customer_service/client.py index d373c5f93..85964868b 100644 --- a/google/ads/googleads/v21/services/services/customer_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_service/client.py @@ -134,6 +134,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -340,14 +368,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = CustomerServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -355,7 +377,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -387,22 +409,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = CustomerServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_service/transports/base.py index 7b8e1e3db..5ae4b2db5 100644 --- a/google/ads/googleads/v21/services/services/customer_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_service/transports/grpc.py index b23f47e92..d43314704 100644 --- a/google/ads/googleads/v21/services/services/customer_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_service/transports/grpc_asyncio.py index fda017fde..fa44b3c82 100644 --- a/google/ads/googleads/v21/services/services/customer_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py index 724f4b4ec..1451b8488 100644 --- a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( customer_sk_ad_network_conversion_value_schema_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerSkAdNetworkConversionValueSchemaServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient: The constructed client. """ - return CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_info.__func__(CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +146,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient: The constructed client. """ - return CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_file.__func__(CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py index 4967dd25f..232ac8a81 100644 --- a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py @@ -52,7 +52,7 @@ from google.ads.googleads.v21.services.types import ( customer_sk_ad_network_conversion_value_schema_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerSkAdNetworkConversionValueSchemaServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +383,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +415,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py index 0993f243c..33c9c4580 100644 --- a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc.py index 251ca2c84..188bc21dc 100644 --- a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc_asyncio.py index 133175a12..472712bd1 100644 --- a/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/async_client.py b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/async_client.py index c399082d3..bf3d73204 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerUserAccessInvitationServiceAsyncClient: The constructed client. """ - return CustomerUserAccessInvitationServiceClient.from_service_account_info.__func__(CustomerUserAccessInvitationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerUserAccessInvitationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerUserAccessInvitationServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +147,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerUserAccessInvitationServiceAsyncClient: The constructed client. """ - return CustomerUserAccessInvitationServiceClient.from_service_account_file.__func__(CustomerUserAccessInvitationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerUserAccessInvitationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerUserAccessInvitationServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/client.py b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/client.py index bccf74a8b..8510e602c 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/client.py @@ -148,6 +148,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -339,14 +367,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerUserAccessInvitationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -354,7 +378,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -386,22 +410,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerUserAccessInvitationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/base.py index d6a613829..4160540bd 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/grpc.py index 01590653e..f2f5eb934 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/grpc.py @@ -170,9 +170,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -313,9 +314,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/grpc_asyncio.py index b1967a03b..4062dcfdd 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_invitation_service/transports/grpc_asyncio.py @@ -160,8 +160,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -216,9 +217,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_user_access_service/async_client.py b/google/ads/googleads/v21/services/services/customer_user_access_service/async_client.py index 1aa896a6c..158b3eb17 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerUserAccessServiceAsyncClient: The constructed client. """ - return CustomerUserAccessServiceClient.from_service_account_info.__func__(CustomerUserAccessServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerUserAccessServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerUserAccessServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerUserAccessServiceAsyncClient: The constructed client. """ - return CustomerUserAccessServiceClient.from_service_account_file.__func__(CustomerUserAccessServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerUserAccessServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerUserAccessServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customer_user_access_service/client.py b/google/ads/googleads/v21/services/services/customer_user_access_service/client.py index b7de28c49..a650d2812 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_service/client.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerUserAccessServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +374,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +406,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerUserAccessServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customer_user_access_service/transports/base.py b/google/ads/googleads/v21/services/services/customer_user_access_service/transports/base.py index c43b8a658..6728e12a0 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customer_user_access_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customer_user_access_service/transports/grpc.py index 3199d3828..ed7c9de50 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_service/transports/grpc.py @@ -165,9 +165,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -308,9 +309,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customer_user_access_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customer_user_access_service/transports/grpc_asyncio.py index a6abf9007..4ae45346e 100644 --- a/google/ads/googleads/v21/services/services/customer_user_access_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customer_user_access_service/transports/grpc_asyncio.py @@ -155,8 +155,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -211,9 +212,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customizer_attribute_service/async_client.py b/google/ads/googleads/v21/services/services/customizer_attribute_service/async_client.py index ae0195977..6797a8cde 100644 --- a/google/ads/googleads/v21/services/services/customizer_attribute_service/async_client.py +++ b/google/ads/googleads/v21/services/services/customizer_attribute_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import customizer_attribute_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomizerAttributeServiceTransport, DEFAULT_CLIENT_INFO, @@ -117,7 +116,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomizerAttributeServiceAsyncClient: The constructed client. """ - return CustomizerAttributeServiceClient.from_service_account_info.__func__(CustomizerAttributeServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomizerAttributeServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomizerAttributeServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -133,7 +137,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomizerAttributeServiceAsyncClient: The constructed client. """ - return CustomizerAttributeServiceClient.from_service_account_file.__func__(CustomizerAttributeServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomizerAttributeServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomizerAttributeServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/customizer_attribute_service/client.py b/google/ads/googleads/v21/services/services/customizer_attribute_service/client.py index 5cb983a1a..2dab22a48 100644 --- a/google/ads/googleads/v21/services/services/customizer_attribute_service/client.py +++ b/google/ads/googleads/v21/services/services/customizer_attribute_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import customizer_attribute_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomizerAttributeServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomizerAttributeServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +383,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +415,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomizerAttributeServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/base.py b/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/base.py index cfc7cd33a..a3bf11cdb 100644 --- a/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/grpc.py b/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/grpc.py index 1b4e8bb4f..985aa3aa9 100644 --- a/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/grpc.py @@ -164,9 +164,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -307,9 +308,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/grpc_asyncio.py index 43197fab1..5610d9406 100644 --- a/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/customizer_attribute_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/data_link_service/async_client.py b/google/ads/googleads/v21/services/services/data_link_service/async_client.py index b290a7b2b..22693deac 100644 --- a/google/ads/googleads/v21/services/services/data_link_service/async_client.py +++ b/google/ads/googleads/v21/services/services/data_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -113,7 +112,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: DataLinkServiceAsyncClient: The constructed client. """ - return DataLinkServiceClient.from_service_account_info.__func__(DataLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + DataLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(DataLinkServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -129,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: DataLinkServiceAsyncClient: The constructed client. """ - return DataLinkServiceClient.from_service_account_file.__func__(DataLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + DataLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + DataLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/data_link_service/client.py b/google/ads/googleads/v21/services/services/data_link_service/client.py index c84e31f01..7249cf2c9 100644 --- a/google/ads/googleads/v21/services/services/data_link_service/client.py +++ b/google/ads/googleads/v21/services/services/data_link_service/client.py @@ -139,6 +139,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -332,14 +360,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = DataLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -347,7 +369,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -379,22 +401,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = DataLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/data_link_service/transports/base.py b/google/ads/googleads/v21/services/services/data_link_service/transports/base.py index 50d08deec..453b88f9c 100644 --- a/google/ads/googleads/v21/services/services/data_link_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/data_link_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/data_link_service/transports/grpc.py b/google/ads/googleads/v21/services/services/data_link_service/transports/grpc.py index c6bcceb3e..9fa4c3112 100644 --- a/google/ads/googleads/v21/services/services/data_link_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/data_link_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/data_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/data_link_service/transports/grpc_asyncio.py index 8bb63c64c..b4def92ed 100644 --- a/google/ads/googleads/v21/services/services/data_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/data_link_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/experiment_arm_service/async_client.py b/google/ads/googleads/v21/services/services/experiment_arm_service/async_client.py index 2506b8e76..b69326326 100644 --- a/google/ads/googleads/v21/services/services/experiment_arm_service/async_client.py +++ b/google/ads/googleads/v21/services/services/experiment_arm_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import experiment_arm_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentArmServiceTransport, DEFAULT_CLIENT_INFO from .client import ExperimentArmServiceClient @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ExperimentArmServiceAsyncClient: The constructed client. """ - return ExperimentArmServiceClient.from_service_account_info.__func__(ExperimentArmServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ExperimentArmServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ExperimentArmServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ExperimentArmServiceAsyncClient: The constructed client. """ - return ExperimentArmServiceClient.from_service_account_file.__func__(ExperimentArmServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ExperimentArmServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ExperimentArmServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/experiment_arm_service/client.py b/google/ads/googleads/v21/services/services/experiment_arm_service/client.py index 7a4521908..2bae258ee 100644 --- a/google/ads/googleads/v21/services/services/experiment_arm_service/client.py +++ b/google/ads/googleads/v21/services/services/experiment_arm_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import experiment_arm_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentArmServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ExperimentArmServiceGrpcTransport from .transports.grpc_asyncio import ExperimentArmServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -379,14 +407,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ExperimentArmServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -394,7 +418,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -426,22 +450,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ExperimentArmServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/experiment_arm_service/transports/base.py b/google/ads/googleads/v21/services/services/experiment_arm_service/transports/base.py index facb8b795..fa721ee99 100644 --- a/google/ads/googleads/v21/services/services/experiment_arm_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/experiment_arm_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/experiment_arm_service/transports/grpc.py b/google/ads/googleads/v21/services/services/experiment_arm_service/transports/grpc.py index 78c748306..a1884e404 100644 --- a/google/ads/googleads/v21/services/services/experiment_arm_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/experiment_arm_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/experiment_arm_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/experiment_arm_service/transports/grpc_asyncio.py index 9c4f0083f..2f6f6eb68 100644 --- a/google/ads/googleads/v21/services/services/experiment_arm_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/experiment_arm_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/experiment_service/async_client.py b/google/ads/googleads/v21/services/services/experiment_service/async_client.py index 4af1fb54e..664238428 100644 --- a/google/ads/googleads/v21/services/services/experiment_service/async_client.py +++ b/google/ads/googleads/v21/services/services/experiment_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -35,10 +34,10 @@ from google.ads.googleads.v21.services.services.experiment_service import pagers from google.ads.googleads.v21.services.types import experiment_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO from .client import ExperimentServiceClient @@ -124,7 +123,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ExperimentServiceAsyncClient: The constructed client. """ - return ExperimentServiceClient.from_service_account_info.__func__(ExperimentServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ExperimentServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(ExperimentServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ExperimentServiceAsyncClient: The constructed client. """ - return ExperimentServiceClient.from_service_account_file.__func__(ExperimentServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ExperimentServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ExperimentServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/experiment_service/client.py b/google/ads/googleads/v21/services/services/experiment_service/client.py index ada60b8e6..7e23528d9 100644 --- a/google/ads/googleads/v21/services/services/experiment_service/client.py +++ b/google/ads/googleads/v21/services/services/experiment_service/client.py @@ -61,10 +61,10 @@ from google.ads.googleads.v21.services.services.experiment_service import pagers from google.ads.googleads.v21.services.types import experiment_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ExperimentServiceGrpcTransport from .transports.grpc_asyncio import ExperimentServiceGrpcAsyncIOTransport @@ -148,6 +148,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -379,14 +407,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = ExperimentServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -394,7 +416,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -426,22 +448,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ExperimentServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/experiment_service/pagers.py b/google/ads/googleads/v21/services/services/experiment_service/pagers.py index b1c71e6d6..773d7fbe3 100644 --- a/google/ads/googleads/v21/services/services/experiment_service/pagers.py +++ b/google/ads/googleads/v21/services/services/experiment_service/pagers.py @@ -37,7 +37,7 @@ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import experiment_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore class ListExperimentAsyncErrorsPager: diff --git a/google/ads/googleads/v21/services/services/experiment_service/transports/base.py b/google/ads/googleads/v21/services/services/experiment_service/transports/base.py index 46bf99289..3571cb410 100644 --- a/google/ads/googleads/v21/services/services/experiment_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/experiment_service/transports/base.py @@ -28,7 +28,7 @@ from google.ads.googleads.v21.services.types import experiment_service from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/experiment_service/transports/grpc.py b/google/ads/googleads/v21/services/services/experiment_service/transports/grpc.py index 728f9f0a7..904c17f6e 100644 --- a/google/ads/googleads/v21/services/services/experiment_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/experiment_service/transports/grpc.py @@ -32,7 +32,7 @@ from google.ads.googleads.v21.services.types import experiment_service from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO try: @@ -165,9 +165,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/experiment_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/experiment_service/transports/grpc_asyncio.py index 9892d3e27..2f367cbc3 100644 --- a/google/ads/googleads/v21/services/services/experiment_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/experiment_service/transports/grpc_asyncio.py @@ -33,7 +33,7 @@ from google.ads.googleads.v21.services.types import experiment_service from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO try: @@ -155,8 +155,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -211,9 +212,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/geo_target_constant_service/async_client.py b/google/ads/googleads/v21/services/services/geo_target_constant_service/async_client.py index f360aeee7..40c636c1c 100644 --- a/google/ads/googleads/v21/services/services/geo_target_constant_service/async_client.py +++ b/google/ads/googleads/v21/services/services/geo_target_constant_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -114,7 +113,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GeoTargetConstantServiceAsyncClient: The constructed client. """ - return GeoTargetConstantServiceClient.from_service_account_info.__func__(GeoTargetConstantServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GeoTargetConstantServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + GeoTargetConstantServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +134,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GeoTargetConstantServiceAsyncClient: The constructed client. """ - return GeoTargetConstantServiceClient.from_service_account_file.__func__(GeoTargetConstantServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GeoTargetConstantServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + GeoTargetConstantServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/geo_target_constant_service/client.py b/google/ads/googleads/v21/services/services/geo_target_constant_service/client.py index 380f462d5..28ffd9214 100644 --- a/google/ads/googleads/v21/services/services/geo_target_constant_service/client.py +++ b/google/ads/googleads/v21/services/services/geo_target_constant_service/client.py @@ -142,6 +142,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -328,14 +356,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + GeoTargetConstantServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -343,7 +367,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -375,22 +399,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + GeoTargetConstantServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/base.py b/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/base.py index 89a6efbb2..82fef354e 100644 --- a/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/grpc.py b/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/grpc.py index cf61d5520..a845c18f5 100644 --- a/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/grpc_asyncio.py index e0f60bc3b..2a915cfb8 100644 --- a/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/geo_target_constant_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/google_ads_field_service/async_client.py b/google/ads/googleads/v21/services/services/google_ads_field_service/async_client.py index 839a15883..9bd835add 100644 --- a/google/ads/googleads/v21/services/services/google_ads_field_service/async_client.py +++ b/google/ads/googleads/v21/services/services/google_ads_field_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GoogleAdsFieldServiceAsyncClient: The constructed client. """ - return GoogleAdsFieldServiceClient.from_service_account_info.__func__(GoogleAdsFieldServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GoogleAdsFieldServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + GoogleAdsFieldServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GoogleAdsFieldServiceAsyncClient: The constructed client. """ - return GoogleAdsFieldServiceClient.from_service_account_file.__func__(GoogleAdsFieldServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GoogleAdsFieldServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + GoogleAdsFieldServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/google_ads_field_service/client.py b/google/ads/googleads/v21/services/services/google_ads_field_service/client.py index 9eb747386..819c6f92c 100644 --- a/google/ads/googleads/v21/services/services/google_ads_field_service/client.py +++ b/google/ads/googleads/v21/services/services/google_ads_field_service/client.py @@ -139,6 +139,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -325,14 +353,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + GoogleAdsFieldServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -340,7 +364,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -372,22 +396,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + GoogleAdsFieldServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/google_ads_field_service/transports/base.py b/google/ads/googleads/v21/services/services/google_ads_field_service/transports/base.py index 434c801db..199430078 100644 --- a/google/ads/googleads/v21/services/services/google_ads_field_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/google_ads_field_service/transports/base.py @@ -67,9 +67,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -82,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/google_ads_field_service/transports/grpc.py b/google/ads/googleads/v21/services/services/google_ads_field_service/transports/grpc.py index 6602fa2b1..a3cf495a7 100644 --- a/google/ads/googleads/v21/services/services/google_ads_field_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/google_ads_field_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/google_ads_field_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/google_ads_field_service/transports/grpc_asyncio.py index fa24569be..cd6cba27a 100644 --- a/google/ads/googleads/v21/services/services/google_ads_field_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/google_ads_field_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/google_ads_service/async_client.py b/google/ads/googleads/v21/services/services/google_ads_service/async_client.py index 1c22ed3de..9a11f1b50 100644 --- a/google/ads/googleads/v21/services/services/google_ads_service/async_client.py +++ b/google/ads/googleads/v21/services/services/google_ads_service/async_client.py @@ -34,7 +34,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -44,8 +43,8 @@ from google.ads.googleads.v21.services.services.google_ads_service import pagers from google.ads.googleads.v21.services.types import google_ads_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import GoogleAdsServiceTransport, DEFAULT_CLIENT_INFO from .client import GoogleAdsServiceClient @@ -1083,7 +1082,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GoogleAdsServiceAsyncClient: The constructed client. """ - return GoogleAdsServiceClient.from_service_account_info.__func__(GoogleAdsServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GoogleAdsServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(GoogleAdsServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -1099,7 +1101,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GoogleAdsServiceAsyncClient: The constructed client. """ - return GoogleAdsServiceClient.from_service_account_file.__func__(GoogleAdsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GoogleAdsServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + GoogleAdsServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -1514,9 +1521,9 @@ async def mutate( methods. The only features it offers over calling those methods directly are: - - Atomic transactions - - Temp resource names (described below) - - Somewhat reduced latency over making a series of mutate calls + - Atomic transactions + - Temp resource names (described below) + - Somewhat reduced latency over making a series of mutate calls Note: Only resources that support atomic transactions are included, so this method can't replace all calls to individual @@ -1546,14 +1553,13 @@ async def mutate( Note: - - Resources must be created with a temp name before the name - can be reused. For example, the previous - CampaignBudget+Campaign example would fail if the mutate - order was reversed. - - Temp names are not remembered across requests. - - There's no limit to the number of temp names in a request. - - Each temp name must use a unique negative number, even if the - resource types differ. + - Resources must be created with a temp name before the name can + be reused. For example, the previous CampaignBudget+Campaign + example would fail if the mutate order was reversed. + - Temp names are not remembered across requests. + - There's no limit to the number of temp names in a request. + - Each temp name must use a unique negative number, even if the + resource types differ. Latency ------- diff --git a/google/ads/googleads/v21/services/services/google_ads_service/client.py b/google/ads/googleads/v21/services/services/google_ads_service/client.py index 19617be41..3851f4b1f 100644 --- a/google/ads/googleads/v21/services/services/google_ads_service/client.py +++ b/google/ads/googleads/v21/services/services/google_ads_service/client.py @@ -62,8 +62,8 @@ from google.ads.googleads.v21.services.services.google_ads_service import pagers from google.ads.googleads.v21.services.types import google_ads_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import GoogleAdsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import GoogleAdsServiceGrpcTransport from .transports.grpc_asyncio import GoogleAdsServiceGrpcAsyncIOTransport @@ -147,6 +147,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -4050,14 +4078,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = GoogleAdsServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -4065,7 +4087,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -4097,22 +4119,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = GoogleAdsServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -4693,9 +4709,9 @@ def mutate( methods. The only features it offers over calling those methods directly are: - - Atomic transactions - - Temp resource names (described below) - - Somewhat reduced latency over making a series of mutate calls + - Atomic transactions + - Temp resource names (described below) + - Somewhat reduced latency over making a series of mutate calls Note: Only resources that support atomic transactions are included, so this method can't replace all calls to individual @@ -4725,14 +4741,13 @@ def mutate( Note: - - Resources must be created with a temp name before the name - can be reused. For example, the previous - CampaignBudget+Campaign example would fail if the mutate - order was reversed. - - Temp names are not remembered across requests. - - There's no limit to the number of temp names in a request. - - Each temp name must use a unique negative number, even if the - resource types differ. + - Resources must be created with a temp name before the name can + be reused. For example, the previous CampaignBudget+Campaign + example would fail if the mutate order was reversed. + - Temp names are not remembered across requests. + - There's no limit to the number of temp names in a request. + - Each temp name must use a unique negative number, even if the + resource types differ. Latency ------- diff --git a/google/ads/googleads/v21/services/services/google_ads_service/transports/base.py b/google/ads/googleads/v21/services/services/google_ads_service/transports/base.py index c76c63756..a789bf167 100644 --- a/google/ads/googleads/v21/services/services/google_ads_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/google_ads_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/google_ads_service/transports/grpc.py b/google/ads/googleads/v21/services/services/google_ads_service/transports/grpc.py index c3572d634..a1b3c8d1e 100644 --- a/google/ads/googleads/v21/services/services/google_ads_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/google_ads_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -427,9 +429,9 @@ def mutate( methods. The only features it offers over calling those methods directly are: - - Atomic transactions - - Temp resource names (described below) - - Somewhat reduced latency over making a series of mutate calls + - Atomic transactions + - Temp resource names (described below) + - Somewhat reduced latency over making a series of mutate calls Note: Only resources that support atomic transactions are included, so this method can't replace all calls to individual @@ -459,14 +461,13 @@ def mutate( Note: - - Resources must be created with a temp name before the name - can be reused. For example, the previous - CampaignBudget+Campaign example would fail if the mutate - order was reversed. - - Temp names are not remembered across requests. - - There's no limit to the number of temp names in a request. - - Each temp name must use a unique negative number, even if the - resource types differ. + - Resources must be created with a temp name before the name can + be reused. For example, the previous CampaignBudget+Campaign + example would fail if the mutate order was reversed. + - Temp names are not remembered across requests. + - There's no limit to the number of temp names in a request. + - Each temp name must use a unique negative number, even if the + resource types differ. Latency ------- diff --git a/google/ads/googleads/v21/services/services/google_ads_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/google_ads_service/transports/grpc_asyncio.py index 500d83c09..b5d8ffef8 100644 --- a/google/ads/googleads/v21/services/services/google_ads_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/google_ads_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -433,9 +435,9 @@ def mutate( methods. The only features it offers over calling those methods directly are: - - Atomic transactions - - Temp resource names (described below) - - Somewhat reduced latency over making a series of mutate calls + - Atomic transactions + - Temp resource names (described below) + - Somewhat reduced latency over making a series of mutate calls Note: Only resources that support atomic transactions are included, so this method can't replace all calls to individual @@ -465,14 +467,13 @@ def mutate( Note: - - Resources must be created with a temp name before the name - can be reused. For example, the previous - CampaignBudget+Campaign example would fail if the mutate - order was reversed. - - Temp names are not remembered across requests. - - There's no limit to the number of temp names in a request. - - Each temp name must use a unique negative number, even if the - resource types differ. + - Resources must be created with a temp name before the name can + be reused. For example, the previous CampaignBudget+Campaign + example would fail if the mutate order was reversed. + - Temp names are not remembered across requests. + - There's no limit to the number of temp names in a request. + - Each temp name must use a unique negative number, even if the + resource types differ. Latency ------- diff --git a/google/ads/googleads/v21/services/services/identity_verification_service/async_client.py b/google/ads/googleads/v21/services/services/identity_verification_service/async_client.py index d247b4b6d..83e8bb040 100644 --- a/google/ads/googleads/v21/services/services/identity_verification_service/async_client.py +++ b/google/ads/googleads/v21/services/services/identity_verification_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -113,7 +112,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: IdentityVerificationServiceAsyncClient: The constructed client. """ - return IdentityVerificationServiceClient.from_service_account_info.__func__(IdentityVerificationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + IdentityVerificationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + IdentityVerificationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -129,7 +133,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: IdentityVerificationServiceAsyncClient: The constructed client. """ - return IdentityVerificationServiceClient.from_service_account_file.__func__(IdentityVerificationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + IdentityVerificationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + IdentityVerificationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -324,7 +333,7 @@ async def start_identity_verification( Args: request (Optional[Union[google.ads.googleads.v21.services.types.StartIdentityVerificationRequest, dict]]): The request object. Request message for - [IdentityVerificationService.StartIdentityVerification]. + [StartIdentityVerification][google.ads.googleads.v21.services.IdentityVerificationService.StartIdentityVerification]. customer_id (:class:`str`): Required. The Id of the customer for whom we are creating this verification. @@ -428,7 +437,7 @@ async def get_identity_verification( Args: request (Optional[Union[google.ads.googleads.v21.services.types.GetIdentityVerificationRequest, dict]]): The request object. Request message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v21.services.IdentityVerificationService.GetIdentityVerification]. customer_id (:class:`str`): Required. The ID of the customer for whom we are requesting verification @@ -448,7 +457,7 @@ async def get_identity_verification( Returns: google.ads.googleads.v21.services.types.GetIdentityVerificationResponse: Response message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v21.services.IdentityVerificationService.GetIdentityVerification]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/identity_verification_service/client.py b/google/ads/googleads/v21/services/services/identity_verification_service/client.py index 2c24771a5..22f76685e 100644 --- a/google/ads/googleads/v21/services/services/identity_verification_service/client.py +++ b/google/ads/googleads/v21/services/services/identity_verification_service/client.py @@ -145,6 +145,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -316,14 +344,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + IdentityVerificationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -331,7 +355,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -363,22 +387,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + IdentityVerificationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -758,7 +778,7 @@ def start_identity_verification( Args: request (Union[google.ads.googleads.v21.services.types.StartIdentityVerificationRequest, dict]): The request object. Request message for - [IdentityVerificationService.StartIdentityVerification]. + [StartIdentityVerification][google.ads.googleads.v21.services.IdentityVerificationService.StartIdentityVerification]. customer_id (str): Required. The Id of the customer for whom we are creating this verification. @@ -861,7 +881,7 @@ def get_identity_verification( Args: request (Union[google.ads.googleads.v21.services.types.GetIdentityVerificationRequest, dict]): The request object. Request message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v21.services.IdentityVerificationService.GetIdentityVerification]. customer_id (str): Required. The ID of the customer for whom we are requesting verification @@ -881,7 +901,7 @@ def get_identity_verification( Returns: google.ads.googleads.v21.services.types.GetIdentityVerificationResponse: Response message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v21.services.IdentityVerificationService.GetIdentityVerification]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/identity_verification_service/transports/base.py b/google/ads/googleads/v21/services/services/identity_verification_service/transports/base.py index de2b60d86..2cc3d0eec 100644 --- a/google/ads/googleads/v21/services/services/identity_verification_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/identity_verification_service/transports/base.py @@ -29,7 +29,7 @@ from google.ads.googleads.v21.services.types import ( identity_verification_service, ) -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -69,9 +69,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -84,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +100,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/identity_verification_service/transports/grpc.py b/google/ads/googleads/v21/services/services/identity_verification_service/transports/grpc.py index ff953e293..1e21202b6 100644 --- a/google/ads/googleads/v21/services/services/identity_verification_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/identity_verification_service/transports/grpc.py @@ -32,7 +32,7 @@ from google.ads.googleads.v21.services.types import ( identity_verification_service, ) -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import IdentityVerificationServiceTransport, DEFAULT_CLIENT_INFO try: @@ -167,9 +167,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -310,9 +311,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/identity_verification_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/identity_verification_service/transports/grpc_asyncio.py index 6c2d73c1a..4d39b9da5 100644 --- a/google/ads/googleads/v21/services/services/identity_verification_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/identity_verification_service/transports/grpc_asyncio.py @@ -33,7 +33,7 @@ from google.ads.googleads.v21.services.types import ( identity_verification_service, ) -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import IdentityVerificationServiceTransport, DEFAULT_CLIENT_INFO try: @@ -157,8 +157,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -213,9 +214,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/invoice_service/async_client.py b/google/ads/googleads/v21/services/services/invoice_service/async_client.py index 2987b7f05..b5098c7ea 100644 --- a/google/ads/googleads/v21/services/services/invoice_service/async_client.py +++ b/google/ads/googleads/v21/services/services/invoice_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -104,7 +103,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: InvoiceServiceAsyncClient: The constructed client. """ - return InvoiceServiceClient.from_service_account_info.__func__(InvoiceServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + InvoiceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(InvoiceServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -120,7 +122,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: InvoiceServiceAsyncClient: The constructed client. """ - return InvoiceServiceClient.from_service_account_file.__func__(InvoiceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + InvoiceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + InvoiceServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/invoice_service/client.py b/google/ads/googleads/v21/services/services/invoice_service/client.py index 99d3db846..97574a8c7 100644 --- a/google/ads/googleads/v21/services/services/invoice_service/client.py +++ b/google/ads/googleads/v21/services/services/invoice_service/client.py @@ -136,6 +136,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -327,14 +355,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = InvoiceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -342,7 +364,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -374,22 +396,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = InvoiceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/invoice_service/transports/base.py b/google/ads/googleads/v21/services/services/invoice_service/transports/base.py index 1994877c0..7f3135ed6 100644 --- a/google/ads/googleads/v21/services/services/invoice_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/invoice_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/invoice_service/transports/grpc.py b/google/ads/googleads/v21/services/services/invoice_service/transports/grpc.py index bbcb78a6c..427a2c06d 100644 --- a/google/ads/googleads/v21/services/services/invoice_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/invoice_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/invoice_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/invoice_service/transports/grpc_asyncio.py index af154afb8..602553241 100644 --- a/google/ads/googleads/v21/services/services/invoice_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/invoice_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/async_client.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/async_client.py index 8087ab292..4505951fa 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/async_client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( keyword_plan_ad_group_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -132,7 +131,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanAdGroupKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupKeywordServiceClient.from_service_account_info.__func__(KeywordPlanAdGroupKeywordServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanAdGroupKeywordServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanAdGroupKeywordServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -148,7 +152,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanAdGroupKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupKeywordServiceClient.from_service_account_file.__func__(KeywordPlanAdGroupKeywordServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanAdGroupKeywordServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanAdGroupKeywordServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/client.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/client.py index 60480acc4..e4663525e 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( keyword_plan_ad_group_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -162,6 +162,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -373,14 +401,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanAdGroupKeywordServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -388,7 +412,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -420,22 +444,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanAdGroupKeywordServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/base.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/base.py index 915db9b57..098a340e8 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/grpc.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/grpc.py index 4d4e746d0..c8427c9c3 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/grpc.py @@ -172,9 +172,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -315,9 +316,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/grpc_asyncio.py index 33a44f117..3381720b2 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_keyword_service/transports/grpc_asyncio.py @@ -162,8 +162,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -218,9 +219,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/async_client.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/async_client.py index 8f321eb26..f9afec2d3 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/async_client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( keyword_plan_ad_group_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanAdGroupServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupServiceClient.from_service_account_info.__func__(KeywordPlanAdGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanAdGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanAdGroupServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanAdGroupServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupServiceClient.from_service_account_file.__func__(KeywordPlanAdGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanAdGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanAdGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/client.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/client.py index 9ad98d6a8..117b172d6 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( keyword_plan_ad_group_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -366,14 +394,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanAdGroupServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -381,7 +405,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -413,22 +437,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanAdGroupServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/base.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/base.py index 2862929ca..f75473b9d 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/grpc.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/grpc.py index 574cfea84..d60fc0226 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/grpc_asyncio.py index 643411a20..b9be5f456 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_ad_group_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/async_client.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/async_client.py index dc3d86fa3..2f5718c0f 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/async_client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( keyword_plan_campaign_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -132,7 +131,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanCampaignKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignKeywordServiceClient.from_service_account_info.__func__(KeywordPlanCampaignKeywordServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanCampaignKeywordServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanCampaignKeywordServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -148,7 +152,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanCampaignKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignKeywordServiceClient.from_service_account_file.__func__(KeywordPlanCampaignKeywordServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanCampaignKeywordServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanCampaignKeywordServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/client.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/client.py index 0a35d722b..e4d842d59 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( keyword_plan_campaign_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -160,6 +160,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -371,14 +399,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanCampaignKeywordServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -386,7 +410,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -418,22 +442,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanCampaignKeywordServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/base.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/base.py index 3da394fe5..1aa159654 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/grpc.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/grpc.py index 92b8e3e3c..d6956dc89 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/grpc.py @@ -173,9 +173,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -316,9 +317,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/grpc_asyncio.py index 643808ce2..6419f80a5 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_keyword_service/transports/grpc_asyncio.py @@ -163,8 +163,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -219,9 +220,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/async_client.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/async_client.py index b8aa332ae..d784a23a2 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/async_client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( keyword_plan_campaign_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignServiceTransport, DEFAULT_CLIENT_INFO, @@ -137,7 +136,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanCampaignServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignServiceClient.from_service_account_info.__func__(KeywordPlanCampaignServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanCampaignServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanCampaignServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -153,7 +157,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanCampaignServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignServiceClient.from_service_account_file.__func__(KeywordPlanCampaignServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanCampaignServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanCampaignServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/client.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/client.py index 8330ae3db..02f5d4153 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( keyword_plan_campaign_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -396,14 +424,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanCampaignServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -411,7 +435,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -443,22 +467,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanCampaignServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/base.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/base.py index af4e8ec3c..8a004ab76 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/grpc.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/grpc.py index 1c2340ba8..7867f4e2a 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/grpc_asyncio.py index 2fb16af7f..161aa1cca 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_campaign_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/async_client.py b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/async_client.py index 0814f9187..e73ece338 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/async_client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanIdeaServiceAsyncClient: The constructed client. """ - return KeywordPlanIdeaServiceClient.from_service_account_info.__func__(KeywordPlanIdeaServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanIdeaServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanIdeaServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanIdeaServiceAsyncClient: The constructed client. """ - return KeywordPlanIdeaServiceClient.from_service_account_file.__func__(KeywordPlanIdeaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanIdeaServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanIdeaServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -603,7 +612,7 @@ async def generate_keyword_forecast_metrics( Args: request (Optional[Union[google.ads.googleads.v21.services.types.GenerateKeywordForecastMetricsRequest, dict]]): The request object. Request message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v21.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. campaign (:class:`google.ads.googleads.v21.services.types.CampaignToForecast`): Required. The campaign used in the forecast. @@ -622,7 +631,7 @@ async def generate_keyword_forecast_metrics( Returns: google.ads.googleads.v21.services.types.GenerateKeywordForecastMetricsResponse: Response message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v21.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/client.py b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/client.py index 331a95cf8..cf24a0e6a 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/client.py @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -322,14 +350,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanIdeaServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -337,7 +361,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -369,22 +393,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanIdeaServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -1039,7 +1059,7 @@ def generate_keyword_forecast_metrics( Args: request (Union[google.ads.googleads.v21.services.types.GenerateKeywordForecastMetricsRequest, dict]): The request object. Request message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v21.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. campaign (google.ads.googleads.v21.services.types.CampaignToForecast): Required. The campaign used in the forecast. @@ -1058,7 +1078,7 @@ def generate_keyword_forecast_metrics( Returns: google.ads.googleads.v21.services.types.GenerateKeywordForecastMetricsResponse: Response message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v21.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/base.py b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/base.py index a62476423..f28c831fb 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/grpc.py b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/grpc.py index 798e41a6e..3e362da59 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/grpc_asyncio.py index 6d226836b..76c9e8d2a 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_idea_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_service/async_client.py b/google/ads/googleads/v21/services/services/keyword_plan_service/async_client.py index 5e5ef9071..b6881798a 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_service/async_client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import keyword_plan_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import KeywordPlanServiceTransport, DEFAULT_CLIENT_INFO from .client import KeywordPlanServiceClient @@ -110,7 +109,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanServiceAsyncClient: The constructed client. """ - return KeywordPlanServiceClient.from_service_account_info.__func__(KeywordPlanServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -126,7 +130,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanServiceAsyncClient: The constructed client. """ - return KeywordPlanServiceClient.from_service_account_file.__func__(KeywordPlanServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/keyword_plan_service/client.py b/google/ads/googleads/v21/services/services/keyword_plan_service/client.py index 5da2068a9..aae8403b2 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_service/client.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import keyword_plan_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import KeywordPlanServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import KeywordPlanServiceGrpcTransport from .transports.grpc_asyncio import KeywordPlanServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = KeywordPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = KeywordPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_service/transports/base.py b/google/ads/googleads/v21/services/services/keyword_plan_service/transports/base.py index 972276627..c16a4f4e4 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/keyword_plan_service/transports/grpc.py b/google/ads/googleads/v21/services/services/keyword_plan_service/transports/grpc.py index f78d762d0..cefab0a74 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_plan_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/keyword_plan_service/transports/grpc_asyncio.py index 1cef1829b..1c12ef2fb 100644 --- a/google/ads/googleads/v21/services/services/keyword_plan_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/keyword_plan_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/async_client.py b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/async_client.py index 2ed058580..2ec582d2a 100644 --- a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/async_client.py +++ b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordThemeConstantServiceAsyncClient: The constructed client. """ - return KeywordThemeConstantServiceClient.from_service_account_info.__func__(KeywordThemeConstantServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordThemeConstantServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordThemeConstantServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordThemeConstantServiceAsyncClient: The constructed client. """ - return KeywordThemeConstantServiceClient.from_service_account_file.__func__(KeywordThemeConstantServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordThemeConstantServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordThemeConstantServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/client.py b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/client.py index fae8e1c10..02e8dfcb3 100644 --- a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/client.py +++ b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordThemeConstantServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +374,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +406,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordThemeConstantServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/base.py b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/base.py index 01eb0c635..072a6c953 100644 --- a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/grpc.py b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/grpc.py index 0cc0d7b95..a338cc2ce 100644 --- a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/grpc_asyncio.py index 4fa705633..1ef733e28 100644 --- a/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/keyword_theme_constant_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/label_service/async_client.py b/google/ads/googleads/v21/services/services/label_service/async_client.py index 85782cd63..03bfd96d9 100644 --- a/google/ads/googleads/v21/services/services/label_service/async_client.py +++ b/google/ads/googleads/v21/services/services/label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import LabelServiceTransport, DEFAULT_CLIENT_INFO from .client import LabelServiceClient @@ -100,7 +99,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: LabelServiceAsyncClient: The constructed client. """ - return LabelServiceClient.from_service_account_info.__func__(LabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + LabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(LabelServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -116,7 +118,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LabelServiceAsyncClient: The constructed client. """ - return LabelServiceClient.from_service_account_file.__func__(LabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + LabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(LabelServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/label_service/client.py b/google/ads/googleads/v21/services/services/label_service/client.py index 58ce404e4..ee488f1fc 100644 --- a/google/ads/googleads/v21/services/services/label_service/client.py +++ b/google/ads/googleads/v21/services/services/label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import LabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import LabelServiceGrpcTransport from .transports.grpc_asyncio import LabelServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -334,14 +362,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = LabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -349,7 +371,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -381,22 +403,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = LabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/label_service/transports/base.py b/google/ads/googleads/v21/services/services/label_service/transports/base.py index c5b46f429..2270454ab 100644 --- a/google/ads/googleads/v21/services/services/label_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/label_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/label_service/transports/grpc.py b/google/ads/googleads/v21/services/services/label_service/transports/grpc.py index 66bbef5ea..c8cf0a5a8 100644 --- a/google/ads/googleads/v21/services/services/label_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/label_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/label_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/label_service/transports/grpc_asyncio.py index 6a3c03a3b..f7709a3cf 100644 --- a/google/ads/googleads/v21/services/services/label_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/label_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/local_services_lead_service/async_client.py b/google/ads/googleads/v21/services/services/local_services_lead_service/async_client.py index e1a93f1ed..5e2038d6c 100644 --- a/google/ads/googleads/v21/services/services/local_services_lead_service/async_client.py +++ b/google/ads/googleads/v21/services/services/local_services_lead_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -116,7 +115,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: LocalServicesLeadServiceAsyncClient: The constructed client. """ - return LocalServicesLeadServiceClient.from_service_account_info.__func__(LocalServicesLeadServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + LocalServicesLeadServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + LocalServicesLeadServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,7 +136,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LocalServicesLeadServiceAsyncClient: The constructed client. """ - return LocalServicesLeadServiceClient.from_service_account_file.__func__(LocalServicesLeadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + LocalServicesLeadServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + LocalServicesLeadServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/local_services_lead_service/client.py b/google/ads/googleads/v21/services/services/local_services_lead_service/client.py index b1386dd24..67d9e88ea 100644 --- a/google/ads/googleads/v21/services/services/local_services_lead_service/client.py +++ b/google/ads/googleads/v21/services/services/local_services_lead_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -345,14 +373,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + LocalServicesLeadServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -360,7 +384,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -392,22 +416,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + LocalServicesLeadServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/local_services_lead_service/transports/base.py b/google/ads/googleads/v21/services/services/local_services_lead_service/transports/base.py index 7df4b06e0..b690474b5 100644 --- a/google/ads/googleads/v21/services/services/local_services_lead_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/local_services_lead_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/local_services_lead_service/transports/grpc.py b/google/ads/googleads/v21/services/services/local_services_lead_service/transports/grpc.py index 743e73dde..6c35268a1 100644 --- a/google/ads/googleads/v21/services/services/local_services_lead_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/local_services_lead_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/local_services_lead_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/local_services_lead_service/transports/grpc_asyncio.py index db7520ae5..464ffe0a8 100644 --- a/google/ads/googleads/v21/services/services/local_services_lead_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/local_services_lead_service/transports/grpc_asyncio.py @@ -155,8 +155,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -211,9 +212,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/offline_user_data_job_service/async_client.py b/google/ads/googleads/v21/services/services/offline_user_data_job_service/async_client.py index ac0e646d5..779d80720 100644 --- a/google/ads/googleads/v21/services/services/offline_user_data_job_service/async_client.py +++ b/google/ads/googleads/v21/services/services/offline_user_data_job_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,10 +36,10 @@ from google.ads.googleads.v21.services.types import ( offline_user_data_job_service, ) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( OfflineUserDataJobServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: OfflineUserDataJobServiceAsyncClient: The constructed client. """ - return OfflineUserDataJobServiceClient.from_service_account_info.__func__(OfflineUserDataJobServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + OfflineUserDataJobServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + OfflineUserDataJobServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: OfflineUserDataJobServiceAsyncClient: The constructed client. """ - return OfflineUserDataJobServiceClient.from_service_account_file.__func__(OfflineUserDataJobServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + OfflineUserDataJobServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + OfflineUserDataJobServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/offline_user_data_job_service/client.py b/google/ads/googleads/v21/services/services/offline_user_data_job_service/client.py index e30ae7a6e..0b2dfc73e 100644 --- a/google/ads/googleads/v21/services/services/offline_user_data_job_service/client.py +++ b/google/ads/googleads/v21/services/services/offline_user_data_job_service/client.py @@ -63,10 +63,10 @@ from google.ads.googleads.v21.services.types import ( offline_user_data_job_service, ) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( OfflineUserDataJobServiceTransport, DEFAULT_CLIENT_INFO, @@ -159,6 +159,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -350,14 +378,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + OfflineUserDataJobServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -365,7 +389,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -397,22 +421,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + OfflineUserDataJobServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/base.py b/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/base.py index 3b480129e..1bfa61202 100644 --- a/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/base.py @@ -69,9 +69,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -84,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +100,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/grpc.py b/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/grpc.py index f0dcd01d0..e25f991b9 100644 --- a/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/grpc.py @@ -168,9 +168,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/grpc_asyncio.py index 6f59ce1ab..029f0d3d7 100644 --- a/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/offline_user_data_job_service/transports/grpc_asyncio.py @@ -158,8 +158,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -214,9 +215,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/payments_account_service/async_client.py b/google/ads/googleads/v21/services/services/payments_account_service/async_client.py index 43a28b81a..21c1cd8ed 100644 --- a/google/ads/googleads/v21/services/services/payments_account_service/async_client.py +++ b/google/ads/googleads/v21/services/services/payments_account_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: PaymentsAccountServiceAsyncClient: The constructed client. """ - return PaymentsAccountServiceClient.from_service_account_info.__func__(PaymentsAccountServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + PaymentsAccountServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + PaymentsAccountServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: PaymentsAccountServiceAsyncClient: The constructed client. """ - return PaymentsAccountServiceClient.from_service_account_file.__func__(PaymentsAccountServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + PaymentsAccountServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + PaymentsAccountServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/payments_account_service/client.py b/google/ads/googleads/v21/services/services/payments_account_service/client.py index 3e5276b3b..08a02170e 100644 --- a/google/ads/googleads/v21/services/services/payments_account_service/client.py +++ b/google/ads/googleads/v21/services/services/payments_account_service/client.py @@ -140,6 +140,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -346,14 +374,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + PaymentsAccountServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -361,7 +385,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -393,22 +417,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + PaymentsAccountServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/payments_account_service/transports/base.py b/google/ads/googleads/v21/services/services/payments_account_service/transports/base.py index b8803bbc9..9e714fbce 100644 --- a/google/ads/googleads/v21/services/services/payments_account_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/payments_account_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/payments_account_service/transports/grpc.py b/google/ads/googleads/v21/services/services/payments_account_service/transports/grpc.py index 89ec36e1b..38d82bc88 100644 --- a/google/ads/googleads/v21/services/services/payments_account_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/payments_account_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/payments_account_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/payments_account_service/transports/grpc_asyncio.py index 3b3e08cef..92b74016b 100644 --- a/google/ads/googleads/v21/services/services/payments_account_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/payments_account_service/transports/grpc_asyncio.py @@ -155,8 +155,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -211,9 +212,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/product_link_invitation_service/async_client.py b/google/ads/googleads/v21/services/services/product_link_invitation_service/async_client.py index 14731236f..641d53623 100644 --- a/google/ads/googleads/v21/services/services/product_link_invitation_service/async_client.py +++ b/google/ads/googleads/v21/services/services/product_link_invitation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -132,7 +131,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ProductLinkInvitationServiceAsyncClient: The constructed client. """ - return ProductLinkInvitationServiceClient.from_service_account_info.__func__(ProductLinkInvitationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ProductLinkInvitationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ProductLinkInvitationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -148,7 +152,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductLinkInvitationServiceAsyncClient: The constructed client. """ - return ProductLinkInvitationServiceClient.from_service_account_file.__func__(ProductLinkInvitationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ProductLinkInvitationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ProductLinkInvitationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -570,7 +579,7 @@ async def remove_product_link_invitation( Args: request (Optional[Union[google.ads.googleads.v21.services.types.RemoveProductLinkInvitationRequest, dict]]): The request object. Request message for - [ProductLinkinvitationService.RemoveProductLinkInvitation][]. + [ProductLinkInvitationService.RemoveProductLinkInvitation][google.ads.googleads.v21.services.ProductLinkInvitationService.RemoveProductLinkInvitation]. customer_id (:class:`str`): Required. The ID of the product link invitation being removed. @@ -582,7 +591,7 @@ async def remove_product_link_invitation( Required. The resource name of the product link invitation being removed. expected, in this format: - ```` + ``customers/{customer_id}/productLinkInvitations/{product_link_invitation_id}`` This corresponds to the ``resource_name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v21/services/services/product_link_invitation_service/client.py b/google/ads/googleads/v21/services/services/product_link_invitation_service/client.py index f2e4ef2ea..6e98289ce 100644 --- a/google/ads/googleads/v21/services/services/product_link_invitation_service/client.py +++ b/google/ads/googleads/v21/services/services/product_link_invitation_service/client.py @@ -152,6 +152,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -358,14 +386,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ProductLinkInvitationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -373,7 +397,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -405,22 +429,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ProductLinkInvitationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -1027,7 +1047,7 @@ def remove_product_link_invitation( Args: request (Union[google.ads.googleads.v21.services.types.RemoveProductLinkInvitationRequest, dict]): The request object. Request message for - [ProductLinkinvitationService.RemoveProductLinkInvitation][]. + [ProductLinkInvitationService.RemoveProductLinkInvitation][google.ads.googleads.v21.services.ProductLinkInvitationService.RemoveProductLinkInvitation]. customer_id (str): Required. The ID of the product link invitation being removed. @@ -1039,7 +1059,7 @@ def remove_product_link_invitation( Required. The resource name of the product link invitation being removed. expected, in this format: - ```` + ``customers/{customer_id}/productLinkInvitations/{product_link_invitation_id}`` This corresponds to the ``resource_name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/base.py b/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/base.py index dcf7be814..26d5903c4 100644 --- a/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/grpc.py b/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/grpc.py index a4ca270c3..a605324b0 100644 --- a/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/grpc.py @@ -167,9 +167,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -310,9 +311,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/grpc_asyncio.py index 6978a096b..323a71ce7 100644 --- a/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/product_link_invitation_service/transports/grpc_asyncio.py @@ -157,8 +157,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -213,9 +214,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/product_link_service/async_client.py b/google/ads/googleads/v21/services/services/product_link_service/async_client.py index 3d1bb17a6..ed4251cb4 100644 --- a/google/ads/googleads/v21/services/services/product_link_service/async_client.py +++ b/google/ads/googleads/v21/services/services/product_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ProductLinkServiceAsyncClient: The constructed client. """ - return ProductLinkServiceClient.from_service_account_info.__func__(ProductLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ProductLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ProductLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductLinkServiceAsyncClient: The constructed client. """ - return ProductLinkServiceClient.from_service_account_file.__func__(ProductLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ProductLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ProductLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/product_link_service/client.py b/google/ads/googleads/v21/services/services/product_link_service/client.py index 913fddfc6..381f2d316 100644 --- a/google/ads/googleads/v21/services/services/product_link_service/client.py +++ b/google/ads/googleads/v21/services/services/product_link_service/client.py @@ -138,6 +138,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = ProductLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +381,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +413,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ProductLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/product_link_service/transports/base.py b/google/ads/googleads/v21/services/services/product_link_service/transports/base.py index 0ec32740b..7ba0bdb70 100644 --- a/google/ads/googleads/v21/services/services/product_link_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/product_link_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/product_link_service/transports/grpc.py b/google/ads/googleads/v21/services/services/product_link_service/transports/grpc.py index b5737fc23..50060562f 100644 --- a/google/ads/googleads/v21/services/services/product_link_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/product_link_service/transports/grpc.py @@ -163,9 +163,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -306,9 +307,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/product_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/product_link_service/transports/grpc_asyncio.py index 7ae8b9a79..3ed1e51c1 100644 --- a/google/ads/googleads/v21/services/services/product_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/product_link_service/transports/grpc_asyncio.py @@ -153,8 +153,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -209,9 +210,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/reach_plan_service/async_client.py b/google/ads/googleads/v21/services/services/reach_plan_service/async_client.py index a5cbb1b6b..720a8d461 100644 --- a/google/ads/googleads/v21/services/services/reach_plan_service/async_client.py +++ b/google/ads/googleads/v21/services/services/reach_plan_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -109,7 +108,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ReachPlanServiceAsyncClient: The constructed client. """ - return ReachPlanServiceClient.from_service_account_info.__func__(ReachPlanServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ReachPlanServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(ReachPlanServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -125,7 +127,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ReachPlanServiceAsyncClient: The constructed client. """ - return ReachPlanServiceClient.from_service_account_file.__func__(ReachPlanServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ReachPlanServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ReachPlanServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -664,9 +671,9 @@ async def list_plannable_user_lists( status. User lists may not be plannable for a number of reasons, including: - - They are less than 10 days old. - - They have a membership lifespan that is less than 30 days - - They have less than 10,000 or more than 700,000 users. + - They are less than 10 days old. + - They have a membership lifespan that is less than 30 days + - They have less than 10,000 or more than 700,000 users. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `FieldError <>`__ `HeaderError <>`__ diff --git a/google/ads/googleads/v21/services/services/reach_plan_service/client.py b/google/ads/googleads/v21/services/services/reach_plan_service/client.py index b6640083a..36860a29b 100644 --- a/google/ads/googleads/v21/services/services/reach_plan_service/client.py +++ b/google/ads/googleads/v21/services/services/reach_plan_service/client.py @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -320,14 +348,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = ReachPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -335,7 +357,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -367,22 +389,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ReachPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -1092,9 +1108,9 @@ def list_plannable_user_lists( status. User lists may not be plannable for a number of reasons, including: - - They are less than 10 days old. - - They have a membership lifespan that is less than 30 days - - They have less than 10,000 or more than 700,000 users. + - They are less than 10 days old. + - They have a membership lifespan that is less than 30 days + - They have less than 10,000 or more than 700,000 users. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `FieldError <>`__ `HeaderError <>`__ diff --git a/google/ads/googleads/v21/services/services/reach_plan_service/transports/base.py b/google/ads/googleads/v21/services/services/reach_plan_service/transports/base.py index 90cc58c54..7a4117e89 100644 --- a/google/ads/googleads/v21/services/services/reach_plan_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/reach_plan_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/reach_plan_service/transports/grpc.py b/google/ads/googleads/v21/services/services/reach_plan_service/transports/grpc.py index 3b4294f0c..96848a978 100644 --- a/google/ads/googleads/v21/services/services/reach_plan_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/reach_plan_service/transports/grpc.py @@ -167,9 +167,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -310,9 +311,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -501,9 +503,9 @@ def list_plannable_user_lists( status. User lists may not be plannable for a number of reasons, including: - - They are less than 10 days old. - - They have a membership lifespan that is less than 30 days - - They have less than 10,000 or more than 700,000 users. + - They are less than 10 days old. + - They have a membership lifespan that is less than 30 days + - They have less than 10,000 or more than 700,000 users. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `FieldError <>`__ `HeaderError <>`__ diff --git a/google/ads/googleads/v21/services/services/reach_plan_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/reach_plan_service/transports/grpc_asyncio.py index eff9986ee..1a6b7662f 100644 --- a/google/ads/googleads/v21/services/services/reach_plan_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/reach_plan_service/transports/grpc_asyncio.py @@ -157,8 +157,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -213,9 +214,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -507,9 +509,9 @@ def list_plannable_user_lists( status. User lists may not be plannable for a number of reasons, including: - - They are less than 10 days old. - - They have a membership lifespan that is less than 30 days - - They have less than 10,000 or more than 700,000 users. + - They are less than 10 days old. + - They have a membership lifespan that is less than 30 days + - They have less than 10,000 or more than 700,000 users. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `FieldError <>`__ `HeaderError <>`__ diff --git a/google/ads/googleads/v21/services/services/recommendation_service/async_client.py b/google/ads/googleads/v21/services/services/recommendation_service/async_client.py index da7476cc0..142c529f0 100644 --- a/google/ads/googleads/v21/services/services/recommendation_service/async_client.py +++ b/google/ads/googleads/v21/services/services/recommendation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -38,7 +37,7 @@ ) from google.ads.googleads.v21.enums.types import recommendation_type from google.ads.googleads.v21.services.types import recommendation_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO from .client import RecommendationServiceClient @@ -142,7 +141,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: RecommendationServiceAsyncClient: The constructed client. """ - return RecommendationServiceClient.from_service_account_info.__func__(RecommendationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + RecommendationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + RecommendationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -158,7 +162,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RecommendationServiceAsyncClient: The constructed client. """ - return RecommendationServiceClient.from_service_account_file.__func__(RecommendationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + RecommendationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + RecommendationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/recommendation_service/client.py b/google/ads/googleads/v21/services/services/recommendation_service/client.py index fa50cca92..bd6951c14 100644 --- a/google/ads/googleads/v21/services/services/recommendation_service/client.py +++ b/google/ads/googleads/v21/services/services/recommendation_service/client.py @@ -64,7 +64,7 @@ ) from google.ads.googleads.v21.enums.types import recommendation_type from google.ads.googleads.v21.services.types import recommendation_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import RecommendationServiceGrpcTransport from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport @@ -150,6 +150,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -459,14 +487,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + RecommendationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -474,7 +498,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -506,22 +530,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + RecommendationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/recommendation_service/transports/base.py b/google/ads/googleads/v21/services/services/recommendation_service/transports/base.py index 5c29196b9..53eb44bde 100644 --- a/google/ads/googleads/v21/services/services/recommendation_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/recommendation_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/recommendation_service/transports/grpc.py b/google/ads/googleads/v21/services/services/recommendation_service/transports/grpc.py index a154fc405..e3aa23df0 100644 --- a/google/ads/googleads/v21/services/services/recommendation_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/recommendation_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/recommendation_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/recommendation_service/transports/grpc_asyncio.py index 45df8ccc1..107ccdd83 100644 --- a/google/ads/googleads/v21/services/services/recommendation_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/recommendation_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/recommendation_subscription_service/async_client.py b/google/ads/googleads/v21/services/services/recommendation_subscription_service/async_client.py index a958faee6..bdd02020e 100644 --- a/google/ads/googleads/v21/services/services/recommendation_subscription_service/async_client.py +++ b/google/ads/googleads/v21/services/services/recommendation_subscription_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( recommendation_subscription_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RecommendationSubscriptionServiceTransport, DEFAULT_CLIENT_INFO, @@ -121,7 +120,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: RecommendationSubscriptionServiceAsyncClient: The constructed client. """ - return RecommendationSubscriptionServiceClient.from_service_account_info.__func__(RecommendationSubscriptionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + RecommendationSubscriptionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + RecommendationSubscriptionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -137,7 +141,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RecommendationSubscriptionServiceAsyncClient: The constructed client. """ - return RecommendationSubscriptionServiceClient.from_service_account_file.__func__(RecommendationSubscriptionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + RecommendationSubscriptionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + RecommendationSubscriptionServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file @@ -333,13 +345,14 @@ async def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Args: request (Optional[Union[google.ads.googleads.v21.services.types.MutateRecommendationSubscriptionRequest, dict]]): The request object. Request message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v21.services.RecommendationSubscriptionService.MutateRecommendationSubscription] customer_id (:class:`str`): Required. The ID of the subscribing customer. @@ -365,7 +378,7 @@ async def mutate_recommendation_subscription( Returns: google.ads.googleads.v21.services.types.MutateRecommendationSubscriptionResponse: Response message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v21.services.RecommendationSubscriptionService.MutateRecommendationSubscription] """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/recommendation_subscription_service/client.py b/google/ads/googleads/v21/services/services/recommendation_subscription_service/client.py index 5fb73cbb2..c757e1743 100644 --- a/google/ads/googleads/v21/services/services/recommendation_subscription_service/client.py +++ b/google/ads/googleads/v21/services/services/recommendation_subscription_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( recommendation_subscription_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RecommendationSubscriptionServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -346,14 +374,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + RecommendationSubscriptionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -361,7 +385,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -393,22 +417,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + RecommendationSubscriptionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -793,13 +813,14 @@ def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Args: request (Union[google.ads.googleads.v21.services.types.MutateRecommendationSubscriptionRequest, dict]): The request object. Request message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v21.services.RecommendationSubscriptionService.MutateRecommendationSubscription] customer_id (str): Required. The ID of the subscribing customer. @@ -825,7 +846,7 @@ def mutate_recommendation_subscription( Returns: google.ads.googleads.v21.services.types.MutateRecommendationSubscriptionResponse: Response message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v21.services.RecommendationSubscriptionService.MutateRecommendationSubscription] """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/base.py b/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/base.py index b50cddd7e..fd7d0893d 100644 --- a/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/grpc.py b/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/grpc.py index 15781eaba..cb17521e0 100644 --- a/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -363,7 +365,8 @@ def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Returns: diff --git a/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/grpc_asyncio.py index d54b6e11c..52c4c7730 100644 --- a/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/recommendation_subscription_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -371,7 +373,8 @@ def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Returns: diff --git a/google/ads/googleads/v21/services/services/remarketing_action_service/async_client.py b/google/ads/googleads/v21/services/services/remarketing_action_service/async_client.py index a4744a13a..f9b9780c6 100644 --- a/google/ads/googleads/v21/services/services/remarketing_action_service/async_client.py +++ b/google/ads/googleads/v21/services/services/remarketing_action_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import remarketing_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RemarketingActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: RemarketingActionServiceAsyncClient: The constructed client. """ - return RemarketingActionServiceClient.from_service_account_info.__func__(RemarketingActionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + RemarketingActionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + RemarketingActionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RemarketingActionServiceAsyncClient: The constructed client. """ - return RemarketingActionServiceClient.from_service_account_file.__func__(RemarketingActionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + RemarketingActionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + RemarketingActionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/remarketing_action_service/client.py b/google/ads/googleads/v21/services/services/remarketing_action_service/client.py index d8148c35e..271bc8bc8 100644 --- a/google/ads/googleads/v21/services/services/remarketing_action_service/client.py +++ b/google/ads/googleads/v21/services/services/remarketing_action_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import remarketing_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RemarketingActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + RemarketingActionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +383,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +415,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + RemarketingActionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/remarketing_action_service/transports/base.py b/google/ads/googleads/v21/services/services/remarketing_action_service/transports/base.py index fba8ced8d..70c0e86e7 100644 --- a/google/ads/googleads/v21/services/services/remarketing_action_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/remarketing_action_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/remarketing_action_service/transports/grpc.py b/google/ads/googleads/v21/services/services/remarketing_action_service/transports/grpc.py index 5df3607fd..fcc15cf8e 100644 --- a/google/ads/googleads/v21/services/services/remarketing_action_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/remarketing_action_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/remarketing_action_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/remarketing_action_service/transports/grpc_asyncio.py index d3dd96299..1208b6b3d 100644 --- a/google/ads/googleads/v21/services/services/remarketing_action_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/remarketing_action_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/shareable_preview_service/async_client.py b/google/ads/googleads/v21/services/services/shareable_preview_service/async_client.py index 2a01521dc..818379091 100644 --- a/google/ads/googleads/v21/services/services/shareable_preview_service/async_client.py +++ b/google/ads/googleads/v21/services/services/shareable_preview_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -108,7 +107,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ShareablePreviewServiceAsyncClient: The constructed client. """ - return ShareablePreviewServiceClient.from_service_account_info.__func__(ShareablePreviewServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ShareablePreviewServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ShareablePreviewServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +128,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ShareablePreviewServiceAsyncClient: The constructed client. """ - return ShareablePreviewServiceClient.from_service_account_file.__func__(ShareablePreviewServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ShareablePreviewServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ShareablePreviewServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/shareable_preview_service/client.py b/google/ads/googleads/v21/services/services/shareable_preview_service/client.py index 33ca78e0e..eb3b53e48 100644 --- a/google/ads/googleads/v21/services/services/shareable_preview_service/client.py +++ b/google/ads/googleads/v21/services/services/shareable_preview_service/client.py @@ -150,6 +150,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -321,14 +349,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ShareablePreviewServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -336,7 +360,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -368,22 +392,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ShareablePreviewServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/shareable_preview_service/transports/base.py b/google/ads/googleads/v21/services/services/shareable_preview_service/transports/base.py index f5d1f4de5..395bc4917 100644 --- a/google/ads/googleads/v21/services/services/shareable_preview_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/shareable_preview_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/shareable_preview_service/transports/grpc.py b/google/ads/googleads/v21/services/services/shareable_preview_service/transports/grpc.py index cf4aa7fac..59b5d3f86 100644 --- a/google/ads/googleads/v21/services/services/shareable_preview_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/shareable_preview_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/shareable_preview_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/shareable_preview_service/transports/grpc_asyncio.py index e5114ef70..9dabdb8f9 100644 --- a/google/ads/googleads/v21/services/services/shareable_preview_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/shareable_preview_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/shared_criterion_service/async_client.py b/google/ads/googleads/v21/services/services/shared_criterion_service/async_client.py index 5dc292b56..6ae50efe8 100644 --- a/google/ads/googleads/v21/services/services/shared_criterion_service/async_client.py +++ b/google/ads/googleads/v21/services/services/shared_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import shared_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SharedCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SharedCriterionServiceAsyncClient: The constructed client. """ - return SharedCriterionServiceClient.from_service_account_info.__func__(SharedCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SharedCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SharedCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SharedCriterionServiceAsyncClient: The constructed client. """ - return SharedCriterionServiceClient.from_service_account_file.__func__(SharedCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SharedCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SharedCriterionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/shared_criterion_service/client.py b/google/ads/googleads/v21/services/services/shared_criterion_service/client.py index 06e76645b..02bb88f47 100644 --- a/google/ads/googleads/v21/services/services/shared_criterion_service/client.py +++ b/google/ads/googleads/v21/services/services/shared_criterion_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import shared_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SharedCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -380,14 +408,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + SharedCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -395,7 +419,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -427,22 +451,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + SharedCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/shared_criterion_service/transports/base.py b/google/ads/googleads/v21/services/services/shared_criterion_service/transports/base.py index b7e3386af..aac825f71 100644 --- a/google/ads/googleads/v21/services/services/shared_criterion_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/shared_criterion_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/shared_criterion_service/transports/grpc.py b/google/ads/googleads/v21/services/services/shared_criterion_service/transports/grpc.py index 62bed723f..38a7164dd 100644 --- a/google/ads/googleads/v21/services/services/shared_criterion_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/shared_criterion_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/shared_criterion_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/shared_criterion_service/transports/grpc_asyncio.py index b268eb1bb..2a1f61a97 100644 --- a/google/ads/googleads/v21/services/services/shared_criterion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/shared_criterion_service/transports/grpc_asyncio.py @@ -154,8 +154,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -210,9 +211,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/shared_set_service/async_client.py b/google/ads/googleads/v21/services/services/shared_set_service/async_client.py index e16eed197..e5c16e9ef 100644 --- a/google/ads/googleads/v21/services/services/shared_set_service/async_client.py +++ b/google/ads/googleads/v21/services/services/shared_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import SharedSetServiceTransport, DEFAULT_CLIENT_INFO from .client import SharedSetServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SharedSetServiceAsyncClient: The constructed client. """ - return SharedSetServiceClient.from_service_account_info.__func__(SharedSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SharedSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SharedSetServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SharedSetServiceAsyncClient: The constructed client. """ - return SharedSetServiceClient.from_service_account_file.__func__(SharedSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SharedSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SharedSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/shared_set_service/client.py b/google/ads/googleads/v21/services/services/shared_set_service/client.py index d601bdec8..653732231 100644 --- a/google/ads/googleads/v21/services/services/shared_set_service/client.py +++ b/google/ads/googleads/v21/services/services/shared_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import SharedSetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SharedSetServiceGrpcTransport from .transports.grpc_asyncio import SharedSetServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = SharedSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = SharedSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/shared_set_service/transports/base.py b/google/ads/googleads/v21/services/services/shared_set_service/transports/base.py index 4dce40522..9df294667 100644 --- a/google/ads/googleads/v21/services/services/shared_set_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/shared_set_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/shared_set_service/transports/grpc.py b/google/ads/googleads/v21/services/services/shared_set_service/transports/grpc.py index 1142defec..5fb9a36fd 100644 --- a/google/ads/googleads/v21/services/services/shared_set_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/shared_set_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/shared_set_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/shared_set_service/transports/grpc_asyncio.py index ef2b2d5ec..33f3eb6e6 100644 --- a/google/ads/googleads/v21/services/services/shared_set_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/shared_set_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/async_client.py b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/async_client.py index a063600b5..2bf4af230 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/async_client.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( smart_campaign_setting_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SmartCampaignSettingServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SmartCampaignSettingServiceAsyncClient: The constructed client. """ - return SmartCampaignSettingServiceClient.from_service_account_info.__func__(SmartCampaignSettingServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SmartCampaignSettingServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SmartCampaignSettingServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SmartCampaignSettingServiceAsyncClient: The constructed client. """ - return SmartCampaignSettingServiceClient.from_service_account_file.__func__(SmartCampaignSettingServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SmartCampaignSettingServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SmartCampaignSettingServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/client.py b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/client.py index 0ae1363a7..108ca2a25 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/client.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( smart_campaign_setting_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SmartCampaignSettingServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -366,14 +394,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + SmartCampaignSettingServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -381,7 +405,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -413,22 +437,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + SmartCampaignSettingServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/base.py b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/base.py index de704b6de..57d592723 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/grpc.py b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/grpc.py index 80fd975d4..c81017104 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/grpc_asyncio.py index b8ed6c00f..7249a2ce6 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_setting_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/async_client.py b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/async_client.py index 6c99f6803..c5b4fd0c6 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/async_client.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SmartCampaignSuggestServiceAsyncClient: The constructed client. """ - return SmartCampaignSuggestServiceClient.from_service_account_info.__func__(SmartCampaignSuggestServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SmartCampaignSuggestServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SmartCampaignSuggestServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SmartCampaignSuggestServiceAsyncClient: The constructed client. """ - return SmartCampaignSuggestServiceClient.from_service_account_file.__func__(SmartCampaignSuggestServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SmartCampaignSuggestServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SmartCampaignSuggestServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -530,13 +539,13 @@ async def suggest_keyword_themes( Required. Information to get keyword theme suggestions. Required fields: - - suggestion_info.final_url - - suggestion_info.language_code - - suggestion_info.geo_target + - suggestion_info.final_url + - suggestion_info.language_code + - suggestion_info.geo_target Recommended fields: - - suggestion_info.business_setting + - suggestion_info.business_setting This corresponds to the ``suggestion_info`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/client.py b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/client.py index 7c0d13559..5b7fc18fc 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/client.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -355,14 +383,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + SmartCampaignSuggestServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -370,7 +394,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -402,22 +426,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + SmartCampaignSuggestServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -991,13 +1011,13 @@ def suggest_keyword_themes( Required. Information to get keyword theme suggestions. Required fields: - - suggestion_info.final_url - - suggestion_info.language_code - - suggestion_info.geo_target + - suggestion_info.final_url + - suggestion_info.language_code + - suggestion_info.geo_target Recommended fields: - - suggestion_info.business_setting + - suggestion_info.business_setting This corresponds to the ``suggestion_info`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/base.py b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/base.py index 8cfeb62d1..fe3e937a1 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/grpc.py b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/grpc.py index 51c0f64cc..5573056e0 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/grpc_asyncio.py index a36344098..6d6fcbefb 100644 --- a/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/smart_campaign_suggest_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/async_client.py b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/async_client.py index c1aabd224..f5133340d 100644 --- a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/async_client.py +++ b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ThirdPartyAppAnalyticsLinkServiceAsyncClient: The constructed client. """ - return ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_info.__func__(ThirdPartyAppAnalyticsLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ThirdPartyAppAnalyticsLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ThirdPartyAppAnalyticsLinkServiceAsyncClient: The constructed client. """ - return ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_file.__func__(ThirdPartyAppAnalyticsLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ThirdPartyAppAnalyticsLinkServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/client.py b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/client.py index 335061527..22c11d237 100644 --- a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/client.py +++ b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/client.py @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -337,14 +365,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ThirdPartyAppAnalyticsLinkServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -352,7 +376,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -384,22 +408,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ThirdPartyAppAnalyticsLinkServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/base.py b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/base.py index 679a77901..ad9387606 100644 --- a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/grpc.py b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/grpc.py index 08b7aecec..903e6f601 100644 --- a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/grpc.py @@ -170,9 +170,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -313,9 +314,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/grpc_asyncio.py index 5080fed23..08f66edea 100644 --- a/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/third_party_app_analytics_link_service/transports/grpc_asyncio.py @@ -160,8 +160,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -216,9 +217,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/async_client.py b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/async_client.py index f5ad0d930..caee4345f 100644 --- a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/async_client.py +++ b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -112,7 +111,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: TravelAssetSuggestionServiceAsyncClient: The constructed client. """ - return TravelAssetSuggestionServiceClient.from_service_account_info.__func__(TravelAssetSuggestionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + TravelAssetSuggestionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + TravelAssetSuggestionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -128,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: TravelAssetSuggestionServiceAsyncClient: The constructed client. """ - return TravelAssetSuggestionServiceClient.from_service_account_file.__func__(TravelAssetSuggestionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + TravelAssetSuggestionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + TravelAssetSuggestionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/client.py b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/client.py index 94fa6efd7..a6c1deb75 100644 --- a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/client.py +++ b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -315,14 +343,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + TravelAssetSuggestionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -330,7 +354,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -362,22 +386,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + TravelAssetSuggestionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/base.py b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/base.py index 7e77af783..2ed94ff52 100644 --- a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/grpc.py b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/grpc.py index 6fae040fb..6385935a7 100644 --- a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/grpc_asyncio.py index 5fb753d7f..9fb99cc4e 100644 --- a/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/travel_asset_suggestion_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/user_data_service/async_client.py b/google/ads/googleads/v21/services/services/user_data_service/async_client.py index c22a96d4b..47d7bd520 100644 --- a/google/ads/googleads/v21/services/services/user_data_service/async_client.py +++ b/google/ads/googleads/v21/services/services/user_data_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: UserDataServiceAsyncClient: The constructed client. """ - return UserDataServiceClient.from_service_account_info.__func__(UserDataServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + UserDataServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(UserDataServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +129,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserDataServiceAsyncClient: The constructed client. """ - return UserDataServiceClient.from_service_account_file.__func__(UserDataServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + UserDataServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + UserDataServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/user_data_service/client.py b/google/ads/googleads/v21/services/services/user_data_service/client.py index 3584f17d6..d3f0a36a7 100644 --- a/google/ads/googleads/v21/services/services/user_data_service/client.py +++ b/google/ads/googleads/v21/services/services/user_data_service/client.py @@ -141,6 +141,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -312,14 +340,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = UserDataServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -327,7 +349,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -359,22 +381,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = UserDataServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/user_data_service/transports/base.py b/google/ads/googleads/v21/services/services/user_data_service/transports/base.py index 05f1593c7..d4d343247 100644 --- a/google/ads/googleads/v21/services/services/user_data_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/user_data_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/user_data_service/transports/grpc.py b/google/ads/googleads/v21/services/services/user_data_service/transports/grpc.py index e009c0872..bc2298af2 100644 --- a/google/ads/googleads/v21/services/services/user_data_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/user_data_service/transports/grpc.py @@ -169,9 +169,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -312,9 +313,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/user_data_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/user_data_service/transports/grpc_asyncio.py index 0dcc2e174..baa654bfe 100644 --- a/google/ads/googleads/v21/services/services/user_data_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/user_data_service/transports/grpc_asyncio.py @@ -159,8 +159,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -215,9 +216,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/user_list_customer_type_service/async_client.py b/google/ads/googleads/v21/services/services/user_list_customer_type_service/async_client.py index bdfdef23a..8fe895332 100644 --- a/google/ads/googleads/v21/services/services/user_list_customer_type_service/async_client.py +++ b/google/ads/googleads/v21/services/services/user_list_customer_type_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v21.services.types import ( user_list_customer_type_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( UserListCustomerTypeServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: UserListCustomerTypeServiceAsyncClient: The constructed client. """ - return UserListCustomerTypeServiceClient.from_service_account_info.__func__(UserListCustomerTypeServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + UserListCustomerTypeServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + UserListCustomerTypeServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserListCustomerTypeServiceAsyncClient: The constructed client. """ - return UserListCustomerTypeServiceClient.from_service_account_file.__func__(UserListCustomerTypeServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + UserListCustomerTypeServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + UserListCustomerTypeServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/user_list_customer_type_service/client.py b/google/ads/googleads/v21/services/services/user_list_customer_type_service/client.py index a06473c69..bbafdb95f 100644 --- a/google/ads/googleads/v21/services/services/user_list_customer_type_service/client.py +++ b/google/ads/googleads/v21/services/services/user_list_customer_type_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v21.services.types import ( user_list_customer_type_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( UserListCustomerTypeServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + UserListCustomerTypeServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + UserListCustomerTypeServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/base.py b/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/base.py index 316477b36..0052b41ee 100644 --- a/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/base.py @@ -68,9 +68,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -83,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/grpc.py b/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/grpc.py index 6e85e893a..7ae28f2fc 100644 --- a/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/grpc.py @@ -166,9 +166,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -309,9 +310,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/grpc_asyncio.py index c3162d8b1..c8a6c4e3a 100644 --- a/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/user_list_customer_type_service/transports/grpc_asyncio.py @@ -156,8 +156,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -212,9 +213,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/user_list_service/async_client.py b/google/ads/googleads/v21/services/services/user_list_service/async_client.py index 938aa61bd..ca542d02f 100644 --- a/google/ads/googleads/v21/services/services/user_list_service/async_client.py +++ b/google/ads/googleads/v21/services/services/user_list_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v21.services.types import user_list_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import UserListServiceTransport, DEFAULT_CLIENT_INFO from .client import UserListServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: UserListServiceAsyncClient: The constructed client. """ - return UserListServiceClient.from_service_account_info.__func__(UserListServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + UserListServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(UserListServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserListServiceAsyncClient: The constructed client. """ - return UserListServiceClient.from_service_account_file.__func__(UserListServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + UserListServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + UserListServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v21/services/services/user_list_service/client.py b/google/ads/googleads/v21/services/services/user_list_service/client.py index 5b8246828..923a21233 100644 --- a/google/ads/googleads/v21/services/services/user_list_service/client.py +++ b/google/ads/googleads/v21/services/services/user_list_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v21.services.types import user_list_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import UserListServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import UserListServiceGrpcTransport from .transports.grpc_asyncio import UserListServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = UserListServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = UserListServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v21/services/services/user_list_service/transports/base.py b/google/ads/googleads/v21/services/services/user_list_service/transports/base.py index 471311f00..24bfe7761 100644 --- a/google/ads/googleads/v21/services/services/user_list_service/transports/base.py +++ b/google/ads/googleads/v21/services/services/user_list_service/transports/base.py @@ -66,9 +66,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. @@ -81,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -98,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v21/services/services/user_list_service/transports/grpc.py b/google/ads/googleads/v21/services/services/user_list_service/transports/grpc.py index 836d5ebd2..ec6f0e84c 100644 --- a/google/ads/googleads/v21/services/services/user_list_service/transports/grpc.py +++ b/google/ads/googleads/v21/services/services/user_list_service/transports/grpc.py @@ -162,9 +162,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if a ``channel`` instance is provided. channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): @@ -305,9 +306,10 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/services/user_list_service/transports/grpc_asyncio.py b/google/ads/googleads/v21/services/services/user_list_service/transports/grpc_asyncio.py index 805d58318..10980b32f 100644 --- a/google/ads/googleads/v21/services/services/user_list_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v21/services/services/user_list_service/transports/grpc_asyncio.py @@ -152,8 +152,9 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -208,9 +209,10 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can + credentials_file (Optional[str]): Deprecated. A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. diff --git a/google/ads/googleads/v21/services/types/account_budget_proposal_service.py b/google/ads/googleads/v21/services/types/account_budget_proposal_service.py index 2eaaa225e..d2739ef50 100644 --- a/google/ads/googleads/v21/services/types/account_budget_proposal_service.py +++ b/google/ads/googleads/v21/services/types/account_budget_proposal_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import account_budget_proposal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/account_link_service.py b/google/ads/googleads/v21/services/types/account_link_service.py index 463307b47..57dcdf253 100644 --- a/google/ads/googleads/v21/services/types/account_link_service.py +++ b/google/ads/googleads/v21/services/types/account_link_service.py @@ -21,9 +21,8 @@ from google.ads.googleads.v21.resources.types import ( account_link as gagr_account_link, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_ad_label_service.py b/google/ads/googleads/v21/services/types/ad_group_ad_label_service.py index 8244372ca..910dac63f 100644 --- a/google/ads/googleads/v21/services/types/ad_group_ad_label_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_ad_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import ad_group_ad_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_ad_service.py b/google/ads/googleads/v21/services/types/ad_group_ad_service.py index 5c58a7d7f..8b84c97a8 100644 --- a/google/ads/googleads/v21/services/types/ad_group_ad_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_ad_service.py @@ -29,9 +29,8 @@ from google.ads.googleads.v21.resources.types import ( ad_group_ad as gagr_ad_group_ad, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", @@ -216,7 +215,7 @@ class MutateAdGroupAdResult(proto.Message): class RemoveAutomaticallyCreatedAssetsRequest(proto.Message): r"""Request message for - [AdGroupAdService.RemoveAutomaticallyCreatedAssetsRequest][]. + [AdGroupAdService.RemoveAutomaticallyCreatedAssets][google.ads.googleads.v21.services.AdGroupAdService.RemoveAutomaticallyCreatedAssets]. Attributes: ad_group_ad (str): diff --git a/google/ads/googleads/v21/services/types/ad_group_asset_service.py b/google/ads/googleads/v21/services/types/ad_group_asset_service.py index 89a266134..e7eaf2946 100644 --- a/google/ads/googleads/v21/services/types/ad_group_asset_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_asset_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( ad_group_asset as gagr_ad_group_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_asset_set_service.py b/google/ads/googleads/v21/services/types/ad_group_asset_set_service.py index 1659ae68a..5bd045e9c 100644 --- a/google/ads/googleads/v21/services/types/ad_group_asset_set_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_asset_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( ad_group_asset_set as gagr_ad_group_asset_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_bid_modifier_service.py b/google/ads/googleads/v21/services/types/ad_group_bid_modifier_service.py index be1a2b7a5..0ddbde3e2 100644 --- a/google/ads/googleads/v21/services/types/ad_group_bid_modifier_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_bid_modifier_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( ad_group_bid_modifier as gagr_ad_group_bid_modifier, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_criterion_customizer_service.py b/google/ads/googleads/v21/services/types/ad_group_criterion_customizer_service.py index 00a66a1e0..18234a596 100644 --- a/google/ads/googleads/v21/services/types/ad_group_criterion_customizer_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_criterion_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( ad_group_criterion_customizer as gagr_ad_group_criterion_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_criterion_label_service.py b/google/ads/googleads/v21/services/types/ad_group_criterion_label_service.py index c6f20272f..7668cc652 100644 --- a/google/ads/googleads/v21/services/types/ad_group_criterion_label_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_criterion_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import ad_group_criterion_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_criterion_service.py b/google/ads/googleads/v21/services/types/ad_group_criterion_service.py index 3ad2a9e3a..e34eec14c 100644 --- a/google/ads/googleads/v21/services/types/ad_group_criterion_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_criterion_service.py @@ -26,9 +26,8 @@ from google.ads.googleads.v21.resources.types import ( ad_group_criterion as gagr_ad_group_criterion, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_customizer_service.py b/google/ads/googleads/v21/services/types/ad_group_customizer_service.py index 64bf7e4a1..ca3317291 100644 --- a/google/ads/googleads/v21/services/types/ad_group_customizer_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( ad_group_customizer as gagr_ad_group_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_label_service.py b/google/ads/googleads/v21/services/types/ad_group_label_service.py index cef592f97..38aceb9e4 100644 --- a/google/ads/googleads/v21/services/types/ad_group_label_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import ad_group_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_group_service.py b/google/ads/googleads/v21/services/types/ad_group_service.py index 07453453f..9d105a0eb 100644 --- a/google/ads/googleads/v21/services/types/ad_group_service.py +++ b/google/ads/googleads/v21/services/types/ad_group_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v21.resources.types import ad_group as gagr_ad_group -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_parameter_service.py b/google/ads/googleads/v21/services/types/ad_parameter_service.py index 25502ae97..d3c80d741 100644 --- a/google/ads/googleads/v21/services/types/ad_parameter_service.py +++ b/google/ads/googleads/v21/services/types/ad_parameter_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( ad_parameter as gagr_ad_parameter, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/ad_service.py b/google/ads/googleads/v21/services/types/ad_service.py index 960cf26fa..f82d0b69b 100644 --- a/google/ads/googleads/v21/services/types/ad_service.py +++ b/google/ads/googleads/v21/services/types/ad_service.py @@ -24,9 +24,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v21.resources.types import ad as gagr_ad -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/asset_group_asset_service.py b/google/ads/googleads/v21/services/types/asset_group_asset_service.py index 57e3ecc96..fc27d5c3e 100644 --- a/google/ads/googleads/v21/services/types/asset_group_asset_service.py +++ b/google/ads/googleads/v21/services/types/asset_group_asset_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import asset_group_asset -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/asset_group_listing_group_filter_service.py b/google/ads/googleads/v21/services/types/asset_group_listing_group_filter_service.py index bb4254919..88c067f3a 100644 --- a/google/ads/googleads/v21/services/types/asset_group_listing_group_filter_service.py +++ b/google/ads/googleads/v21/services/types/asset_group_listing_group_filter_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( asset_group_listing_group_filter as gagr_asset_group_listing_group_filter, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/asset_group_service.py b/google/ads/googleads/v21/services/types/asset_group_service.py index 278566903..550d3fad6 100644 --- a/google/ads/googleads/v21/services/types/asset_group_service.py +++ b/google/ads/googleads/v21/services/types/asset_group_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import asset_group -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/asset_group_signal_service.py b/google/ads/googleads/v21/services/types/asset_group_signal_service.py index 8d9a2e622..bf2b66495 100644 --- a/google/ads/googleads/v21/services/types/asset_group_signal_service.py +++ b/google/ads/googleads/v21/services/types/asset_group_signal_service.py @@ -26,8 +26,7 @@ from google.ads.googleads.v21.resources.types import ( asset_group_signal as gagr_asset_group_signal, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/asset_service.py b/google/ads/googleads/v21/services/types/asset_service.py index 5047c2955..3c0eda50e 100644 --- a/google/ads/googleads/v21/services/types/asset_service.py +++ b/google/ads/googleads/v21/services/types/asset_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v21.resources.types import asset as gagr_asset -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/asset_set_asset_service.py b/google/ads/googleads/v21/services/types/asset_set_asset_service.py index 86f562d02..0b74579bf 100644 --- a/google/ads/googleads/v21/services/types/asset_set_asset_service.py +++ b/google/ads/googleads/v21/services/types/asset_set_asset_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( asset_set_asset as gagr_asset_set_asset, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/asset_set_service.py b/google/ads/googleads/v21/services/types/asset_set_service.py index 8e96bfca0..ebae9013b 100644 --- a/google/ads/googleads/v21/services/types/asset_set_service.py +++ b/google/ads/googleads/v21/services/types/asset_set_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v21.resources.types import asset_set as gagr_asset_set -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/audience_insights_service.py b/google/ads/googleads/v21/services/types/audience_insights_service.py index 3c1df6303..bf201a576 100644 --- a/google/ads/googleads/v21/services/types/audience_insights_service.py +++ b/google/ads/googleads/v21/services/types/audience_insights_service.py @@ -28,7 +28,6 @@ audience_insights_marketing_objective, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.services", marshal="google.ads.googleads.v21", @@ -732,7 +731,7 @@ class GenerateTargetingSuggestionMetricsResponse(proto.Message): suggestions (MutableSequence[google.ads.googleads.v21.services.types.TargetingSuggestionMetrics]): Suggested targetable audiences. There will be one suggestion for each - [GenerateTargetingSuggestionMetricsRequest.audiences] + [GenerateTargetingSuggestionMetricsRequest.audiences][google.ads.googleads.v21.services.GenerateTargetingSuggestionMetricsRequest.audiences] requested, matching the order requested. """ diff --git a/google/ads/googleads/v21/services/types/audience_service.py b/google/ads/googleads/v21/services/types/audience_service.py index 2916dddca..c72128a24 100644 --- a/google/ads/googleads/v21/services/types/audience_service.py +++ b/google/ads/googleads/v21/services/types/audience_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v21.resources.types import audience as gagr_audience -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/automatically_created_asset_removal_service.py b/google/ads/googleads/v21/services/types/automatically_created_asset_removal_service.py index fd247da9e..aa98c7058 100644 --- a/google/ads/googleads/v21/services/types/automatically_created_asset_removal_service.py +++ b/google/ads/googleads/v21/services/types/automatically_created_asset_removal_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.enums.types import asset_field_type -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/batch_job_service.py b/google/ads/googleads/v21/services/types/batch_job_service.py index e0aa14887..3079c45ad 100644 --- a/google/ads/googleads/v21/services/types/batch_job_service.py +++ b/google/ads/googleads/v21/services/types/batch_job_service.py @@ -24,8 +24,7 @@ ) from google.ads.googleads.v21.resources.types import batch_job from google.ads.googleads.v21.services.types import google_ads_service -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/bidding_data_exclusion_service.py b/google/ads/googleads/v21/services/types/bidding_data_exclusion_service.py index 638265659..468661108 100644 --- a/google/ads/googleads/v21/services/types/bidding_data_exclusion_service.py +++ b/google/ads/googleads/v21/services/types/bidding_data_exclusion_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( bidding_data_exclusion as gagr_bidding_data_exclusion, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/bidding_seasonality_adjustment_service.py b/google/ads/googleads/v21/services/types/bidding_seasonality_adjustment_service.py index 2a826c166..6d5750b2a 100644 --- a/google/ads/googleads/v21/services/types/bidding_seasonality_adjustment_service.py +++ b/google/ads/googleads/v21/services/types/bidding_seasonality_adjustment_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( bidding_seasonality_adjustment as gagr_bidding_seasonality_adjustment, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/bidding_strategy_service.py b/google/ads/googleads/v21/services/types/bidding_strategy_service.py index 9910eca18..1c9e836b3 100644 --- a/google/ads/googleads/v21/services/types/bidding_strategy_service.py +++ b/google/ads/googleads/v21/services/types/bidding_strategy_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( bidding_strategy as gagr_bidding_strategy, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_asset_service.py b/google/ads/googleads/v21/services/types/campaign_asset_service.py index 2944b8ee1..3e6e62674 100644 --- a/google/ads/googleads/v21/services/types/campaign_asset_service.py +++ b/google/ads/googleads/v21/services/types/campaign_asset_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( campaign_asset as gagr_campaign_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_asset_set_service.py b/google/ads/googleads/v21/services/types/campaign_asset_set_service.py index d54ec903d..5f030a9b1 100644 --- a/google/ads/googleads/v21/services/types/campaign_asset_set_service.py +++ b/google/ads/googleads/v21/services/types/campaign_asset_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( campaign_asset_set as gagr_campaign_asset_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_bid_modifier_service.py b/google/ads/googleads/v21/services/types/campaign_bid_modifier_service.py index 8bc1a8263..678acdf83 100644 --- a/google/ads/googleads/v21/services/types/campaign_bid_modifier_service.py +++ b/google/ads/googleads/v21/services/types/campaign_bid_modifier_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( campaign_bid_modifier as gagr_campaign_bid_modifier, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_budget_service.py b/google/ads/googleads/v21/services/types/campaign_budget_service.py index cc13c1267..020040fdb 100644 --- a/google/ads/googleads/v21/services/types/campaign_budget_service.py +++ b/google/ads/googleads/v21/services/types/campaign_budget_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( campaign_budget as gagr_campaign_budget, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_conversion_goal_service.py b/google/ads/googleads/v21/services/types/campaign_conversion_goal_service.py index 01ad3c08d..31e2c2fed 100644 --- a/google/ads/googleads/v21/services/types/campaign_conversion_goal_service.py +++ b/google/ads/googleads/v21/services/types/campaign_conversion_goal_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import campaign_conversion_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_criterion_service.py b/google/ads/googleads/v21/services/types/campaign_criterion_service.py index 9aa707590..7d692f048 100644 --- a/google/ads/googleads/v21/services/types/campaign_criterion_service.py +++ b/google/ads/googleads/v21/services/types/campaign_criterion_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( campaign_criterion as gagr_campaign_criterion, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_customizer_service.py b/google/ads/googleads/v21/services/types/campaign_customizer_service.py index 9bfd04d0e..ee2f49b6a 100644 --- a/google/ads/googleads/v21/services/types/campaign_customizer_service.py +++ b/google/ads/googleads/v21/services/types/campaign_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( campaign_customizer as gagr_campaign_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_draft_service.py b/google/ads/googleads/v21/services/types/campaign_draft_service.py index ecf1f48f1..f8aa7833c 100644 --- a/google/ads/googleads/v21/services/types/campaign_draft_service.py +++ b/google/ads/googleads/v21/services/types/campaign_draft_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( campaign_draft as gagr_campaign_draft, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_group_service.py b/google/ads/googleads/v21/services/types/campaign_group_service.py index a9b953ec5..2b3b11eab 100644 --- a/google/ads/googleads/v21/services/types/campaign_group_service.py +++ b/google/ads/googleads/v21/services/types/campaign_group_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( campaign_group as gagr_campaign_group, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_label_service.py b/google/ads/googleads/v21/services/types/campaign_label_service.py index 344bd848f..b3b29f683 100644 --- a/google/ads/googleads/v21/services/types/campaign_label_service.py +++ b/google/ads/googleads/v21/services/types/campaign_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import campaign_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_lifecycle_goal_service.py b/google/ads/googleads/v21/services/types/campaign_lifecycle_goal_service.py index edcc07c88..2831a06df 100644 --- a/google/ads/googleads/v21/services/types/campaign_lifecycle_goal_service.py +++ b/google/ads/googleads/v21/services/types/campaign_lifecycle_goal_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import campaign_lifecycle_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", @@ -36,7 +35,7 @@ class ConfigureCampaignLifecycleGoalsRequest(proto.Message): r"""Request message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v21.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. Attributes: customer_id (str): @@ -115,7 +114,7 @@ class CampaignLifecycleGoalOperation(proto.Message): class ConfigureCampaignLifecycleGoalsResponse(proto.Message): r"""Response message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v21.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. Attributes: result (google.ads.googleads.v21.services.types.ConfigureCampaignLifecycleGoalsResult): diff --git a/google/ads/googleads/v21/services/types/campaign_service.py b/google/ads/googleads/v21/services/types/campaign_service.py index bfdfbe9f6..7127cef45 100644 --- a/google/ads/googleads/v21/services/types/campaign_service.py +++ b/google/ads/googleads/v21/services/types/campaign_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v21.resources.types import campaign as gagr_campaign -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/campaign_shared_set_service.py b/google/ads/googleads/v21/services/types/campaign_shared_set_service.py index 8e4e675e2..d13dc5802 100644 --- a/google/ads/googleads/v21/services/types/campaign_shared_set_service.py +++ b/google/ads/googleads/v21/services/types/campaign_shared_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( campaign_shared_set as gagr_campaign_shared_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/content_creator_insights_service.py b/google/ads/googleads/v21/services/types/content_creator_insights_service.py index 9f8eaf1af..47ae82310 100644 --- a/google/ads/googleads/v21/services/types/content_creator_insights_service.py +++ b/google/ads/googleads/v21/services/types/content_creator_insights_service.py @@ -24,7 +24,6 @@ from google.ads.googleads.v21.common.types import criteria from google.ads.googleads.v21.enums.types import insights_trend - __protobuf__ = proto.module( package="google.ads.googleads.v21.services", marshal="google.ads.googleads.v21", @@ -69,24 +68,28 @@ class GenerateCreatorInsightsRequest(proto.Message): to the criteria. sub_country_locations (MutableSequence[google.ads.googleads.v21.common.types.LocationInfo]): The sub-country geographic locations to search that apply to - the criteria. Only supported for [SearchAttributes] + the criteria. Only supported for + [SearchAttributes][google.ads.googleads.v21.services.GenerateCreatorInsightsRequest.SearchAttributes] criteria. search_attributes (google.ads.googleads.v21.services.types.GenerateCreatorInsightsRequest.SearchAttributes): The attributes used to identify top creators. Data fetched is based on the list of countries or sub-country locations - specified in [country_locations] or [sub_country_locations]. + specified in + [country_locations][google.ads.googleads.v21.services.GenerateCreatorInsightsRequest.country_locations] + or + [sub_country_locations][google.ads.googleads.v21.services.GenerateCreatorInsightsRequest.sub_country_locations]. This field is a member of `oneof`_ ``criteria``. search_brand (google.ads.googleads.v21.services.types.GenerateCreatorInsightsRequest.SearchBrand): A brand used to search for top creators. Data fetched is based on the list of countries specified in - [country_locations]. + [country_locations][google.ads.googleads.v21.services.GenerateCreatorInsightsRequest.country_locations]. This field is a member of `oneof`_ ``criteria``. search_channels (google.ads.googleads.v21.services.types.GenerateCreatorInsightsRequest.YouTubeChannels): YouTube Channel IDs for Creator Insights. Data fetched for channels is based on the list of countries specified in - [country_locations]. + [country_locations][google.ads.googleads.v21.services.GenerateCreatorInsightsRequest.country_locations]. This field is a member of `oneof`_ ``criteria``. """ @@ -109,7 +112,7 @@ class SearchAttributes(proto.Message): types of content. This is used to search for creators whose content matches the input creator attributes. Only Knowledge Graph Entities tagged with - [InsightsKnowledgeGraphEntityCapabilities.CREATOR_ATTRIBUTE][] + [CREATOR_ATTRIBUTE][google.ads.googleads.v21.enums.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities.CREATOR_ATTRIBUTE] are supported. Use [AudienceInsightsService.ListAudienceInsightsAttributes][google.ads.googleads.v21.services.AudienceInsightsService.ListAudienceInsightsAttributes] to get the list of supported entities. Other attributes @@ -141,9 +144,10 @@ class SearchBrand(proto.Message): find insights. include_related_topics (bool): Optional. When true, we will expand the search to beyond - just the entities specified in [brand_entities] to other - related knowledge graph entities similar to the brand. The - default value is ``false``. + just the entities specified in + [brand_entities][google.ads.googleads.v21.services.GenerateCreatorInsightsRequest.SearchBrand.brand_entities] + to other related knowledge graph entities similar to the + brand. The default value is ``false``. """ brand_entities: MutableSequence[ @@ -246,7 +250,7 @@ class GenerateCreatorInsightsResponse(proto.Message): class GenerateTrendingInsightsRequest(proto.Message): r"""Request message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v21.services.ContentCreatorInsightsService.GenerateTrendingInsights]. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -314,7 +318,7 @@ class GenerateTrendingInsightsRequest(proto.Message): class GenerateTrendingInsightsResponse(proto.Message): r"""Response message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v21.services.ContentCreatorInsightsService.GenerateTrendingInsights]. Attributes: trend_insights (MutableSequence[google.ads.googleads.v21.services.types.TrendInsight]): @@ -375,7 +379,7 @@ class YouTubeMetrics(proto.Message): The lifetime engagement rate of this channel. The value is computed as the total number of likes, shares, and comments across all videos - divided by the total number of videos. + divided by the total number of video views. average_views_per_video (float): The average number of views per video in the last 28 days. @@ -611,7 +615,10 @@ class SearchTopics(proto.Message): entities (MutableSequence[google.ads.googleads.v21.common.types.AudienceInsightsEntity]): Required. A list of knowledge graph entities to retrieve trend information for. Supported entities are tagged with - [InsightsKnowledgeGraphEntityCapabilities.CONTENT_TRENDING_INSIGHTS][]. + [CONTENT_TRENDING_INSIGHTS][google.ads.googleads.v21.enums.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities.CONTENT_TRENDING_INSIGHTS]. + Use + [AudienceInsightsService.ListAudienceInsightsAttributes][google.ads.googleads.v21.services.AudienceInsightsService.ListAudienceInsightsAttributes] + to get the list of supported entities. """ entities: MutableSequence[ @@ -630,7 +637,9 @@ class TrendInsight(proto.Message): trend_attribute (google.ads.googleads.v21.common.types.AudienceInsightsAttributeMetadata): The attribute this trend is for. trend_metrics (google.ads.googleads.v21.services.types.TrendInsightMetrics): - Metrics associated with this trend. + Metrics associated with this trend. These + metrics are for the latest available month and + the comparison period is 3 months. trend (google.ads.googleads.v21.enums.types.InsightsTrendEnum.InsightsTrend): The direction of trend (such as RISING or DECLINING). diff --git a/google/ads/googleads/v21/services/types/conversion_action_service.py b/google/ads/googleads/v21/services/types/conversion_action_service.py index b3ffe1dec..178708d34 100644 --- a/google/ads/googleads/v21/services/types/conversion_action_service.py +++ b/google/ads/googleads/v21/services/types/conversion_action_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( conversion_action as gagr_conversion_action, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/conversion_adjustment_upload_service.py b/google/ads/googleads/v21/services/types/conversion_adjustment_upload_service.py index 22cdcdba0..f2604bbf8 100644 --- a/google/ads/googleads/v21/services/types/conversion_adjustment_upload_service.py +++ b/google/ads/googleads/v21/services/types/conversion_adjustment_upload_service.py @@ -21,8 +21,7 @@ from google.ads.googleads.v21.common.types import offline_user_data from google.ads.googleads.v21.enums.types import conversion_adjustment_type -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", @@ -174,7 +173,7 @@ class ConversionAdjustment(proto.Message): adjustment_date_time (str): The date time at which the adjustment occurred. Must be after the conversion_date_time. The timezone must be - specified. The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for + specified. The format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_adjustment_date_time``. @@ -314,7 +313,7 @@ class GclidDateTimePair(proto.Message): conversion_date_time (str): The date time at which the original conversion for this adjustment occurred. The timezone must be specified. The - format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, + format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. @@ -353,7 +352,7 @@ class ConversionAdjustmentResult(proto.Message): This field is a member of `oneof`_ ``_conversion_action``. adjustment_date_time (str): The date time at which the adjustment occurred. The format - is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, "2019-01-01 + is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_adjustment_date_time``. diff --git a/google/ads/googleads/v21/services/types/conversion_custom_variable_service.py b/google/ads/googleads/v21/services/types/conversion_custom_variable_service.py index f0052ce07..79b03de93 100644 --- a/google/ads/googleads/v21/services/types/conversion_custom_variable_service.py +++ b/google/ads/googleads/v21/services/types/conversion_custom_variable_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( conversion_custom_variable as gagr_conversion_custom_variable, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/conversion_goal_campaign_config_service.py b/google/ads/googleads/v21/services/types/conversion_goal_campaign_config_service.py index 910c33a56..ff48229ea 100644 --- a/google/ads/googleads/v21/services/types/conversion_goal_campaign_config_service.py +++ b/google/ads/googleads/v21/services/types/conversion_goal_campaign_config_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( conversion_goal_campaign_config as gagr_conversion_goal_campaign_config, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/conversion_upload_service.py b/google/ads/googleads/v21/services/types/conversion_upload_service.py index c93499d58..0a8de3926 100644 --- a/google/ads/googleads/v21/services/types/conversion_upload_service.py +++ b/google/ads/googleads/v21/services/types/conversion_upload_service.py @@ -23,8 +23,7 @@ from google.ads.googleads.v21.common.types import offline_user_data from google.ads.googleads.v21.enums.types import conversion_customer_type from google.ads.googleads.v21.enums.types import conversion_environment_enum -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", @@ -241,13 +240,11 @@ class ClickConversion(proto.Message): This field is a member of `oneof`_ ``_gclid``. gbraid (str): - The click identifier for clicks associated - with app conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + app conversions. wbraid (str): - The click identifier for clicks associated - with web conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + web conversions. conversion_action (str): Resource name of the conversion action associated with this conversion. Note: Although @@ -260,7 +257,7 @@ class ClickConversion(proto.Message): conversion_date_time (str): The date time at which the conversion occurred. Must be after the click time. The timezone must be specified. The - format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, + format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. @@ -324,7 +321,10 @@ class ClickConversion(proto.Message): consent where required by law or any applicable Google policies. See the https://support.google.com/google-ads/answer/2998031 - page for more details. + page for more details. This field is only + available to allowlisted users. To include this + field in conversion imports, upgrade to the Data + Manager API. This field is a member of `oneof`_ ``_user_ip_address``. session_attributes_encoded (bytes): @@ -332,12 +332,17 @@ class ClickConversion(proto.Message): base64-encoded JSON string. The content should be generated by Google-provided library. To set session attributes individually, use session_attributes_key_value_pairs - instead. + instead. This field is only available to allowlisted users. + To include this field in conversion imports, upgrade to the + Data Manager API. This field is a member of `oneof`_ ``session_attributes``. session_attributes_key_value_pairs (google.ads.googleads.v21.services.types.SessionAttributesKeyValuePairs): The session attributes for the event, - represented as key-value pairs. + represented as key-value pairs. This field is + only available to allowlisted users. To include + this field in conversion imports, upgrade to the + Data Manager API. This field is a member of `oneof`_ ``session_attributes``. """ @@ -456,7 +461,7 @@ class CallConversion(proto.Message): This field is a member of `oneof`_ ``_caller_id``. call_start_date_time (str): The date time at which the call occurred. The timezone must - be specified. The format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", + be specified. The format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_call_start_date_time``. @@ -472,7 +477,7 @@ class CallConversion(proto.Message): conversion_date_time (str): The date time at which the conversion occurred. Must be after the call time. The timezone must be specified. The - format is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, + format is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. @@ -581,13 +586,11 @@ class ClickConversionResult(proto.Message): This field is a member of `oneof`_ ``_gclid``. gbraid (str): - The click identifier for clicks associated - with app conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + app conversions. wbraid (str): - The click identifier for clicks associated - with web conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + web conversions. conversion_action (str): Resource name of the conversion action associated with this conversion. @@ -595,7 +598,7 @@ class ClickConversionResult(proto.Message): This field is a member of `oneof`_ ``_conversion_action``. conversion_date_time (str): The date time at which the conversion occurred. The format - is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, "2019-01-01 + is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. @@ -654,7 +657,7 @@ class CallConversionResult(proto.Message): This field is a member of `oneof`_ ``_caller_id``. call_start_date_time (str): The date time at which the call occurred. The format is - "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, "2019-01-01 + "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_call_start_date_time``. @@ -665,7 +668,7 @@ class CallConversionResult(proto.Message): This field is a member of `oneof`_ ``_conversion_action``. conversion_date_time (str): The date time at which the conversion occurred. The format - is "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, "2019-01-01 + is "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_conversion_date_time``. diff --git a/google/ads/googleads/v21/services/types/conversion_value_rule_service.py b/google/ads/googleads/v21/services/types/conversion_value_rule_service.py index 33a0ffeff..0286adddb 100644 --- a/google/ads/googleads/v21/services/types/conversion_value_rule_service.py +++ b/google/ads/googleads/v21/services/types/conversion_value_rule_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( conversion_value_rule as gagr_conversion_value_rule, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/conversion_value_rule_set_service.py b/google/ads/googleads/v21/services/types/conversion_value_rule_set_service.py index f9e68b536..b4e969e2f 100644 --- a/google/ads/googleads/v21/services/types/conversion_value_rule_set_service.py +++ b/google/ads/googleads/v21/services/types/conversion_value_rule_set_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( conversion_value_rule_set as gagr_conversion_value_rule_set, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/custom_audience_service.py b/google/ads/googleads/v21/services/types/custom_audience_service.py index 3b07a0cee..68a7a1e3a 100644 --- a/google/ads/googleads/v21/services/types/custom_audience_service.py +++ b/google/ads/googleads/v21/services/types/custom_audience_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import custom_audience -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/custom_conversion_goal_service.py b/google/ads/googleads/v21/services/types/custom_conversion_goal_service.py index d5ddea055..40109bc72 100644 --- a/google/ads/googleads/v21/services/types/custom_conversion_goal_service.py +++ b/google/ads/googleads/v21/services/types/custom_conversion_goal_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( custom_conversion_goal as gagr_custom_conversion_goal, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/custom_interest_service.py b/google/ads/googleads/v21/services/types/custom_interest_service.py index b14724a84..0b7bf365c 100644 --- a/google/ads/googleads/v21/services/types/custom_interest_service.py +++ b/google/ads/googleads/v21/services/types/custom_interest_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import custom_interest -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_asset_service.py b/google/ads/googleads/v21/services/types/customer_asset_service.py index 5e52d0bad..f20e956f9 100644 --- a/google/ads/googleads/v21/services/types/customer_asset_service.py +++ b/google/ads/googleads/v21/services/types/customer_asset_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( customer_asset as gagr_customer_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_asset_set_service.py b/google/ads/googleads/v21/services/types/customer_asset_set_service.py index fc50aa648..cfc872f0b 100644 --- a/google/ads/googleads/v21/services/types/customer_asset_set_service.py +++ b/google/ads/googleads/v21/services/types/customer_asset_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( customer_asset_set as gagr_customer_asset_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_client_link_service.py b/google/ads/googleads/v21/services/types/customer_client_link_service.py index ed01ae93e..a2311cfd8 100644 --- a/google/ads/googleads/v21/services/types/customer_client_link_service.py +++ b/google/ads/googleads/v21/services/types/customer_client_link_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import customer_client_link -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_conversion_goal_service.py b/google/ads/googleads/v21/services/types/customer_conversion_goal_service.py index 44189cca0..0d2311ba1 100644 --- a/google/ads/googleads/v21/services/types/customer_conversion_goal_service.py +++ b/google/ads/googleads/v21/services/types/customer_conversion_goal_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import customer_conversion_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_customizer_service.py b/google/ads/googleads/v21/services/types/customer_customizer_service.py index 8121be55d..136b4b6a1 100644 --- a/google/ads/googleads/v21/services/types/customer_customizer_service.py +++ b/google/ads/googleads/v21/services/types/customer_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( customer_customizer as gagr_customer_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_label_service.py b/google/ads/googleads/v21/services/types/customer_label_service.py index 1f103f4c0..8da38fbb3 100644 --- a/google/ads/googleads/v21/services/types/customer_label_service.py +++ b/google/ads/googleads/v21/services/types/customer_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import customer_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_lifecycle_goal_service.py b/google/ads/googleads/v21/services/types/customer_lifecycle_goal_service.py index dc176edc6..8e4cd5325 100644 --- a/google/ads/googleads/v21/services/types/customer_lifecycle_goal_service.py +++ b/google/ads/googleads/v21/services/types/customer_lifecycle_goal_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import customer_lifecycle_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", @@ -36,7 +35,7 @@ class ConfigureCustomerLifecycleGoalsRequest(proto.Message): r"""Request message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v21.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. Attributes: customer_id (str): @@ -113,7 +112,7 @@ class CustomerLifecycleGoalOperation(proto.Message): class ConfigureCustomerLifecycleGoalsResponse(proto.Message): r"""Response message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v21.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. Attributes: result (google.ads.googleads.v21.services.types.ConfigureCustomerLifecycleGoalsResult): diff --git a/google/ads/googleads/v21/services/types/customer_manager_link_service.py b/google/ads/googleads/v21/services/types/customer_manager_link_service.py index 8b5bed30e..207cf8870 100644 --- a/google/ads/googleads/v21/services/types/customer_manager_link_service.py +++ b/google/ads/googleads/v21/services/types/customer_manager_link_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import customer_manager_link -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_negative_criterion_service.py b/google/ads/googleads/v21/services/types/customer_negative_criterion_service.py index b78cbc2ad..f96d7d561 100644 --- a/google/ads/googleads/v21/services/types/customer_negative_criterion_service.py +++ b/google/ads/googleads/v21/services/types/customer_negative_criterion_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( customer_negative_criterion as gagr_customer_negative_criterion, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_service.py b/google/ads/googleads/v21/services/types/customer_service.py index 130672580..f4b6bfc18 100644 --- a/google/ads/googleads/v21/services/types/customer_service.py +++ b/google/ads/googleads/v21/services/types/customer_service.py @@ -24,8 +24,7 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v21.resources.types import customer as gagr_customer -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_sk_ad_network_conversion_value_schema_service.py b/google/ads/googleads/v21/services/types/customer_sk_ad_network_conversion_value_schema_service.py index 801b92a31..5446c4b54 100644 --- a/google/ads/googleads/v21/services/types/customer_sk_ad_network_conversion_value_schema_service.py +++ b/google/ads/googleads/v21/services/types/customer_sk_ad_network_conversion_value_schema_service.py @@ -21,8 +21,7 @@ from google.ads.googleads.v21.resources.types import ( customer_sk_ad_network_conversion_value_schema, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customer_user_access_service.py b/google/ads/googleads/v21/services/types/customer_user_access_service.py index e70c1c477..ad1e67a44 100644 --- a/google/ads/googleads/v21/services/types/customer_user_access_service.py +++ b/google/ads/googleads/v21/services/types/customer_user_access_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import customer_user_access -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/customizer_attribute_service.py b/google/ads/googleads/v21/services/types/customizer_attribute_service.py index 0b368918f..9c0b610f8 100644 --- a/google/ads/googleads/v21/services/types/customizer_attribute_service.py +++ b/google/ads/googleads/v21/services/types/customizer_attribute_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( customizer_attribute as gagr_customizer_attribute, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/experiment_arm_service.py b/google/ads/googleads/v21/services/types/experiment_arm_service.py index 7c47d4065..e8e7e6680 100644 --- a/google/ads/googleads/v21/services/types/experiment_arm_service.py +++ b/google/ads/googleads/v21/services/types/experiment_arm_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( experiment_arm as gagr_experiment_arm, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/experiment_service.py b/google/ads/googleads/v21/services/types/experiment_service.py index 961f51cbb..14cd44818 100644 --- a/google/ads/googleads/v21/services/types/experiment_service.py +++ b/google/ads/googleads/v21/services/types/experiment_service.py @@ -22,9 +22,8 @@ from google.ads.googleads.v21.resources.types import ( experiment as gagr_experiment, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/google_ads_service.py b/google/ads/googleads/v21/services/types/google_ads_service.py index 5015a7080..ed596127f 100644 --- a/google/ads/googleads/v21/services/types/google_ads_service.py +++ b/google/ads/googleads/v21/services/types/google_ads_service.py @@ -624,9 +624,8 @@ smart_campaign_setting_service, ) from google.ads.googleads.v21.services.types import user_list_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/identity_verification_service.py b/google/ads/googleads/v21/services/types/identity_verification_service.py index 09b5d757f..962c2c435 100644 --- a/google/ads/googleads/v21/services/types/identity_verification_service.py +++ b/google/ads/googleads/v21/services/types/identity_verification_service.py @@ -24,7 +24,6 @@ identity_verification_program_status, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.services", marshal="google.ads.googleads.v21", @@ -41,7 +40,7 @@ class StartIdentityVerificationRequest(proto.Message): r"""Request message for - [IdentityVerificationService.StartIdentityVerification]. + [StartIdentityVerification][google.ads.googleads.v21.services.IdentityVerificationService.StartIdentityVerification]. Attributes: customer_id (str): @@ -67,7 +66,7 @@ class StartIdentityVerificationRequest(proto.Message): class GetIdentityVerificationRequest(proto.Message): r"""Request message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v21.services.IdentityVerificationService.GetIdentityVerification]. Attributes: customer_id (str): @@ -83,7 +82,7 @@ class GetIdentityVerificationRequest(proto.Message): class GetIdentityVerificationResponse(proto.Message): r"""Response message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v21.services.IdentityVerificationService.GetIdentityVerification]. Attributes: identity_verification (MutableSequence[google.ads.googleads.v21.services.types.IdentityVerification]): diff --git a/google/ads/googleads/v21/services/types/keyword_plan_ad_group_keyword_service.py b/google/ads/googleads/v21/services/types/keyword_plan_ad_group_keyword_service.py index e56d74ca1..52594f234 100644 --- a/google/ads/googleads/v21/services/types/keyword_plan_ad_group_keyword_service.py +++ b/google/ads/googleads/v21/services/types/keyword_plan_ad_group_keyword_service.py @@ -22,9 +22,8 @@ from google.ads.googleads.v21.resources.types import ( keyword_plan_ad_group_keyword, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/keyword_plan_ad_group_service.py b/google/ads/googleads/v21/services/types/keyword_plan_ad_group_service.py index e25d6d005..7a2001e86 100644 --- a/google/ads/googleads/v21/services/types/keyword_plan_ad_group_service.py +++ b/google/ads/googleads/v21/services/types/keyword_plan_ad_group_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import keyword_plan_ad_group -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/keyword_plan_campaign_keyword_service.py b/google/ads/googleads/v21/services/types/keyword_plan_campaign_keyword_service.py index 2c2caf9cb..4f9eac289 100644 --- a/google/ads/googleads/v21/services/types/keyword_plan_campaign_keyword_service.py +++ b/google/ads/googleads/v21/services/types/keyword_plan_campaign_keyword_service.py @@ -22,9 +22,8 @@ from google.ads.googleads.v21.resources.types import ( keyword_plan_campaign_keyword, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/keyword_plan_campaign_service.py b/google/ads/googleads/v21/services/types/keyword_plan_campaign_service.py index fa8fea1a9..de2b397fc 100644 --- a/google/ads/googleads/v21/services/types/keyword_plan_campaign_service.py +++ b/google/ads/googleads/v21/services/types/keyword_plan_campaign_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import keyword_plan_campaign -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/keyword_plan_idea_service.py b/google/ads/googleads/v21/services/types/keyword_plan_idea_service.py index f1b9db920..1c3f00280 100644 --- a/google/ads/googleads/v21/services/types/keyword_plan_idea_service.py +++ b/google/ads/googleads/v21/services/types/keyword_plan_idea_service.py @@ -28,7 +28,6 @@ keyword_plan_network as gage_keyword_plan_network, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.services", marshal="google.ads.googleads.v21", @@ -664,8 +663,8 @@ class UnusableAdGroup(proto.Message): AdGroups may not be usable if the AdGroup - - belongs to a Campaign that is not ENABLED or PAUSED - - is itself not ENABLED + - belongs to a Campaign that is not ENABLED or PAUSED + - is itself not ENABLED Attributes: ad_group (str): @@ -688,7 +687,7 @@ class UnusableAdGroup(proto.Message): class GenerateKeywordForecastMetricsRequest(proto.Message): r"""Request message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v21.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -1049,7 +1048,7 @@ class MaximizeConversionsBiddingStrategy(proto.Message): class GenerateKeywordForecastMetricsResponse(proto.Message): r"""Response message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v21.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v21/services/types/keyword_plan_service.py b/google/ads/googleads/v21/services/types/keyword_plan_service.py index ba44d526d..624bdb117 100644 --- a/google/ads/googleads/v21/services/types/keyword_plan_service.py +++ b/google/ads/googleads/v21/services/types/keyword_plan_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import keyword_plan -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/label_service.py b/google/ads/googleads/v21/services/types/label_service.py index 029034f42..ad47a6290 100644 --- a/google/ads/googleads/v21/services/types/label_service.py +++ b/google/ads/googleads/v21/services/types/label_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v21.resources.types import label as gagr_label -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/local_services_lead_service.py b/google/ads/googleads/v21/services/types/local_services_lead_service.py index 98f9feeed..9020ba05a 100644 --- a/google/ads/googleads/v21/services/types/local_services_lead_service.py +++ b/google/ads/googleads/v21/services/types/local_services_lead_service.py @@ -31,8 +31,7 @@ from google.ads.googleads.v21.enums.types import ( local_services_lead_survey_satisfied_reason, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/offline_user_data_job_service.py b/google/ads/googleads/v21/services/types/offline_user_data_job_service.py index 4307f53e9..f9354a5aa 100644 --- a/google/ads/googleads/v21/services/types/offline_user_data_job_service.py +++ b/google/ads/googleads/v21/services/types/offline_user_data_job_service.py @@ -21,8 +21,7 @@ from google.ads.googleads.v21.common.types import offline_user_data from google.ads.googleads.v21.resources.types import offline_user_data_job -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/product_link_invitation_service.py b/google/ads/googleads/v21/services/types/product_link_invitation_service.py index 343e9208d..725574645 100644 --- a/google/ads/googleads/v21/services/types/product_link_invitation_service.py +++ b/google/ads/googleads/v21/services/types/product_link_invitation_service.py @@ -25,7 +25,6 @@ product_link_invitation as gagr_product_link_invitation, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.services", marshal="google.ads.googleads.v21", @@ -129,7 +128,7 @@ class UpdateProductLinkInvitationResponse(proto.Message): class RemoveProductLinkInvitationRequest(proto.Message): r"""Request message for - [ProductLinkinvitationService.RemoveProductLinkInvitation][]. + [ProductLinkInvitationService.RemoveProductLinkInvitation][google.ads.googleads.v21.services.ProductLinkInvitationService.RemoveProductLinkInvitation]. Attributes: customer_id (str): @@ -139,7 +138,7 @@ class RemoveProductLinkInvitationRequest(proto.Message): Required. The resource name of the product link invitation being removed. expected, in this format: - ```` + ``customers/{customer_id}/productLinkInvitations/{product_link_invitation_id}`` """ customer_id: str = proto.Field( diff --git a/google/ads/googleads/v21/services/types/reach_plan_service.py b/google/ads/googleads/v21/services/types/reach_plan_service.py index cb4c6a709..ee4313dc8 100644 --- a/google/ads/googleads/v21/services/types/reach_plan_service.py +++ b/google/ads/googleads/v21/services/types/reach_plan_service.py @@ -38,7 +38,6 @@ user_list_type as gage_user_list_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.services", marshal="google.ads.googleads.v21", @@ -1450,10 +1449,10 @@ class OnTargetAudienceMetrics(proto.Message): r"""Audience metrics for the planned products. These metrics consider the following targeting dimensions: - - Location - - PlannableAgeRange - - Gender - - AudienceTargeting (only for youtube_audience_size) + - Location + - PlannableAgeRange + - Gender + - AudienceTargeting (only for youtube_audience_size) .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v21/services/types/recommendation_service.py b/google/ads/googleads/v21/services/types/recommendation_service.py index b4f739b11..def78879c 100644 --- a/google/ads/googleads/v21/services/types/recommendation_service.py +++ b/google/ads/googleads/v21/services/types/recommendation_service.py @@ -39,8 +39,7 @@ from google.ads.googleads.v21.resources.types import ad as gagr_ad from google.ads.googleads.v21.resources.types import asset from google.ads.googleads.v21.resources.types import recommendation -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/recommendation_subscription_service.py b/google/ads/googleads/v21/services/types/recommendation_subscription_service.py index c21b55627..e3f060910 100644 --- a/google/ads/googleads/v21/services/types/recommendation_subscription_service.py +++ b/google/ads/googleads/v21/services/types/recommendation_subscription_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( recommendation_subscription as gagr_recommendation_subscription, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", @@ -43,7 +42,7 @@ class MutateRecommendationSubscriptionRequest(proto.Message): r"""Request message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v21.services.RecommendationSubscriptionService.MutateRecommendationSubscription] Attributes: customer_id (str): @@ -100,7 +99,7 @@ class MutateRecommendationSubscriptionRequest(proto.Message): class RecommendationSubscriptionOperation(proto.Message): r"""A single operation (create, update) on a recommendation subscription. - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v21.services.RecommendationSubscriptionService.MutateRecommendationSubscription] This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -150,7 +149,7 @@ class RecommendationSubscriptionOperation(proto.Message): class MutateRecommendationSubscriptionResponse(proto.Message): r"""Response message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v21.services.RecommendationSubscriptionService.MutateRecommendationSubscription] Attributes: results (MutableSequence[google.ads.googleads.v21.services.types.MutateRecommendationSubscriptionResult]): @@ -179,7 +178,7 @@ class MutateRecommendationSubscriptionResponse(proto.Message): class MutateRecommendationSubscriptionResult(proto.Message): r"""Result message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v21.services.RecommendationSubscriptionService.MutateRecommendationSubscription] Attributes: resource_name (str): diff --git a/google/ads/googleads/v21/services/types/remarketing_action_service.py b/google/ads/googleads/v21/services/types/remarketing_action_service.py index 8160eac2d..8bd6afedd 100644 --- a/google/ads/googleads/v21/services/types/remarketing_action_service.py +++ b/google/ads/googleads/v21/services/types/remarketing_action_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import remarketing_action -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/shareable_preview_service.py b/google/ads/googleads/v21/services/types/shareable_preview_service.py index 5dfd7b017..2c43d01af 100644 --- a/google/ads/googleads/v21/services/types/shareable_preview_service.py +++ b/google/ads/googleads/v21/services/types/shareable_preview_service.py @@ -19,8 +19,7 @@ import proto # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/shared_criterion_service.py b/google/ads/googleads/v21/services/types/shared_criterion_service.py index ce560ec31..086877572 100644 --- a/google/ads/googleads/v21/services/types/shared_criterion_service.py +++ b/google/ads/googleads/v21/services/types/shared_criterion_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v21.resources.types import ( shared_criterion as gagr_shared_criterion, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/shared_set_service.py b/google/ads/googleads/v21/services/types/shared_set_service.py index ddaf1b400..72476c6f8 100644 --- a/google/ads/googleads/v21/services/types/shared_set_service.py +++ b/google/ads/googleads/v21/services/types/shared_set_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v21.resources.types import ( shared_set as gagr_shared_set, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/smart_campaign_setting_service.py b/google/ads/googleads/v21/services/types/smart_campaign_setting_service.py index 13085d5bc..177cc8076 100644 --- a/google/ads/googleads/v21/services/types/smart_campaign_setting_service.py +++ b/google/ads/googleads/v21/services/types/smart_campaign_setting_service.py @@ -31,9 +31,8 @@ from google.ads.googleads.v21.resources.types import ( smart_campaign_setting as gagr_smart_campaign_setting, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/smart_campaign_suggest_service.py b/google/ads/googleads/v21/services/types/smart_campaign_suggest_service.py index dff4b2506..104cce1f2 100644 --- a/google/ads/googleads/v21/services/types/smart_campaign_suggest_service.py +++ b/google/ads/googleads/v21/services/types/smart_campaign_suggest_service.py @@ -25,7 +25,6 @@ keyword_theme_constant as gagr_keyword_theme_constant, ) - __protobuf__ = proto.module( package="google.ads.googleads.v21.services", marshal="google.ads.googleads.v21", @@ -355,13 +354,13 @@ class SuggestKeywordThemesRequest(proto.Message): Required. Information to get keyword theme suggestions. Required fields: - - suggestion_info.final_url - - suggestion_info.language_code - - suggestion_info.geo_target + - suggestion_info.final_url + - suggestion_info.language_code + - suggestion_info.geo_target Recommended fields: - - suggestion_info.business_setting + - suggestion_info.business_setting """ customer_id: str = proto.Field( diff --git a/google/ads/googleads/v21/services/types/user_data_service.py b/google/ads/googleads/v21/services/types/user_data_service.py index e74aeb46d..b2bc18056 100644 --- a/google/ads/googleads/v21/services/types/user_data_service.py +++ b/google/ads/googleads/v21/services/types/user_data_service.py @@ -21,7 +21,6 @@ from google.ads.googleads.v21.common.types import offline_user_data - __protobuf__ = proto.module( package="google.ads.googleads.v21.services", marshal="google.ads.googleads.v21", @@ -122,7 +121,7 @@ class UploadUserDataResponse(proto.Message): Attributes: upload_date_time (str): The date time at which the request was received by API, - formatted as "yyyy-mm-dd hh:mm:ss+|-hh:mm", for example, + formatted as "yyyy-mm-dd hh:mm:ss+\|-hh:mm", for example, "2019-01-01 12:32:45-08:00". This field is a member of `oneof`_ ``_upload_date_time``. diff --git a/google/ads/googleads/v21/services/types/user_list_customer_type_service.py b/google/ads/googleads/v21/services/types/user_list_customer_type_service.py index edc4bc806..5a0cf513d 100644 --- a/google/ads/googleads/v21/services/types/user_list_customer_type_service.py +++ b/google/ads/googleads/v21/services/types/user_list_customer_type_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import user_list_customer_type -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v21/services/types/user_list_service.py b/google/ads/googleads/v21/services/types/user_list_service.py index 72473f0cc..216115b56 100644 --- a/google/ads/googleads/v21/services/types/user_list_service.py +++ b/google/ads/googleads/v21/services/types/user_list_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v21.resources.types import user_list -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v21.services", diff --git a/google/ads/googleads/v22/__init__.py b/google/ads/googleads/v22/__init__.py index 821a9a227..c4583821b 100644 --- a/google/ads/googleads/v22/__init__.py +++ b/google/ads/googleads/v22/__init__.py @@ -15,14 +15,117 @@ # from google.ads.googleads.v22 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from . import common from . import enums from . import errors from . import resources from . import services +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v22") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v22") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v22" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( "common", diff --git a/google/ads/googleads/v22/common/__init__.py b/google/ads/googleads/v22/common/__init__.py index 0acf1cad8..bdc363479 100644 --- a/google/ads/googleads/v22/common/__init__.py +++ b/google/ads/googleads/v22/common/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v22 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.ad_asset import AdAppDeepLinkAsset from .types.ad_asset import AdCallToActionAsset @@ -380,6 +390,100 @@ from .types.user_lists import UserListStringRuleItemInfo from .types.value import Value +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v22") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v22") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v22" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "ActivityCityInfo", "ActivityCountryInfo", diff --git a/google/ads/googleads/v22/common/types/additional_application_info.py b/google/ads/googleads/v22/common/types/additional_application_info.py index 3c614e244..b1721dfc2 100644 --- a/google/ads/googleads/v22/common/types/additional_application_info.py +++ b/google/ads/googleads/v22/common/types/additional_application_info.py @@ -22,7 +22,6 @@ application_instance as gage_application_instance, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.common", marshal="google.ads.googleads.v22", @@ -34,8 +33,12 @@ class AdditionalApplicationInfo(proto.Message): r"""Additional information about the application/tool issuing the - request. This field is only used by [ContentCreatorInsightsService], - [AudienceInsightsService], and [ReachPlanService] APIs. + request. This field is only used by + [ContentCreatorInsightsService][google.ads.googleads.v22.services.ContentCreatorInsightsService], + [AudienceInsightsService][google.ads.googleads.v22.services.AudienceInsightsService], + and + [ReachPlanService][google.ads.googleads.v22.services.ReachPlanService] + APIs. Attributes: application_id (str): diff --git a/google/ads/googleads/v22/common/types/audience_insights_attribute.py b/google/ads/googleads/v22/common/types/audience_insights_attribute.py index 1405e4a03..0060f3cbc 100644 --- a/google/ads/googleads/v22/common/types/audience_insights_attribute.py +++ b/google/ads/googleads/v22/common/types/audience_insights_attribute.py @@ -29,7 +29,6 @@ ) from google.ads.googleads.v22.enums.types import youtube_video_property - __protobuf__ = proto.module( package="google.ads.googleads.v22.common", marshal="google.ads.googleads.v22", @@ -206,7 +205,7 @@ class AudienceInsightsAttributeMetadata(proto.Message): class AudienceInsightsAttribute(proto.Message): r"""An audience attribute that can be used to request insights about the audience. Valid inputs for these fields are available from - [AudienceInsightsService.ListAudienceInsightsAttributes][]. + [AudienceInsightsService.ListAudienceInsightsAttributes][google.ads.googleads.v22.services.AudienceInsightsService.ListAudienceInsightsAttributes]. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -593,7 +592,7 @@ class KnowledgeGraphAttributeMetadata(proto.Message): Attributes: entity_capabilities (MutableSequence[google.ads.googleads.v22.enums.types.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities]): The capabilities of the entity used in - [ContentCreatorInsightsService][]. + [ContentCreatorInsightsService][google.ads.googleads.v22.services.ContentCreatorInsightsService]. related_categories (MutableSequence[google.ads.googleads.v22.common.types.AudienceInsightsAttributeMetadata]): A list of CATEGORY attributes related to this entity. diff --git a/google/ads/googleads/v22/common/types/criteria.py b/google/ads/googleads/v22/common/types/criteria.py index 28bd3f32e..678afec5d 100644 --- a/google/ads/googleads/v22/common/types/criteria.py +++ b/google/ads/googleads/v22/common/types/criteria.py @@ -51,7 +51,6 @@ from google.ads.googleads.v22.enums.types import webpage_condition_operand from google.ads.googleads.v22.enums.types import webpage_condition_operator - __protobuf__ = proto.module( package="google.ads.googleads.v22.common", marshal="google.ads.googleads.v22", @@ -1648,19 +1647,37 @@ class LanguageInfo(proto.Message): class IpBlockInfo(proto.Message): - r"""An IpBlock criterion used for IP exclusions. We allow: + r"""An IpBlock criterion used for excluding IP addresses. + + We support excluding individual IP addresses or CIDR blocks. Create + one IpBlockInfo criterion for each individual IP address or CIDR + block you want to exclude. You can exclude up to 500 IP addresses + per campaign. For more details, see `Exclude IP + addresses `__. + + IPv4 examples: + + - Individual address: 192.168.0.1 + + - Individual address as CIDR block: 192.168.0.1/32 + + - CIDR block: 192.168.0.0/24 + + IPv6 examples: + + - Individual address: 2001:db8:a0b:12f0::1 + + - Individual address as CIDR block: 2001:db8:a0b:12f0::1/128 - - IPv4 and IPv6 addresses - - individual addresses (192.168.0.1) - - masks for individual addresses (192.168.0.1/32) - - masks for Class C networks (192.168.0.1/24) + - CIDR block: 2001:db8::/48 .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: ip_address (str): - The IP address of this IP block. + The IP address or the CIDR block to be + excluded. This field is a member of `oneof`_ ``_ip_address``. """ diff --git a/google/ads/googleads/v22/common/types/metrics.py b/google/ads/googleads/v22/common/types/metrics.py index 3cff8aa67..534532b90 100644 --- a/google/ads/googleads/v22/common/types/metrics.py +++ b/google/ads/googleads/v22/common/types/metrics.py @@ -22,7 +22,6 @@ from google.ads.googleads.v22.enums.types import interaction_event_type from google.ads.googleads.v22.enums.types import quality_score_bucket - __protobuf__ = proto.module( package="google.ads.googleads.v22.common", marshal="google.ads.googleads.v22", @@ -140,18 +139,18 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_value_per_cost``. all_conversions_from_click_to_call (float): The number of times people clicked the "Call" - button to call a store during or after clicking - an ad. This number doesn't include whether or - not calls were connected, or the duration of any - calls. + button to call a business during or after + clicking an ad. This number doesn't include + whether or not calls were connected, or the + duration of any calls. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_click_to_call``. all_conversions_from_directions (float): The number of times people clicked a "Get - directions" button to navigate to a store after - clicking an ad. + directions" button to navigate to a business + after clicking an ad. This metric applies to feed items only. @@ -164,34 +163,36 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_from_interactions_value_per_interaction``. all_conversions_from_menu (float): The number of times people clicked a link to - view a store's menu after clicking an ad. + view a business's menu after clicking an ad. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_menu``. all_conversions_from_order (float): The number of times people placed an order at - a store after clicking an ad. + a business after clicking an ad. + This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_order``. all_conversions_from_other_engagement (float): The number of other conversions (for example, posting a review or saving a location for a - store) that occurred after people clicked an ad. + business) that occurred after people clicked an + ad. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_other_engagement``. all_conversions_from_store_visit (float): Estimated number of times people visited a - store after clicking an ad. + business after clicking an ad. This metric applies to feed items only. This field is a member of `oneof`_ ``_all_conversions_from_store_visit``. all_conversions_from_store_website (float): The number of times that people were taken to - a store's URL after clicking an ad. + a business's URL after clicking an ad. This metric applies to feed items only. @@ -638,8 +639,8 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_gmail_secondary_clicks``. impressions_from_store_reach (int): - The number of times a store's location-based - ad was shown. + The number of times a business's + location-based ad was shown. This metric applies to feed items only. This field is a member of `oneof`_ ``_impressions_from_store_reach``. @@ -1091,10 +1092,10 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_from_location_asset_other_engagement``. all_conversions_from_location_asset_store_visits (float): - Estimated number of visits to the store after - a chargeable ad event (click or impression). - This measure is coming from Asset based - location. + Estimated number of visits to the business + after a chargeable ad event (click or + impression). This measure is coming from Asset + based location. This field is a member of `oneof`_ ``_all_conversions_from_location_asset_store_visits``. all_conversions_from_location_asset_website (float): @@ -1105,7 +1106,7 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_all_conversions_from_location_asset_website``. eligible_impressions_from_location_asset_store_reach (int): - Number of impressions in which the store + Number of impressions in which the business location was shown or the location was used for targeting. This measure is coming from Asset based location. @@ -1143,9 +1144,9 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_view_through_conversions_from_location_asset_other_engagement``. view_through_conversions_from_location_asset_store_visits (float): - Estimated number of visits to the store after - an impression. This measure is coming from Asset - based location. + Estimated number of visits to the business + after an impression. This measure is coming from + Asset based location. This field is a member of `oneof`_ ``_view_through_conversions_from_location_asset_store_visits``. view_through_conversions_from_location_asset_website (float): @@ -1684,8 +1685,8 @@ class Metrics(proto.Message): This field is a member of `oneof`_ ``_asset_unrated_performance_cost_percentage``. store_visits_last_click_model_attributed_conversions (float): - The amount of store visits attributed by the - last click model. + The amount of business visits attributed by + the last click model. This field is a member of `oneof`_ ``_store_visits_last_click_model_attributed_conversions``. results_conversions_purchase (float): diff --git a/google/ads/googleads/v22/common/types/policy.py b/google/ads/googleads/v22/common/types/policy.py index efd96391a..25c5de710 100644 --- a/google/ads/googleads/v22/common/types/policy.py +++ b/google/ads/googleads/v22/common/types/policy.py @@ -30,7 +30,6 @@ policy_topic_evidence_destination_not_working_dns_error_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.common", marshal="google.ads.googleads.v22", @@ -84,27 +83,32 @@ class PolicyValidationParameter(proto.Message): Attributes: ignorable_policy_topics (MutableSequence[str]): - The list of policy topics that should not - cause a PolicyFindingError to be reported. This - field is currently only compatible with Enhanced - Text Ad. It corresponds to the - PolicyTopicEntry.topic field. - - Resources violating these policies will be - saved, but will not be eligible to serve. They - may begin serving at a later time due to a - change in policies, re-review of the resource, - or a change in advertiser certificates. + The list of policy topics that should not cause a + ``PolicyFindingError`` to be reported. This field is used + for ad policy exemptions. It corresponds to the + ``PolicyTopicEntry.topic`` field. + + If this field is populated, then + ``exempt_policy_violation_keys`` must be empty. + + Resources that violate these policies will be saved, but + will not be eligible to serve. They may begin serving at a + later time due to a change in policies, re-review of the + resource, or a change in advertiser certificates. exempt_policy_violation_keys (MutableSequence[google.ads.googleads.v22.common.types.PolicyViolationKey]): The list of policy violation keys that should not cause a - PolicyViolationError to be reported. Not all policy - violations are exemptable, refer to the is_exemptible field - in the returned PolicyViolationError. - - Resources violating these polices will be saved, but will - not be eligible to serve. They may begin serving at a later - time due to a change in policies, re-review of the resource, - or a change in advertiser certificates. + ``PolicyViolationError`` to be reported. Not all policy + violations are exemptable. Refer to the ``is_exemptible`` + field in the returned ``PolicyViolationError``. This field + is used for keyword policy exemptions. + + If this field is populated, then ``ignorable_policy_topics`` + must be empty. + + Resources that violate these policies will be saved, but + will not be eligible to serve. They may begin serving at a + later time due to a change in policies, re-review of the + resource, or a change in advertiser certificates. """ ignorable_policy_topics: MutableSequence[str] = proto.RepeatedField( diff --git a/google/ads/googleads/v22/enums/__init__.py b/google/ads/googleads/v22/enums/__init__.py index 3cee39bdf..b9a11f2d7 100644 --- a/google/ads/googleads/v22/enums/__init__.py +++ b/google/ads/googleads/v22/enums/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v22 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.access_invitation_status import AccessInvitationStatusEnum from .types.access_reason import AccessReasonEnum @@ -577,6 +587,100 @@ from .types.webpage_condition_operator import WebpageConditionOperatorEnum from .types.youtube_video_property import YouTubeVideoPropertyEnum +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v22") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v22") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v22" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "AccessInvitationStatusEnum", "AccessReasonEnum", diff --git a/google/ads/googleads/v22/enums/types/insights_knowledge_graph_entity_capabilities.py b/google/ads/googleads/v22/enums/types/insights_knowledge_graph_entity_capabilities.py index 1768cc2eb..1b72247ec 100644 --- a/google/ads/googleads/v22/enums/types/insights_knowledge_graph_entity_capabilities.py +++ b/google/ads/googleads/v22/enums/types/insights_knowledge_graph_entity_capabilities.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v22.enums", marshal="google.ads.googleads.v22", @@ -44,10 +43,10 @@ class InsightsKnowledgeGraphEntityCapabilities(proto.Enum): The value is unknown in this version. CONTENT_TRENDING_INSIGHTS (2): An entity that is supported to use as a trending topic in - [ContentCreatorInsightsService.GenerateTrendingInsights]. + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v22.services.ContentCreatorInsightsService.GenerateTrendingInsights]. CREATOR_ATTRIBUTE (3): An entity that is supported to use as a creator attribute in - [ContentCreatorInsightsService.GenerateCreatorInsights]. + [ContentCreatorInsightsService.GenerateCreatorInsights][google.ads.googleads.v22.services.ContentCreatorInsightsService.GenerateCreatorInsights]. """ UNSPECIFIED = 0 diff --git a/google/ads/googleads/v22/enums/types/offline_user_data_job_status.py b/google/ads/googleads/v22/enums/types/offline_user_data_job_status.py index 26faa4da9..1d2aa7563 100644 --- a/google/ads/googleads/v22/enums/types/offline_user_data_job_status.py +++ b/google/ads/googleads/v22/enums/types/offline_user_data_job_status.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v22.enums", marshal="google.ads.googleads.v22", @@ -51,9 +50,15 @@ class OfflineUserDataJobStatus(proto.Enum): being processed. SUCCESS (4): Uploaded data has been successfully - processed. + processed. The job might have no operations, + which can happen if the job was run without any + operations added, or if all operations failed + validation individually when attempting to add + them to the job. FAILED (5): Uploaded data has failed to be processed. + Some operations may have been successfully + processed. """ UNSPECIFIED = 0 diff --git a/google/ads/googleads/v22/errors/__init__.py b/google/ads/googleads/v22/errors/__init__.py index 3a08be0ee..480640b74 100644 --- a/google/ads/googleads/v22/errors/__init__.py +++ b/google/ads/googleads/v22/errors/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v22 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.access_invitation_error import AccessInvitationErrorEnum from .types.account_budget_proposal_error import AccountBudgetProposalErrorEnum @@ -232,6 +242,100 @@ YoutubeVideoRegistrationErrorEnum, ) +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v22") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v22") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v22" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "AccessInvitationErrorEnum", "AccountBudgetProposalErrorEnum", diff --git a/google/ads/googleads/v22/errors/types/errors.py b/google/ads/googleads/v22/errors/types/errors.py index e36f283c0..ae5c41059 100644 --- a/google/ads/googleads/v22/errors/types/errors.py +++ b/google/ads/googleads/v22/errors/types/errors.py @@ -495,8 +495,7 @@ from google.ads.googleads.v22.errors.types import ( youtube_video_registration_error as gage_youtube_video_registration_error, ) -from google.protobuf import duration_pb2 # type: ignore - +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.errors", diff --git a/google/ads/googleads/v22/errors/types/mutate_error.py b/google/ads/googleads/v22/errors/types/mutate_error.py index a118baf57..f95020c8f 100644 --- a/google/ads/googleads/v22/errors/types/mutate_error.py +++ b/google/ads/googleads/v22/errors/types/mutate_error.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v22.errors", marshal="google.ads.googleads.v22", @@ -62,6 +61,10 @@ class MutateError(proto.Enum): This operation cannot be used with "partial_failure". RESOURCE_READ_ONLY (13): Attempt to write to read-only fields. + EU_POLITICAL_ADVERTISING_DECLARATION_REQUIRED (17): + Mutates are generally not allowed if the + customer contains non-exempt campaigns without + the EU political advertising declaration. """ UNSPECIFIED = 0 @@ -75,6 +78,7 @@ class MutateError(proto.Enum): RESOURCE_DOES_NOT_SUPPORT_VALIDATE_ONLY = 12 OPERATION_DOES_NOT_SUPPORT_PARTIAL_FAILURE = 16 RESOURCE_READ_ONLY = 13 + EU_POLITICAL_ADVERTISING_DECLARATION_REQUIRED = 17 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v22/resources/__init__.py b/google/ads/googleads/v22/resources/__init__.py index 3ffadc3b5..f87ee709b 100644 --- a/google/ads/googleads/v22/resources/__init__.py +++ b/google/ads/googleads/v22/resources/__init__.py @@ -15,8 +15,18 @@ # from google.ads.googleads.v22 import gapic_version as package_version +import google.api_core as api_core +import sys + __version__ = package_version.__version__ +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + from .types.accessible_bidding_strategy import AccessibleBiddingStrategy from .types.account_budget import AccountBudget @@ -311,6 +321,100 @@ from .types.video import Video from .types.webpage_view import WebpageView +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.ads.googleads.v22") # type: ignore + api_core.check_dependency_versions("google.ads.googleads.v22") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.ads.googleads.v22" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + _version_used, _version_used_string = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + __all__ = ( "AccessibleBiddingStrategy", "AccountBudget", diff --git a/google/ads/googleads/v22/resources/types/ad_group.py b/google/ads/googleads/v22/resources/types/ad_group.py index f0a6d5b9e..1eadea193 100644 --- a/google/ads/googleads/v22/resources/types/ad_group.py +++ b/google/ads/googleads/v22/resources/types/ad_group.py @@ -35,7 +35,6 @@ from google.ads.googleads.v22.enums.types import demand_gen_channel_strategy from google.ads.googleads.v22.enums.types import targeting_dimension - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -109,7 +108,12 @@ class AdGroup(proto.Message): This field is a member of `oneof`_ ``_campaign``. cpc_bid_micros (int): - The maximum CPC (cost-per-click) bid. + The maximum CPC (cost-per-click) bid. This + field is used when the ad group's effective + bidding strategy is Manual CPC. This field is + not applicable and will be ignored if the ad + group's campaign is using a portfolio bidding + strategy. This field is a member of `oneof`_ ``_cpc_bid_micros``. effective_cpc_bid_micros (int): @@ -145,12 +149,24 @@ class AdGroup(proto.Message): This field is a member of `oneof`_ ``_target_cpm_micros``. target_roas (float): - The target ROAS (return-on-ad-spend) override. If the ad - group's campaign bidding strategy is TargetRoas or - MaximizeConversionValue (with its target_roas field set), - then this field overrides the target ROAS specified in the - campaign's bidding strategy. Otherwise, this value is - ignored. + The target ROAS (return-on-ad-spend) for this ad group. + + This field lets you override the target ROAS specified in + the campaign's bidding strategy, but only if the campaign is + using a standard (not portfolio) ``TargetRoas`` strategy or + a standard ``MaximizeConversionValue`` strategy with its + ``target_roas`` field set. + + If the campaign is using a portfolio bidding strategy, this + field cannot be set and attempting to do so will result in + an error. + + For any other bidding strategies, this value is ignored. + + To see the actual target ROAS being used by the ad group, + considering potential overrides, query the + ``effective_target_roas`` and + ``effective_target_roas_source`` fields. This field is a member of `oneof`_ ``_target_roas``. percent_cpc_bid_micros (int): @@ -188,7 +204,7 @@ class AdGroup(proto.Message): optimized_targeting_enabled is false, this field is ignored. Default is false. display_custom_bid_dimension (google.ads.googleads.v22.enums.types.TargetingDimensionEnum.TargetingDimension): - Allows advertisers to specify a targeting + Lets advertisers specify a targeting dimension on which to place absolute bids. This is only applicable for campaigns that target only the display network and not search. diff --git a/google/ads/googleads/v22/resources/types/ad_group_ad_asset_view.py b/google/ads/googleads/v22/resources/types/ad_group_ad_asset_view.py index 28c9989fa..369dbc167 100644 --- a/google/ads/googleads/v22/resources/types/ad_group_ad_asset_view.py +++ b/google/ads/googleads/v22/resources/types/ad_group_ad_asset_view.py @@ -27,7 +27,6 @@ from google.ads.googleads.v22.enums.types import policy_review_status from google.ads.googleads.v22.enums.types import served_asset_field_type - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -39,9 +38,17 @@ class AdGroupAdAssetView(proto.Message): - r"""A link between an AdGroupAd and an Asset. AdGroupAdAssetView - supports AppAds, Demand Gen campaigns, and Responsive Search - Ads. + r"""Represents a link between an AdGroupAd and an Asset. This view + provides insights into the performance of assets within specific + ads. + + AdGroupAdAssetView supports the following ad types: + + - App Ads + - Demand Gen campaigns + - Responsive Search Ads + + It does not support Responsive Display Ads. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v22/resources/types/ad_group_bid_modifier.py b/google/ads/googleads/v22/resources/types/ad_group_bid_modifier.py index 6d7dc903e..ee33420af 100644 --- a/google/ads/googleads/v22/resources/types/ad_group_bid_modifier.py +++ b/google/ads/googleads/v22/resources/types/ad_group_bid_modifier.py @@ -23,7 +23,6 @@ bid_modifier_source as gage_bid_modifier_source, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -63,9 +62,7 @@ class AdGroupBidModifier(proto.Message): bid_modifier (float): The modifier for the bid when the criterion matches. The modifier must be in the range: 0.1 - - 10.0. The range is 1.0 - 6.0 for - PreferredContent. Use 0 to opt out of a Device - type. + - 10.0. Use 0 to opt out of a Device type. This field is a member of `oneof`_ ``_bid_modifier``. base_ad_group (str): diff --git a/google/ads/googleads/v22/resources/types/ad_group_simulation.py b/google/ads/googleads/v22/resources/types/ad_group_simulation.py index 8f78a3dfc..69245fa4f 100644 --- a/google/ads/googleads/v22/resources/types/ad_group_simulation.py +++ b/google/ads/googleads/v22/resources/types/ad_group_simulation.py @@ -22,7 +22,6 @@ from google.ads.googleads.v22.enums.types import simulation_modification_method from google.ads.googleads.v22.enums.types import simulation_type - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -38,11 +37,17 @@ class AdGroupSimulation(proto.Message): detailed below respectively. 1. SEARCH - CPC_BID - DEFAULT + 2. SEARCH - CPC_BID - UNIFORM + 3. SEARCH - TARGET_CPA - UNIFORM + 4. SEARCH - TARGET_ROAS - UNIFORM + 5. DISPLAY - CPC_BID - DEFAULT + 6. DISPLAY - CPC_BID - UNIFORM + 7. DISPLAY - TARGET_CPA - UNIFORM This message has `oneof`_ fields (mutually exclusive fields). diff --git a/google/ads/googleads/v22/resources/types/campaign.py b/google/ads/googleads/v22/resources/types/campaign.py index 0b4e06247..5ca8299d4 100644 --- a/google/ads/googleads/v22/resources/types/campaign.py +++ b/google/ads/googleads/v22/resources/types/campaign.py @@ -102,7 +102,6 @@ video_ad_sequence_minimum_duration, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -430,6 +429,15 @@ class Campaign(proto.Message): feed_types (MutableSequence[google.ads.googleads.v22.enums.types.AssetSetTypeEnum.AssetSetType]): Output only. Types of feeds that are attached directly to this campaign. + missing_eu_political_advertising_declaration (bool): + Output only. Indicates whether this campaign is missing a + declaration about whether it contains political advertising + targeted towards the EU and is ineligible for any + exemptions. If this field is true, use the + contains_eu_political_advertising field to add the required + declaration. + + This field is read-only. bidding_strategy (str): The resource name of the portfolio bidding strategy used by the campaign. @@ -704,11 +712,15 @@ class ShoppingSetting(proto.Message): This field is a member of `oneof`_ ``_merchant_id``. feed_label (str): - Feed label of products to include in the campaign. Only one - of feed_label or sales_country can be set. If used instead - of sales_country, the feed_label field accepts country codes - in the same format for example: 'XX'. Otherwise can be any - string used for feed label in Google Merchant Center. + Feed label of products to include in the campaign. Valid + feed labels may contain a maximum of 20 characters including + uppercase letters, numbers, hyphens, and underscores. If you + previously used the deprecated ``sales_country`` in the + two-letter country code (``XX``) format, the ``feed_label`` + field should be used instead. For more information see the + `feed + label `__ + support article. campaign_priority (int): Priority of the campaign. Campaigns with numerically higher priorities take precedence @@ -1822,6 +1834,10 @@ class AiMaxBundlingRequired(proto.Enum): number=103, enum=asset_set_type.AssetSetTypeEnum.AssetSetType, ) + missing_eu_political_advertising_declaration: bool = proto.Field( + proto.BOOL, + number=108, + ) bidding_strategy: str = proto.Field( proto.STRING, number=67, diff --git a/google/ads/googleads/v22/resources/types/campaign_budget.py b/google/ads/googleads/v22/resources/types/campaign_budget.py index 8444514c0..b6d76b533 100644 --- a/google/ads/googleads/v22/resources/types/campaign_budget.py +++ b/google/ads/googleads/v22/resources/types/campaign_budget.py @@ -23,7 +23,6 @@ from google.ads.googleads.v22.enums.types import budget_status from google.ads.googleads.v22.enums.types import budget_type - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -70,18 +69,32 @@ class CampaignBudget(proto.Message): This field is a member of `oneof`_ ``_name``. amount_micros (int): - The amount of the budget, in the local - currency for the account. Amount is specified in - micros, where one million is equivalent to one - currency unit. Monthly spend is capped at 30.4 - times this amount. + The average daily amount to be spent by the campaign. This + field is used when the CampaignBudget ``period`` is set to + ``DAILY``, which is the default. + + Amount is specified in micros in the account's local + currency. One million micros is equivalent to one currency + unit. The effective monthly spend is capped at 30.4 times + this daily amount. + + This field is mutually exclusive with 'total_amount_micros'. + Only one of 'amount_micros' or 'total_amount_micros' should + be set. This field is a member of `oneof`_ ``_amount_micros``. total_amount_micros (int): - The lifetime amount of the budget, in the - local currency for the account. Amount is - specified in micros, where one million is - equivalent to one currency unit. + The total amount to be spent by the campaign over its entire + duration. This field is used *only* when the CampaignBudget + ``period`` is set to ``CUSTOM_PERIOD``. It represents the + budget cap for the campaign's lifetime, rather than a daily + limit. The amount is specified in micros in the account's + local currency. One million micros is equivalent to one + currency unit. + + This field is mutually exclusive with 'amount_micros'. Only + one of 'total_amount_micros' or 'amount_micros' should be + set. This field is a member of `oneof`_ ``_total_amount_micros``. status (google.ads.googleads.v22.enums.types.BudgetStatusEnum.BudgetStatus): diff --git a/google/ads/googleads/v22/resources/types/campaign_criterion.py b/google/ads/googleads/v22/resources/types/campaign_criterion.py index 03b623a93..61ec72861 100644 --- a/google/ads/googleads/v22/resources/types/campaign_criterion.py +++ b/google/ads/googleads/v22/resources/types/campaign_criterion.py @@ -22,7 +22,6 @@ from google.ads.googleads.v22.enums.types import campaign_criterion_status from google.ads.googleads.v22.enums.types import criterion_type - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -154,6 +153,9 @@ class CampaignCriterion(proto.Message): ip_block (google.ads.googleads.v22.common.types.IpBlockInfo): Immutable. IpBlock. + You can exclude up to 500 IP addresses per + campaign. + This field is a member of `oneof`_ ``criterion``. content_label (google.ads.googleads.v22.common.types.ContentLabelInfo): Immutable. ContentLabel. diff --git a/google/ads/googleads/v22/resources/types/campaign_search_term_view.py b/google/ads/googleads/v22/resources/types/campaign_search_term_view.py index 410a22c6c..f04f76846 100644 --- a/google/ads/googleads/v22/resources/types/campaign_search_term_view.py +++ b/google/ads/googleads/v22/resources/types/campaign_search_term_view.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -31,7 +30,8 @@ class CampaignSearchTermView(proto.Message): r"""This report provides granular performance data, including cost metrics, for each individual search term that triggered - your ads. + your ads. If keyword-related segments are used, Performance Max + data will be excluded from the results. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v22/resources/types/change_event.py b/google/ads/googleads/v22/resources/types/change_event.py index 5bb30eab7..09221bc2a 100644 --- a/google/ads/googleads/v22/resources/types/change_event.py +++ b/google/ads/googleads/v22/resources/types/change_event.py @@ -58,8 +58,7 @@ from google.ads.googleads.v22.resources.types import ( customer_asset as gagr_customer_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", diff --git a/google/ads/googleads/v22/resources/types/click_view.py b/google/ads/googleads/v22/resources/types/click_view.py index c9baac837..abea96d77 100644 --- a/google/ads/googleads/v22/resources/types/click_view.py +++ b/google/ads/googleads/v22/resources/types/click_view.py @@ -21,7 +21,6 @@ from google.ads.googleads.v22.common.types import click_location from google.ads.googleads.v22.common.types import criteria - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -39,6 +38,9 @@ class ClickView(proto.Message): filter limiting the results to one day and can be requested for dates back to 90 days before the time of the request. + GCLIDs are not available in this report for App Campaigns for + Installs (ACi) and App Campaigns for Pre-registration (ACpre). + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v22/resources/types/conversion_value_rule_set.py b/google/ads/googleads/v22/resources/types/conversion_value_rule_set.py index 6e3878bb5..b9f5fdcca 100644 --- a/google/ads/googleads/v22/resources/types/conversion_value_rule_set.py +++ b/google/ads/googleads/v22/resources/types/conversion_value_rule_set.py @@ -26,7 +26,6 @@ from google.ads.googleads.v22.enums.types import value_rule_set_attachment_type from google.ads.googleads.v22.enums.types import value_rule_set_dimension - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -37,7 +36,9 @@ class ConversionValueRuleSet(proto.Message): - r"""A conversion value rule set + r"""A conversion value rule set is a collection of conversion value + rules that lets you adjust conversion values based on the dimensions + specified in the ``dimensions`` field. Attributes: resource_name (str): diff --git a/google/ads/googleads/v22/resources/types/customer.py b/google/ads/googleads/v22/resources/types/customer.py index 96df9c765..a1aadf327 100644 --- a/google/ads/googleads/v22/resources/types/customer.py +++ b/google/ads/googleads/v22/resources/types/customer.py @@ -28,11 +28,11 @@ customer_pay_per_conversion_eligibility_failure_reason, ) from google.ads.googleads.v22.enums.types import customer_status +from google.ads.googleads.v22.enums.types import eu_political_advertising_status from google.ads.googleads.v22.enums.types import ( local_services_verification_status, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -192,6 +192,14 @@ class Customer(proto.Message): https://support.google.com/google-ads/answer/7515513. video_customer (google.ads.googleads.v22.resources.types.VideoCustomer): Video specific information about a Customer. + contains_eu_political_advertising (google.ads.googleads.v22.enums.types.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus): + Output only. Returns the advertiser + self-declaration status of whether this customer + contains political advertising content targeted + towards the European Union. You can use the + Google Ads UI to update this account-level + declaration, or use the API to update the + self-declaration status of individual campaigns. """ resource_name: str = proto.Field( @@ -326,6 +334,13 @@ class Customer(proto.Message): number=54, message="VideoCustomer", ) + contains_eu_political_advertising: ( + eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus + ) = proto.Field( + proto.ENUM, + number=55, + enum=eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus, + ) class CallReportingSetting(proto.Message): diff --git a/google/ads/googleads/v22/resources/types/customer_negative_criterion.py b/google/ads/googleads/v22/resources/types/customer_negative_criterion.py index b612506bf..e660007a8 100644 --- a/google/ads/googleads/v22/resources/types/customer_negative_criterion.py +++ b/google/ads/googleads/v22/resources/types/customer_negative_criterion.py @@ -21,7 +21,6 @@ from google.ads.googleads.v22.common.types import criteria from google.ads.googleads.v22.enums.types import criterion_type - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -83,7 +82,10 @@ class CustomerNegativeCriterion(proto.Message): This field is a member of `oneof`_ ``criterion``. ip_block (google.ads.googleads.v22.common.types.IpBlockInfo): - Immutable. IPBLock + Immutable. IpBlock. + + You can exclude up to 500 IP addresses per + account. This field is a member of `oneof`_ ``criterion``. placement_list (google.ads.googleads.v22.common.types.PlacementListInfo): diff --git a/google/ads/googleads/v22/resources/types/detail_placement_view.py b/google/ads/googleads/v22/resources/types/detail_placement_view.py index 8d21792d5..6ac7cecc0 100644 --- a/google/ads/googleads/v22/resources/types/detail_placement_view.py +++ b/google/ads/googleads/v22/resources/types/detail_placement_view.py @@ -22,7 +22,6 @@ placement_type as gage_placement_type, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -33,8 +32,14 @@ class DetailPlacementView(proto.Message): - r"""A view with metrics aggregated by ad group and URL or YouTube - video. + r"""A view with metrics aggregated by ad group and URL or YouTube video. + + This view primarily surfaces placement data from the Google Display + Network. While you can select segments like + ``segments.ad_network_type``, this view generally does not include + placement data from other networks, such as the Search Partners + network. To understand performance on Search Partners, consider + other reports and segmentations. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v22/resources/types/display_keyword_view.py b/google/ads/googleads/v22/resources/types/display_keyword_view.py index 0c0191cbf..3bb8bc427 100644 --- a/google/ads/googleads/v22/resources/types/display_keyword_view.py +++ b/google/ads/googleads/v22/resources/types/display_keyword_view.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -31,6 +30,22 @@ class DisplayKeywordView(proto.Message): r"""A display keyword view. + Provides performance data for keywords used in Display Network + campaigns. This view lets you analyze how your display keywords are + performing across various segments. + + This view is primarily used to track the effectiveness of keyword + targeting within your Display campaigns. To understand which network + the metrics apply to, you can select the + ``segments.ad_network_type`` field in your query. This field will + segment the data by networks such as the Google Display Network, + YouTube, Gmail, and so on. + + You can select fields from this resource along with metrics like + impressions, clicks, and conversions to gauge performance. + Attributed resources like ``ad_group`` and ``campaign`` can also be + selected without segmenting metrics. + Attributes: resource_name (str): Output only. The resource name of the display keyword view. diff --git a/google/ads/googleads/v22/resources/types/local_services_lead.py b/google/ads/googleads/v22/resources/types/local_services_lead.py index 300c7d7d2..0169df211 100644 --- a/google/ads/googleads/v22/resources/types/local_services_lead.py +++ b/google/ads/googleads/v22/resources/types/local_services_lead.py @@ -24,7 +24,6 @@ from google.ads.googleads.v22.enums.types import local_services_lead_status from google.ads.googleads.v22.enums.types import local_services_lead_type - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -48,7 +47,7 @@ class LocalServicesLead(proto.Message): Attributes: resource_name (str): - Output only. The resource name of the local services lead + Immutable. The resource name of the local services lead data. Local Services Lead resource name have the form ``customers/{customer_id}/localServicesLead/{local_services_lead_id}`` @@ -168,8 +167,12 @@ class ContactDetails(proto.Message): Attributes: phone_number (str): - Output only. Consumer phone number in E164 - format. + Output only. Phone number of the consumer for + the lead. This can be a real phone number or a + tracking number. The phone number is returned in + E164 format. See + https://support.google.com/google-ads/answer/16355235?hl=en + to learn more. Example: +16504519489. email (str): Output only. Consumer email address. consumer_name (str): diff --git a/google/ads/googleads/v22/resources/types/shopping_performance_view.py b/google/ads/googleads/v22/resources/types/shopping_performance_view.py index 690c72d0b..3e77c9a8a 100644 --- a/google/ads/googleads/v22/resources/types/shopping_performance_view.py +++ b/google/ads/googleads/v22/resources/types/shopping_performance_view.py @@ -18,7 +18,6 @@ import proto # type: ignore - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -30,12 +29,26 @@ class ShoppingPerformanceView(proto.Message): r"""Shopping performance view. - Provides Shopping campaign statistics aggregated at several - product dimension levels. Product dimension values from Merchant - Center such as brand, category, custom attributes, product - condition and product type will reflect the state of each - dimension as of the date and time when the corresponding event - was recorded. + + Provides Shopping campaign and Performance Max campaign statistics + aggregated at several product dimension levels. Product dimension + values from Merchant Center such as brand, category, custom + attributes, product condition, and product type will reflect the + state of each dimension as of the date and time when the + corresponding event was recorded. + + The number of impressions and clicks that + ``shopping_performance_view`` returns stats for may be different + from campaign reports. ``shopping_performance_view`` shows + impressions and clicks on products appearing in ads, while campaign + reports show impressions and clicks on the ads themselves. Depending + on the format, an ad can show from zero to several products, so the + numbers may not match. + + In Google Ads UI, you can query impressions and clicks of products + appearing in ads by selecting a column from "Product attributes" in + the report editor. For example, selecting the "Brand" column is + equivalent to selecting ``segments.product_brand``. Attributes: resource_name (str): diff --git a/google/ads/googleads/v22/resources/types/user_list.py b/google/ads/googleads/v22/resources/types/user_list.py index 888ae96c6..52fbeb095 100644 --- a/google/ads/googleads/v22/resources/types/user_list.py +++ b/google/ads/googleads/v22/resources/types/user_list.py @@ -28,7 +28,6 @@ from google.ads.googleads.v22.enums.types import user_list_size_range from google.ads.googleads.v22.enums.types import user_list_type - __protobuf__ = proto.module( package="google.ads.googleads.v22.resources", marshal="google.ads.googleads.v22", @@ -39,7 +38,12 @@ class UserList(proto.Message): - r"""A user list. This is a list of users a customer may target. + r"""A user list. This is a list of users a customer may target. The + unique key of a user list consists of the following fields: ``id``. + Note that the ``name`` must also be unique for user lists owned by a + given customer, except in some cases where ``access_reason`` is set + to ``SHARED``. Violating the unique name constraint produces error: + ``UserListError.INVALID_NAME``. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -68,9 +72,9 @@ class UserList(proto.Message): This field is a member of `oneof`_ ``_read_only``. name (str): - Name of this user list. Depending on its access_reason, the - user list name may not be unique (for example, if - access_reason=SHARED) + Name of this user list. Unique per user list, except in some + cases where a user list of the same name has + ``access_reason`` set to ``SHARED``. This field is a member of `oneof`_ ``_name``. description (str): diff --git a/google/ads/googleads/v22/services/services/account_budget_proposal_service/async_client.py b/google/ads/googleads/v22/services/services/account_budget_proposal_service/async_client.py index caab61e93..cd4787b69 100644 --- a/google/ads/googleads/v22/services/services/account_budget_proposal_service/async_client.py +++ b/google/ads/googleads/v22/services/services/account_budget_proposal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -140,7 +139,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AccountBudgetProposalServiceAsyncClient: The constructed client. """ - return AccountBudgetProposalServiceClient.from_service_account_info.__func__(AccountBudgetProposalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AccountBudgetProposalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AccountBudgetProposalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -156,7 +160,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountBudgetProposalServiceAsyncClient: The constructed client. """ - return AccountBudgetProposalServiceClient.from_service_account_file.__func__(AccountBudgetProposalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AccountBudgetProposalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AccountBudgetProposalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/account_budget_proposal_service/client.py b/google/ads/googleads/v22/services/services/account_budget_proposal_service/client.py index 08f067f95..417448616 100644 --- a/google/ads/googleads/v22/services/services/account_budget_proposal_service/client.py +++ b/google/ads/googleads/v22/services/services/account_budget_proposal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -389,14 +417,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AccountBudgetProposalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -404,7 +428,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -436,22 +460,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AccountBudgetProposalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/account_budget_proposal_service/transports/base.py b/google/ads/googleads/v22/services/services/account_budget_proposal_service/transports/base.py index b252f7340..01053ae85 100644 --- a/google/ads/googleads/v22/services/services/account_budget_proposal_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/account_budget_proposal_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/account_link_service/async_client.py b/google/ads/googleads/v22/services/services/account_link_service/async_client.py index b7cf25adb..14b2636c6 100644 --- a/google/ads/googleads/v22/services/services/account_link_service/async_client.py +++ b/google/ads/googleads/v22/services/services/account_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,7 +36,7 @@ account_link as gagr_account_link, ) from google.ads.googleads.v22.services.types import account_link_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AccountLinkServiceTransport, DEFAULT_CLIENT_INFO from .client import AccountLinkServiceClient @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AccountLinkServiceAsyncClient: The constructed client. """ - return AccountLinkServiceClient.from_service_account_info.__func__(AccountLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AccountLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AccountLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountLinkServiceAsyncClient: The constructed client. """ - return AccountLinkServiceClient.from_service_account_file.__func__(AccountLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AccountLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AccountLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/account_link_service/client.py b/google/ads/googleads/v22/services/services/account_link_service/client.py index 71fd41684..5a6960fd3 100644 --- a/google/ads/googleads/v22/services/services/account_link_service/client.py +++ b/google/ads/googleads/v22/services/services/account_link_service/client.py @@ -53,7 +53,7 @@ account_link as gagr_account_link, ) from google.ads.googleads.v22.services.types import account_link_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AccountLinkServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AccountLinkServiceGrpcTransport from .transports.grpc_asyncio import AccountLinkServiceGrpcAsyncIOTransport @@ -139,6 +139,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -330,14 +358,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AccountLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -345,7 +367,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -377,22 +399,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AccountLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/account_link_service/transports/base.py b/google/ads/googleads/v22/services/services/account_link_service/transports/base.py index 19ca8169d..db7006b00 100644 --- a/google/ads/googleads/v22/services/services/account_link_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/account_link_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_ad_label_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_ad_label_service/async_client.py index d68a0c8ae..fe065f15a 100644 --- a/google/ads/googleads/v22/services/services/ad_group_ad_label_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_ad_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_group_ad_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupAdLabelServiceClient @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAdLabelServiceAsyncClient: The constructed client. """ - return AdGroupAdLabelServiceClient.from_service_account_info.__func__(AdGroupAdLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAdLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupAdLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAdLabelServiceAsyncClient: The constructed client. """ - return AdGroupAdLabelServiceClient.from_service_account_file.__func__(AdGroupAdLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAdLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAdLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_ad_label_service/client.py b/google/ads/googleads/v22/services/services/ad_group_ad_label_service/client.py index dd6774cf1..c8127699b 100644 --- a/google/ads/googleads/v22/services/services/ad_group_ad_label_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_ad_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_group_ad_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupAdLabelServiceGrpcTransport from .transports.grpc_asyncio import AdGroupAdLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -384,14 +412,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupAdLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -399,7 +423,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -431,22 +455,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupAdLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_ad_label_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_ad_label_service/transports/base.py index c22eb0733..f7be16c67 100644 --- a/google/ads/googleads/v22/services/services/ad_group_ad_label_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_ad_label_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_ad_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_ad_service/async_client.py index 68e25e8a7..b08580265 100644 --- a/google/ads/googleads/v22/services/services/ad_group_ad_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_ad_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_group_ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupAdServiceClient @@ -122,7 +121,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAdServiceAsyncClient: The constructed client. """ - return AdGroupAdServiceClient.from_service_account_info.__func__(AdGroupAdServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAdServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdGroupAdServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAdServiceAsyncClient: The constructed client. """ - return AdGroupAdServiceClient.from_service_account_file.__func__(AdGroupAdServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAdServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAdServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -456,7 +463,7 @@ async def remove_automatically_created_assets( Args: request (Optional[Union[google.ads.googleads.v22.services.types.RemoveAutomaticallyCreatedAssetsRequest, dict]]): The request object. Request message for - [AdGroupAdService.RemoveAutomaticallyCreatedAssetsRequest][]. + [AdGroupAdService.RemoveAutomaticallyCreatedAssets][google.ads.googleads.v22.services.AdGroupAdService.RemoveAutomaticallyCreatedAssets]. ad_group_ad (:class:`str`): Required. The resource name of the AdGroupAd from which to remove diff --git a/google/ads/googleads/v22/services/services/ad_group_ad_service/client.py b/google/ads/googleads/v22/services/services/ad_group_ad_service/client.py index 11bb1023e..1bca2ff7d 100644 --- a/google/ads/googleads/v22/services/services/ad_group_ad_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_ad_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_group_ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupAdServiceGrpcTransport from .transports.grpc_asyncio import AdGroupAdServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -421,14 +449,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupAdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -436,7 +458,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -468,22 +490,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupAdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -974,7 +990,7 @@ def remove_automatically_created_assets( Args: request (Union[google.ads.googleads.v22.services.types.RemoveAutomaticallyCreatedAssetsRequest, dict]): The request object. Request message for - [AdGroupAdService.RemoveAutomaticallyCreatedAssetsRequest][]. + [AdGroupAdService.RemoveAutomaticallyCreatedAssets][google.ads.googleads.v22.services.AdGroupAdService.RemoveAutomaticallyCreatedAssets]. ad_group_ad (str): Required. The resource name of the AdGroupAd from which to remove diff --git a/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/base.py index 32fc45df6..5a740f417 100644 --- a/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/base.py @@ -27,7 +27,7 @@ import google.protobuf from google.ads.googleads.v22.services.types import ad_group_ad_service -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -83,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/grpc.py b/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/grpc.py index b8b25ccaa..e74667d2f 100644 --- a/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/grpc.py +++ b/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/grpc.py @@ -30,7 +30,7 @@ import proto # type: ignore from google.ads.googleads.v22.services.types import ad_group_ad_service -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO try: diff --git a/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/grpc_asyncio.py b/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/grpc_asyncio.py index a4de87bc3..415ea577d 100644 --- a/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v22/services/services/ad_group_ad_service/transports/grpc_asyncio.py @@ -31,7 +31,7 @@ from grpc.experimental import aio # type: ignore from google.ads.googleads.v22.services.types import ad_group_ad_service -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import AdGroupAdServiceTransport, DEFAULT_CLIENT_INFO try: diff --git a/google/ads/googleads/v22/services/services/ad_group_asset_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_asset_service/async_client.py index ceacefeb4..d201b5858 100644 --- a/google/ads/googleads/v22/services/services/ad_group_asset_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupAssetServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAssetServiceAsyncClient: The constructed client. """ - return AdGroupAssetServiceClient.from_service_account_info.__func__(AdGroupAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAssetServiceAsyncClient: The constructed client. """ - return AdGroupAssetServiceClient.from_service_account_file.__func__(AdGroupAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_asset_service/client.py b/google/ads/googleads/v22/services/services/ad_group_asset_service/client.py index 656b57078..812d82358 100644 --- a/google/ads/googleads/v22/services/services/ad_group_asset_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupAssetServiceGrpcTransport from .transports.grpc_asyncio import AdGroupAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -380,14 +408,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupAssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -395,7 +417,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -427,22 +449,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupAssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_asset_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_asset_service/transports/base.py index 7b4c0e38e..ad4851ea8 100644 --- a/google/ads/googleads/v22/services/services/ad_group_asset_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_asset_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_asset_set_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_asset_set_service/async_client.py index aad4847e2..4c313d257 100644 --- a/google/ads/googleads/v22/services/services/ad_group_asset_set_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_group_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupAssetSetServiceAsyncClient: The constructed client. """ - return AdGroupAssetSetServiceClient.from_service_account_info.__func__(AdGroupAssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupAssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupAssetSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupAssetSetServiceAsyncClient: The constructed client. """ - return AdGroupAssetSetServiceClient.from_service_account_file.__func__(AdGroupAssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupAssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupAssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_asset_set_service/client.py b/google/ads/googleads/v22/services/services/ad_group_asset_set_service/client.py index 3db244c0e..b26c5c501 100644 --- a/google/ads/googleads/v22/services/services/ad_group_asset_set_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_group_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -382,14 +410,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupAssetSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -397,7 +421,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -429,22 +453,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupAssetSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_asset_set_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_asset_set_service/transports/base.py index 296f7c5c1..120753db0 100644 --- a/google/ads/googleads/v22/services/services/ad_group_asset_set_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_asset_set_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/async_client.py index 0f832902c..e889f5974 100644 --- a/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( ad_group_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupBidModifierServiceAsyncClient: The constructed client. """ - return AdGroupBidModifierServiceClient.from_service_account_info.__func__(AdGroupBidModifierServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupBidModifierServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupBidModifierServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupBidModifierServiceAsyncClient: The constructed client. """ - return AdGroupBidModifierServiceClient.from_service_account_file.__func__(AdGroupBidModifierServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupBidModifierServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupBidModifierServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/client.py b/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/client.py index f00943652..a4c26bd55 100644 --- a/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( ad_group_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupBidModifierServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupBidModifierServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/transports/base.py index be562df41..fdfe3db63 100644 --- a/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_bid_modifier_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/async_client.py index 6315c5fda..12bdff958 100644 --- a/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( ad_group_criterion_customizer_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -133,7 +132,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCriterionCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCriterionCustomizerServiceClient.from_service_account_info.__func__(AdGroupCriterionCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCriterionCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCriterionCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -149,7 +153,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCriterionCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCriterionCustomizerServiceClient.from_service_account_file.__func__(AdGroupCriterionCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCriterionCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCriterionCustomizerServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/client.py b/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/client.py index 9ecc3e40a..a22647b7c 100644 --- a/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( ad_group_criterion_customizer_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -392,14 +420,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCriterionCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -407,7 +431,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -439,22 +463,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCriterionCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/transports/base.py index a6b27a3eb..3b0faf780 100644 --- a/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_criterion_customizer_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/async_client.py index 98751a5dc..55a104bd9 100644 --- a/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( ad_group_criterion_label_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionLabelServiceTransport, DEFAULT_CLIENT_INFO, @@ -129,7 +128,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCriterionLabelServiceAsyncClient: The constructed client. """ - return AdGroupCriterionLabelServiceClient.from_service_account_info.__func__(AdGroupCriterionLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCriterionLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCriterionLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -145,7 +149,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCriterionLabelServiceAsyncClient: The constructed client. """ - return AdGroupCriterionLabelServiceClient.from_service_account_file.__func__(AdGroupCriterionLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCriterionLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCriterionLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/client.py b/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/client.py index 22d3304bb..307776465 100644 --- a/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( ad_group_criterion_label_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionLabelServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -391,14 +419,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCriterionLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -406,7 +430,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -438,22 +462,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCriterionLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/transports/base.py index 262909084..2ca7b71fd 100644 --- a/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_criterion_label_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_criterion_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_criterion_service/async_client.py index c6119f877..52673b7e3 100644 --- a/google/ads/googleads/v22/services/services/ad_group_criterion_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_group_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -143,7 +142,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCriterionServiceAsyncClient: The constructed client. """ - return AdGroupCriterionServiceClient.from_service_account_info.__func__(AdGroupCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -159,7 +163,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCriterionServiceAsyncClient: The constructed client. """ - return AdGroupCriterionServiceClient.from_service_account_file.__func__(AdGroupCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCriterionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_criterion_service/client.py b/google/ads/googleads/v22/services/services/ad_group_criterion_service/client.py index 3f79c2577..8dd1d8f7a 100644 --- a/google/ads/googleads/v22/services/services/ad_group_criterion_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_criterion_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_group_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -441,14 +469,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -456,7 +480,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -488,22 +512,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_criterion_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_criterion_service/transports/base.py index 5e120a98a..5db4b59df 100644 --- a/google/ads/googleads/v22/services/services/ad_group_criterion_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_criterion_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_customizer_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_customizer_service/async_client.py index fd6de38c1..33ca5163d 100644 --- a/google/ads/googleads/v22/services/services/ad_group_customizer_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_group_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCustomizerServiceClient.from_service_account_info.__func__(AdGroupCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupCustomizerServiceAsyncClient: The constructed client. """ - return AdGroupCustomizerServiceClient.from_service_account_file.__func__(AdGroupCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupCustomizerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_customizer_service/client.py b/google/ads/googleads/v22/services/services/ad_group_customizer_service/client.py index c963383d8..e74aff84b 100644 --- a/google/ads/googleads/v22/services/services/ad_group_customizer_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_customizer_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_group_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AdGroupCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AdGroupCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AdGroupCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_customizer_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_customizer_service/transports/base.py index 9131839d8..23561852f 100644 --- a/google/ads/googleads/v22/services/services/ad_group_customizer_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_customizer_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_label_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_label_service/async_client.py index b09c275a7..b4947d2d9 100644 --- a/google/ads/googleads/v22/services/services/ad_group_label_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_group_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupLabelServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupLabelServiceAsyncClient: The constructed client. """ - return AdGroupLabelServiceClient.from_service_account_info.__func__(AdGroupLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdGroupLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupLabelServiceAsyncClient: The constructed client. """ - return AdGroupLabelServiceClient.from_service_account_file.__func__(AdGroupLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_label_service/client.py b/google/ads/googleads/v22/services/services/ad_group_label_service/client.py index 37df90169..4121fef8b 100644 --- a/google/ads/googleads/v22/services/services/ad_group_label_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_group_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupLabelServiceGrpcTransport from .transports.grpc_asyncio import AdGroupLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -378,14 +406,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupLabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -393,7 +415,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -425,22 +447,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupLabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_label_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_label_service/transports/base.py index 472cef622..29070e788 100644 --- a/google/ads/googleads/v22/services/services/ad_group_label_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_label_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_group_service/async_client.py b/google/ads/googleads/v22/services/services/ad_group_service/async_client.py index 0129d1ecf..73fd427cf 100644 --- a/google/ads/googleads/v22/services/services/ad_group_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupServiceTransport, DEFAULT_CLIENT_INFO from .client import AdGroupServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdGroupServiceAsyncClient: The constructed client. """ - return AdGroupServiceClient.from_service_account_info.__func__(AdGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdGroupServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdGroupServiceAsyncClient: The constructed client. """ - return AdGroupServiceClient.from_service_account_file.__func__(AdGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_group_service/client.py b/google/ads/googleads/v22/services/services/ad_group_service/client.py index 21f934b81..a37e662ac 100644 --- a/google/ads/googleads/v22/services/services/ad_group_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_group_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupServiceGrpcTransport from .transports.grpc_asyncio import AdGroupServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -377,14 +405,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -392,7 +414,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -424,22 +446,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_group_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_group_service/transports/base.py index c79c2d170..1a2df2887 100644 --- a/google/ads/googleads/v22/services/services/ad_group_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_group_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_parameter_service/async_client.py b/google/ads/googleads/v22/services/services/ad_parameter_service/async_client.py index 1d9a279f3..c2d1c4711 100644 --- a/google/ads/googleads/v22/services/services/ad_parameter_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_parameter_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_parameter_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdParameterServiceTransport, DEFAULT_CLIENT_INFO from .client import AdParameterServiceClient @@ -116,7 +115,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdParameterServiceAsyncClient: The constructed client. """ - return AdParameterServiceClient.from_service_account_info.__func__(AdParameterServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdParameterServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AdParameterServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,7 +136,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdParameterServiceAsyncClient: The constructed client. """ - return AdParameterServiceClient.from_service_account_file.__func__(AdParameterServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdParameterServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AdParameterServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_parameter_service/client.py b/google/ads/googleads/v22/services/services/ad_parameter_service/client.py index 58adc4a94..8f2d022dd 100644 --- a/google/ads/googleads/v22/services/services/ad_parameter_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_parameter_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_parameter_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdParameterServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdParameterServiceGrpcTransport from .transports.grpc_asyncio import AdParameterServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -361,14 +389,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdParameterServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -376,7 +398,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -408,22 +430,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdParameterServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_parameter_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_parameter_service/transports/base.py index 6859f5f57..448e59855 100644 --- a/google/ads/googleads/v22/services/services/ad_parameter_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_parameter_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/ad_service/async_client.py b/google/ads/googleads/v22/services/services/ad_service/async_client.py index 4cd0f7b28..decd9f7a7 100644 --- a/google/ads/googleads/v22/services/services/ad_service/async_client.py +++ b/google/ads/googleads/v22/services/services/ad_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdServiceTransport, DEFAULT_CLIENT_INFO from .client import AdServiceClient @@ -100,7 +99,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AdServiceAsyncClient: The constructed client. """ - return AdServiceClient.from_service_account_info.__func__(AdServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AdServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AdServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -116,7 +118,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AdServiceAsyncClient: The constructed client. """ - return AdServiceClient.from_service_account_file.__func__(AdServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AdServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AdServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/ad_service/client.py b/google/ads/googleads/v22/services/services/ad_service/client.py index caf8ed5e5..43e054e48 100644 --- a/google/ads/googleads/v22/services/services/ad_service/client.py +++ b/google/ads/googleads/v22/services/services/ad_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import ad_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AdServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdServiceGrpcTransport from .transports.grpc_asyncio import AdServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -334,14 +362,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -349,7 +371,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -381,22 +403,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AdServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/ad_service/transports/base.py b/google/ads/googleads/v22/services/services/ad_service/transports/base.py index 201f3a52b..05f94d294 100644 --- a/google/ads/googleads/v22/services/services/ad_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/ad_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/asset_generation_service/async_client.py b/google/ads/googleads/v22/services/services/asset_generation_service/async_client.py index 543d4cd4c..4da9a3de3 100644 --- a/google/ads/googleads/v22/services/services/asset_generation_service/async_client.py +++ b/google/ads/googleads/v22/services/services/asset_generation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGenerationServiceAsyncClient: The constructed client. """ - return AssetGenerationServiceClient.from_service_account_info.__func__(AssetGenerationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGenerationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGenerationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGenerationServiceAsyncClient: The constructed client. """ - return AssetGenerationServiceClient.from_service_account_file.__func__(AssetGenerationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGenerationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGenerationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/asset_generation_service/client.py b/google/ads/googleads/v22/services/services/asset_generation_service/client.py index d35baa2cf..ef05d9766 100644 --- a/google/ads/googleads/v22/services/services/asset_generation_service/client.py +++ b/google/ads/googleads/v22/services/services/asset_generation_service/client.py @@ -138,6 +138,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -353,14 +381,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGenerationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -368,7 +392,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -400,22 +424,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGenerationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/asset_generation_service/transports/base.py b/google/ads/googleads/v22/services/services/asset_generation_service/transports/base.py index 05e0cfb5b..557aba944 100644 --- a/google/ads/googleads/v22/services/services/asset_generation_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/asset_generation_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/asset_group_asset_service/async_client.py b/google/ads/googleads/v22/services/services/asset_group_asset_service/async_client.py index 6317a3206..d8ae6e8c2 100644 --- a/google/ads/googleads/v22/services/services/asset_group_asset_service/async_client.py +++ b/google/ads/googleads/v22/services/services/asset_group_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import asset_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupAssetServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupAssetServiceAsyncClient: The constructed client. """ - return AssetGroupAssetServiceClient.from_service_account_info.__func__(AssetGroupAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGroupAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupAssetServiceAsyncClient: The constructed client. """ - return AssetGroupAssetServiceClient.from_service_account_file.__func__(AssetGroupAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/asset_group_asset_service/client.py b/google/ads/googleads/v22/services/services/asset_group_asset_service/client.py index db75502f8..c4517c1af 100644 --- a/google/ads/googleads/v22/services/services/asset_group_asset_service/client.py +++ b/google/ads/googleads/v22/services/services/asset_group_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import asset_group_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupAssetServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -383,14 +411,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGroupAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -398,7 +422,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -430,22 +454,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGroupAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/asset_group_asset_service/transports/base.py b/google/ads/googleads/v22/services/services/asset_group_asset_service/transports/base.py index 6ad848a2f..7da7da5d7 100644 --- a/google/ads/googleads/v22/services/services/asset_group_asset_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/asset_group_asset_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/async_client.py b/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/async_client.py index c82ef5ad3..c62ace653 100644 --- a/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/async_client.py +++ b/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -128,7 +127,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupListingGroupFilterServiceAsyncClient: The constructed client. """ - return AssetGroupListingGroupFilterServiceClient.from_service_account_info.__func__(AssetGroupListingGroupFilterServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupListingGroupFilterServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGroupListingGroupFilterServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -144,7 +151,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupListingGroupFilterServiceAsyncClient: The constructed client. """ - return AssetGroupListingGroupFilterServiceClient.from_service_account_file.__func__(AssetGroupListingGroupFilterServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupListingGroupFilterServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupListingGroupFilterServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/client.py b/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/client.py index 752748773..131c3a81a 100644 --- a/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/client.py +++ b/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/client.py @@ -156,6 +156,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -371,14 +399,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGroupListingGroupFilterServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -386,7 +410,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -418,22 +442,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGroupListingGroupFilterServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/transports/base.py b/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/transports/base.py index 8cd40429f..547ea48bd 100644 --- a/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/asset_group_listing_group_filter_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/asset_group_service/async_client.py b/google/ads/googleads/v22/services/services/asset_group_service/async_client.py index 1a31faf61..a9f70f7e3 100644 --- a/google/ads/googleads/v22/services/services/asset_group_service/async_client.py +++ b/google/ads/googleads/v22/services/services/asset_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import asset_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetGroupServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetGroupServiceClient @@ -114,7 +113,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupServiceAsyncClient: The constructed client. """ - return AssetGroupServiceClient.from_service_account_info.__func__(AssetGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssetGroupServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupServiceAsyncClient: The constructed client. """ - return AssetGroupServiceClient.from_service_account_file.__func__(AssetGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/asset_group_service/client.py b/google/ads/googleads/v22/services/services/asset_group_service/client.py index d95a99f7d..00c294ee3 100644 --- a/google/ads/googleads/v22/services/services/asset_group_service/client.py +++ b/google/ads/googleads/v22/services/services/asset_group_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import asset_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetGroupServiceGrpcTransport from .transports.grpc_asyncio import AssetGroupServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -355,14 +383,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AssetGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -370,7 +392,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -402,22 +424,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AssetGroupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/asset_group_service/transports/base.py b/google/ads/googleads/v22/services/services/asset_group_service/transports/base.py index d42436ad8..02f2c752d 100644 --- a/google/ads/googleads/v22/services/services/asset_group_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/asset_group_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/asset_group_signal_service/async_client.py b/google/ads/googleads/v22/services/services/asset_group_signal_service/async_client.py index 9381c7f99..77de11a92 100644 --- a/google/ads/googleads/v22/services/services/asset_group_signal_service/async_client.py +++ b/google/ads/googleads/v22/services/services/asset_group_signal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import asset_group_signal_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupSignalServiceTransport, DEFAULT_CLIENT_INFO, @@ -121,7 +120,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetGroupSignalServiceAsyncClient: The constructed client. """ - return AssetGroupSignalServiceClient.from_service_account_info.__func__(AssetGroupSignalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetGroupSignalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetGroupSignalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -137,7 +141,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetGroupSignalServiceAsyncClient: The constructed client. """ - return AssetGroupSignalServiceClient.from_service_account_file.__func__(AssetGroupSignalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetGroupSignalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetGroupSignalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/asset_group_signal_service/client.py b/google/ads/googleads/v22/services/services/asset_group_signal_service/client.py index 6c9f5523d..f3769317a 100644 --- a/google/ads/googleads/v22/services/services/asset_group_signal_service/client.py +++ b/google/ads/googleads/v22/services/services/asset_group_signal_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import asset_group_signal_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AssetGroupSignalServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -364,14 +392,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetGroupSignalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -379,7 +403,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -411,22 +435,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetGroupSignalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/asset_group_signal_service/transports/base.py b/google/ads/googleads/v22/services/services/asset_group_signal_service/transports/base.py index d6066deaf..f64606a3d 100644 --- a/google/ads/googleads/v22/services/services/asset_group_signal_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/asset_group_signal_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/asset_service/async_client.py b/google/ads/googleads/v22/services/services/asset_service/async_client.py index dc380f6d1..c35caa539 100644 --- a/google/ads/googleads/v22/services/services/asset_service/async_client.py +++ b/google/ads/googleads/v22/services/services/asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetServiceClient @@ -109,7 +108,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetServiceAsyncClient: The constructed client. """ - return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssetServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -125,7 +127,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetServiceAsyncClient: The constructed client. """ - return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AssetServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/asset_service/client.py b/google/ads/googleads/v22/services/services/asset_service/client.py index 72581a2c9..2a32f533e 100644 --- a/google/ads/googleads/v22/services/services/asset_service/client.py +++ b/google/ads/googleads/v22/services/services/asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport @@ -147,6 +147,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -357,14 +385,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -372,7 +394,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -404,22 +426,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/asset_service/transports/base.py b/google/ads/googleads/v22/services/services/asset_service/transports/base.py index d24f1cf97..e857953dd 100644 --- a/google/ads/googleads/v22/services/services/asset_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/asset_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/asset_set_asset_service/async_client.py b/google/ads/googleads/v22/services/services/asset_set_asset_service/async_client.py index 189fe418f..92b9d5e3b 100644 --- a/google/ads/googleads/v22/services/services/asset_set_asset_service/async_client.py +++ b/google/ads/googleads/v22/services/services/asset_set_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import asset_set_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetSetAssetServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetSetAssetServiceAsyncClient: The constructed client. """ - return AssetSetAssetServiceClient.from_service_account_info.__func__(AssetSetAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetSetAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AssetSetAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetSetAssetServiceAsyncClient: The constructed client. """ - return AssetSetAssetServiceClient.from_service_account_file.__func__(AssetSetAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetSetAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetSetAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/asset_set_asset_service/client.py b/google/ads/googleads/v22/services/services/asset_set_asset_service/client.py index d213502d1..09e14b130 100644 --- a/google/ads/googleads/v22/services/services/asset_set_asset_service/client.py +++ b/google/ads/googleads/v22/services/services/asset_set_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import asset_set_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetSetAssetServiceGrpcTransport from .transports.grpc_asyncio import AssetSetAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -378,14 +406,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AssetSetAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -393,7 +417,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -425,22 +449,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AssetSetAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/asset_set_asset_service/transports/base.py b/google/ads/googleads/v22/services/services/asset_set_asset_service/transports/base.py index 9ca91f3a8..69884955e 100644 --- a/google/ads/googleads/v22/services/services/asset_set_asset_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/asset_set_asset_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/asset_set_service/async_client.py b/google/ads/googleads/v22/services/services/asset_set_service/async_client.py index 73649fab8..662603059 100644 --- a/google/ads/googleads/v22/services/services/asset_set_service/async_client.py +++ b/google/ads/googleads/v22/services/services/asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetServiceTransport, DEFAULT_CLIENT_INFO from .client import AssetSetServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AssetSetServiceAsyncClient: The constructed client. """ - return AssetSetServiceClient.from_service_account_info.__func__(AssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AssetSetServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetSetServiceAsyncClient: The constructed client. """ - return AssetSetServiceClient.from_service_account_file.__func__(AssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/asset_set_service/client.py b/google/ads/googleads/v22/services/services/asset_set_service/client.py index 1946be70e..148bebb94 100644 --- a/google/ads/googleads/v22/services/services/asset_set_service/client.py +++ b/google/ads/googleads/v22/services/services/asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AssetSetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetSetServiceGrpcTransport from .transports.grpc_asyncio import AssetSetServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AssetSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AssetSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/asset_set_service/transports/base.py b/google/ads/googleads/v22/services/services/asset_set_service/transports/base.py index b8ca75f8a..f9b3e45d3 100644 --- a/google/ads/googleads/v22/services/services/asset_set_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/asset_set_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/audience_insights_service/async_client.py b/google/ads/googleads/v22/services/services/audience_insights_service/async_client.py index a4c96d89a..c12018c5f 100644 --- a/google/ads/googleads/v22/services/services/audience_insights_service/async_client.py +++ b/google/ads/googleads/v22/services/services/audience_insights_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -114,7 +113,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AudienceInsightsServiceAsyncClient: The constructed client. """ - return AudienceInsightsServiceClient.from_service_account_info.__func__(AudienceInsightsServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AudienceInsightsServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AudienceInsightsServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +134,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AudienceInsightsServiceAsyncClient: The constructed client. """ - return AudienceInsightsServiceClient.from_service_account_file.__func__(AudienceInsightsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AudienceInsightsServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AudienceInsightsServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/audience_insights_service/client.py b/google/ads/googleads/v22/services/services/audience_insights_service/client.py index dfbc6bc7b..896cfbd73 100644 --- a/google/ads/googleads/v22/services/services/audience_insights_service/client.py +++ b/google/ads/googleads/v22/services/services/audience_insights_service/client.py @@ -156,6 +156,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -327,14 +355,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AudienceInsightsServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -342,7 +366,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -374,22 +398,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AudienceInsightsServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/audience_insights_service/transports/base.py b/google/ads/googleads/v22/services/services/audience_insights_service/transports/base.py index 2e9f935a0..5e556d7bb 100644 --- a/google/ads/googleads/v22/services/services/audience_insights_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/audience_insights_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/audience_service/async_client.py b/google/ads/googleads/v22/services/services/audience_service/async_client.py index 2c0d6386e..68a72d10b 100644 --- a/google/ads/googleads/v22/services/services/audience_service/async_client.py +++ b/google/ads/googleads/v22/services/services/audience_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import audience_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AudienceServiceTransport, DEFAULT_CLIENT_INFO from .client import AudienceServiceClient @@ -122,7 +121,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AudienceServiceAsyncClient: The constructed client. """ - return AudienceServiceClient.from_service_account_info.__func__(AudienceServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AudienceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AudienceServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AudienceServiceAsyncClient: The constructed client. """ - return AudienceServiceClient.from_service_account_file.__func__(AudienceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AudienceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AudienceServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/audience_service/client.py b/google/ads/googleads/v22/services/services/audience_service/client.py index 294be3c63..00b066649 100644 --- a/google/ads/googleads/v22/services/services/audience_service/client.py +++ b/google/ads/googleads/v22/services/services/audience_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import audience_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import AudienceServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AudienceServiceGrpcTransport from .transports.grpc_asyncio import AudienceServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -395,14 +423,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = AudienceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -410,7 +432,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -442,22 +464,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = AudienceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/audience_service/transports/base.py b/google/ads/googleads/v22/services/services/audience_service/transports/base.py index d243c1401..ce04e27b3 100644 --- a/google/ads/googleads/v22/services/services/audience_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/audience_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/async_client.py b/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/async_client.py index 33d8e8a8f..882dc914a 100644 --- a/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/async_client.py +++ b/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( automatically_created_asset_removal_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AutomaticallyCreatedAssetRemovalServiceTransport, DEFAULT_CLIENT_INFO, @@ -117,7 +116,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: AutomaticallyCreatedAssetRemovalServiceAsyncClient: The constructed client. """ - return AutomaticallyCreatedAssetRemovalServiceClient.from_service_account_info.__func__(AutomaticallyCreatedAssetRemovalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + AutomaticallyCreatedAssetRemovalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + AutomaticallyCreatedAssetRemovalServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -133,7 +140,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AutomaticallyCreatedAssetRemovalServiceAsyncClient: The constructed client. """ - return AutomaticallyCreatedAssetRemovalServiceClient.from_service_account_file.__func__(AutomaticallyCreatedAssetRemovalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + AutomaticallyCreatedAssetRemovalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + AutomaticallyCreatedAssetRemovalServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/client.py b/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/client.py index 7dd44a806..3b5d411c8 100644 --- a/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/client.py +++ b/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( automatically_created_asset_removal_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( AutomaticallyCreatedAssetRemovalServiceTransport, DEFAULT_CLIENT_INFO, @@ -159,6 +159,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -330,14 +358,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + AutomaticallyCreatedAssetRemovalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -345,7 +369,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -377,22 +401,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + AutomaticallyCreatedAssetRemovalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/transports/base.py b/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/transports/base.py index bf438bcf9..bcaf81fcf 100644 --- a/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/automatically_created_asset_removal_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/batch_job_service/async_client.py b/google/ads/googleads/v22/services/services/batch_job_service/async_client.py index dab0738e0..2f0631b93 100644 --- a/google/ads/googleads/v22/services/services/batch_job_service/async_client.py +++ b/google/ads/googleads/v22/services/services/batch_job_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,9 +36,9 @@ from google.ads.googleads.v22.services.services.batch_job_service import pagers from google.ads.googleads.v22.services.types import batch_job_service from google.ads.googleads.v22.services.types import google_ads_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .transports.base import BatchJobServiceTransport, DEFAULT_CLIENT_INFO from .client import BatchJobServiceClient @@ -523,7 +522,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BatchJobServiceAsyncClient: The constructed client. """ - return BatchJobServiceClient.from_service_account_info.__func__(BatchJobServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BatchJobServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(BatchJobServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -539,7 +541,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BatchJobServiceAsyncClient: The constructed client. """ - return BatchJobServiceClient.from_service_account_file.__func__(BatchJobServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BatchJobServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BatchJobServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/batch_job_service/client.py b/google/ads/googleads/v22/services/services/batch_job_service/client.py index 84c6c9965..9ad752f18 100644 --- a/google/ads/googleads/v22/services/services/batch_job_service/client.py +++ b/google/ads/googleads/v22/services/services/batch_job_service/client.py @@ -63,9 +63,9 @@ from google.ads.googleads.v22.services.services.batch_job_service import pagers from google.ads.googleads.v22.services.types import batch_job_service from google.ads.googleads.v22.services.types import google_ads_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .transports.base import BatchJobServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import BatchJobServiceGrpcTransport from .transports.grpc_asyncio import BatchJobServiceGrpcAsyncIOTransport @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -1882,14 +1910,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = BatchJobServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -1897,7 +1919,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -1929,22 +1951,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = BatchJobServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/batch_job_service/transports/base.py b/google/ads/googleads/v22/services/services/batch_job_service/transports/base.py index 7c9363c87..a70d16e48 100644 --- a/google/ads/googleads/v22/services/services/batch_job_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/batch_job_service/transports/base.py @@ -83,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/async_client.py b/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/async_client.py index 2cb40b5ec..cfed48486 100644 --- a/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/async_client.py +++ b/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( bidding_data_exclusion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingDataExclusionServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BiddingDataExclusionServiceAsyncClient: The constructed client. """ - return BiddingDataExclusionServiceClient.from_service_account_info.__func__(BiddingDataExclusionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BiddingDataExclusionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BiddingDataExclusionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BiddingDataExclusionServiceAsyncClient: The constructed client. """ - return BiddingDataExclusionServiceClient.from_service_account_file.__func__(BiddingDataExclusionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BiddingDataExclusionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BiddingDataExclusionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/client.py b/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/client.py index 8e822d6a3..b4f842f8e 100644 --- a/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/client.py +++ b/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( bidding_data_exclusion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingDataExclusionServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -366,14 +394,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BiddingDataExclusionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -381,7 +405,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -413,22 +437,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BiddingDataExclusionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/transports/base.py b/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/transports/base.py index e4a44d1a8..4c6c81583 100644 --- a/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/bidding_data_exclusion_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/async_client.py b/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/async_client.py index 3bf1c89a9..cf4363ee8 100644 --- a/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/async_client.py +++ b/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( bidding_seasonality_adjustment_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingSeasonalityAdjustmentServiceTransport, DEFAULT_CLIENT_INFO, @@ -129,7 +128,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BiddingSeasonalityAdjustmentServiceAsyncClient: The constructed client. """ - return BiddingSeasonalityAdjustmentServiceClient.from_service_account_info.__func__(BiddingSeasonalityAdjustmentServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BiddingSeasonalityAdjustmentServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BiddingSeasonalityAdjustmentServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -145,7 +152,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BiddingSeasonalityAdjustmentServiceAsyncClient: The constructed client. """ - return BiddingSeasonalityAdjustmentServiceClient.from_service_account_file.__func__(BiddingSeasonalityAdjustmentServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BiddingSeasonalityAdjustmentServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BiddingSeasonalityAdjustmentServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/client.py b/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/client.py index 7210dbea3..a8c3e43c7 100644 --- a/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/client.py +++ b/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( bidding_seasonality_adjustment_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingSeasonalityAdjustmentServiceTransport, DEFAULT_CLIENT_INFO, @@ -157,6 +157,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BiddingSeasonalityAdjustmentServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BiddingSeasonalityAdjustmentServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/transports/base.py b/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/transports/base.py index c2f8bf51f..85d99d967 100644 --- a/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/bidding_seasonality_adjustment_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/bidding_strategy_service/async_client.py b/google/ads/googleads/v22/services/services/bidding_strategy_service/async_client.py index 317505cd9..1fb1dbcb9 100644 --- a/google/ads/googleads/v22/services/services/bidding_strategy_service/async_client.py +++ b/google/ads/googleads/v22/services/services/bidding_strategy_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import bidding_strategy_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingStrategyServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BiddingStrategyServiceAsyncClient: The constructed client. """ - return BiddingStrategyServiceClient.from_service_account_info.__func__(BiddingStrategyServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BiddingStrategyServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BiddingStrategyServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BiddingStrategyServiceAsyncClient: The constructed client. """ - return BiddingStrategyServiceClient.from_service_account_file.__func__(BiddingStrategyServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BiddingStrategyServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BiddingStrategyServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/bidding_strategy_service/client.py b/google/ads/googleads/v22/services/services/bidding_strategy_service/client.py index 3a9a53dfd..26b65e1e6 100644 --- a/google/ads/googleads/v22/services/services/bidding_strategy_service/client.py +++ b/google/ads/googleads/v22/services/services/bidding_strategy_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import bidding_strategy_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( BiddingStrategyServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -340,14 +368,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BiddingStrategyServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -355,7 +379,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -387,22 +411,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BiddingStrategyServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/bidding_strategy_service/transports/base.py b/google/ads/googleads/v22/services/services/bidding_strategy_service/transports/base.py index 3619fff34..98c2e8af0 100644 --- a/google/ads/googleads/v22/services/services/bidding_strategy_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/bidding_strategy_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/billing_setup_service/async_client.py b/google/ads/googleads/v22/services/services/billing_setup_service/async_client.py index 258e34ac6..214d4da45 100644 --- a/google/ads/googleads/v22/services/services/billing_setup_service/async_client.py +++ b/google/ads/googleads/v22/services/services/billing_setup_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -128,7 +127,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BillingSetupServiceAsyncClient: The constructed client. """ - return BillingSetupServiceClient.from_service_account_info.__func__(BillingSetupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BillingSetupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BillingSetupServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -144,7 +148,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BillingSetupServiceAsyncClient: The constructed client. """ - return BillingSetupServiceClient.from_service_account_file.__func__(BillingSetupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BillingSetupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BillingSetupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/billing_setup_service/client.py b/google/ads/googleads/v22/services/services/billing_setup_service/client.py index fa9efc45e..459a98ef0 100644 --- a/google/ads/googleads/v22/services/services/billing_setup_service/client.py +++ b/google/ads/googleads/v22/services/services/billing_setup_service/client.py @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -359,14 +387,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = BillingSetupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -374,7 +396,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -406,22 +428,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = BillingSetupServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/billing_setup_service/transports/base.py b/google/ads/googleads/v22/services/services/billing_setup_service/transports/base.py index 891f4e1f3..52e28b64d 100644 --- a/google/ads/googleads/v22/services/services/billing_setup_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/billing_setup_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/brand_suggestion_service/async_client.py b/google/ads/googleads/v22/services/services/brand_suggestion_service/async_client.py index 1ea27776f..9efd8a45b 100644 --- a/google/ads/googleads/v22/services/services/brand_suggestion_service/async_client.py +++ b/google/ads/googleads/v22/services/services/brand_suggestion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -108,7 +107,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: BrandSuggestionServiceAsyncClient: The constructed client. """ - return BrandSuggestionServiceClient.from_service_account_info.__func__(BrandSuggestionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + BrandSuggestionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + BrandSuggestionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +128,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BrandSuggestionServiceAsyncClient: The constructed client. """ - return BrandSuggestionServiceClient.from_service_account_file.__func__(BrandSuggestionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + BrandSuggestionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BrandSuggestionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/brand_suggestion_service/client.py b/google/ads/googleads/v22/services/services/brand_suggestion_service/client.py index 4be551b12..dd8a52849 100644 --- a/google/ads/googleads/v22/services/services/brand_suggestion_service/client.py +++ b/google/ads/googleads/v22/services/services/brand_suggestion_service/client.py @@ -138,6 +138,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -309,14 +337,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + BrandSuggestionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -324,7 +348,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -356,22 +380,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + BrandSuggestionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/brand_suggestion_service/transports/base.py b/google/ads/googleads/v22/services/services/brand_suggestion_service/transports/base.py index b979758ff..67bddf687 100644 --- a/google/ads/googleads/v22/services/services/brand_suggestion_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/brand_suggestion_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_asset_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_asset_service/async_client.py index 16f8b9498..9904b3dfb 100644 --- a/google/ads/googleads/v22/services/services/campaign_asset_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignAssetServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignAssetServiceAsyncClient: The constructed client. """ - return CampaignAssetServiceClient.from_service_account_info.__func__(CampaignAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignAssetServiceAsyncClient: The constructed client. """ - return CampaignAssetServiceClient.from_service_account_file.__func__(CampaignAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_asset_service/client.py b/google/ads/googleads/v22/services/services/campaign_asset_service/client.py index 645cbf7be..b381bc590 100644 --- a/google/ads/googleads/v22/services/services/campaign_asset_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignAssetServiceGrpcTransport from .transports.grpc_asyncio import CampaignAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -380,14 +408,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -395,7 +419,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -427,22 +451,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_asset_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_asset_service/transports/base.py index 2894dbebd..92054be4a 100644 --- a/google/ads/googleads/v22/services/services/campaign_asset_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_asset_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_asset_set_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_asset_set_service/async_client.py index 61046865d..5c43cb5ad 100644 --- a/google/ads/googleads/v22/services/services/campaign_asset_set_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignAssetSetServiceAsyncClient: The constructed client. """ - return CampaignAssetSetServiceClient.from_service_account_info.__func__(CampaignAssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignAssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignAssetSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignAssetSetServiceAsyncClient: The constructed client. """ - return CampaignAssetSetServiceClient.from_service_account_file.__func__(CampaignAssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignAssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignAssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_asset_set_service/client.py b/google/ads/googleads/v22/services/services/campaign_asset_set_service/client.py index 2b10c99e4..8dd6e8c2c 100644 --- a/google/ads/googleads/v22/services/services/campaign_asset_set_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -384,14 +412,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignAssetSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -399,7 +423,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -431,22 +455,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignAssetSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_asset_set_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_asset_set_service/transports/base.py index 454a54429..dbfce731f 100644 --- a/google/ads/googleads/v22/services/services/campaign_asset_set_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_asset_set_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/async_client.py index 752dfdc1d..118b5e25a 100644 --- a/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( campaign_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignBidModifierServiceAsyncClient: The constructed client. """ - return CampaignBidModifierServiceClient.from_service_account_info.__func__(CampaignBidModifierServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignBidModifierServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignBidModifierServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignBidModifierServiceAsyncClient: The constructed client. """ - return CampaignBidModifierServiceClient.from_service_account_file.__func__(CampaignBidModifierServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignBidModifierServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignBidModifierServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/client.py b/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/client.py index b17a1e096..fefec05bf 100644 --- a/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( campaign_bid_modifier_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignBidModifierServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignBidModifierServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignBidModifierServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/transports/base.py index 70b95622b..8fa9f48cd 100644 --- a/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_bid_modifier_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_budget_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_budget_service/async_client.py index 52d32a4d4..4b6238313 100644 --- a/google/ads/googleads/v22/services/services/campaign_budget_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_budget_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_budget_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignBudgetServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignBudgetServiceClient @@ -112,7 +111,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignBudgetServiceAsyncClient: The constructed client. """ - return CampaignBudgetServiceClient.from_service_account_info.__func__(CampaignBudgetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignBudgetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignBudgetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -128,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignBudgetServiceAsyncClient: The constructed client. """ - return CampaignBudgetServiceClient.from_service_account_file.__func__(CampaignBudgetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignBudgetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignBudgetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_budget_service/client.py b/google/ads/googleads/v22/services/services/campaign_budget_service/client.py index b0f867cb9..d01270830 100644 --- a/google/ads/googleads/v22/services/services/campaign_budget_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_budget_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_budget_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignBudgetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignBudgetServiceGrpcTransport from .transports.grpc_asyncio import CampaignBudgetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -337,14 +365,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignBudgetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -352,7 +376,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -384,22 +408,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignBudgetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_budget_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_budget_service/transports/base.py index 14665a12d..5d595f455 100644 --- a/google/ads/googleads/v22/services/services/campaign_budget_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_budget_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/async_client.py index 1cafcc568..ac3b45c0d 100644 --- a/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignConversionGoalServiceAsyncClient: The constructed client. """ - return CampaignConversionGoalServiceClient.from_service_account_info.__func__(CampaignConversionGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignConversionGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignConversionGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignConversionGoalServiceAsyncClient: The constructed client. """ - return CampaignConversionGoalServiceClient.from_service_account_file.__func__(CampaignConversionGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignConversionGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignConversionGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/client.py b/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/client.py index ea49cd353..2af8f1ff8 100644 --- a/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -369,14 +397,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignConversionGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -384,7 +408,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -416,22 +440,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignConversionGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/transports/base.py index 7967af629..ff5106d55 100644 --- a/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_conversion_goal_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_criterion_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_criterion_service/async_client.py index 77338cbf4..b9442ed23 100644 --- a/google/ads/googleads/v22/services/services/campaign_criterion_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -161,7 +160,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignCriterionServiceAsyncClient: The constructed client. """ - return CampaignCriterionServiceClient.from_service_account_info.__func__(CampaignCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -177,7 +181,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignCriterionServiceAsyncClient: The constructed client. """ - return CampaignCriterionServiceClient.from_service_account_file.__func__(CampaignCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignCriterionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_criterion_service/client.py b/google/ads/googleads/v22/services/services/campaign_criterion_service/client.py index 87ec90b12..9acd73be2 100644 --- a/google/ads/googleads/v22/services/services/campaign_criterion_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_criterion_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -488,14 +516,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -503,7 +527,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -535,22 +559,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_criterion_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_criterion_service/transports/base.py index ee5b5f92f..694d770e9 100644 --- a/google/ads/googleads/v22/services/services/campaign_criterion_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_criterion_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_customizer_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_customizer_service/async_client.py index d555a8ca2..bc51ade8b 100644 --- a/google/ads/googleads/v22/services/services/campaign_customizer_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -127,7 +126,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignCustomizerServiceAsyncClient: The constructed client. """ - return CampaignCustomizerServiceClient.from_service_account_info.__func__(CampaignCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -143,7 +147,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignCustomizerServiceAsyncClient: The constructed client. """ - return CampaignCustomizerServiceClient.from_service_account_file.__func__(CampaignCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignCustomizerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_customizer_service/client.py b/google/ads/googleads/v22/services/services/campaign_customizer_service/client.py index 4228aee03..acd49ce98 100644 --- a/google/ads/googleads/v22/services/services/campaign_customizer_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_customizer_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_customizer_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_customizer_service/transports/base.py index ba7f09d88..8ba10dd3c 100644 --- a/google/ads/googleads/v22/services/services/campaign_customizer_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_customizer_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_draft_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_draft_service/async_client.py index 42a4629f3..6a9c97be9 100644 --- a/google/ads/googleads/v22/services/services/campaign_draft_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_draft_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,10 +36,10 @@ pagers, ) from google.ads.googleads.v22.services.types import campaign_draft_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignDraftServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignDraftServiceClient @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignDraftServiceAsyncClient: The constructed client. """ - return CampaignDraftServiceClient.from_service_account_info.__func__(CampaignDraftServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignDraftServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignDraftServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignDraftServiceAsyncClient: The constructed client. """ - return CampaignDraftServiceClient.from_service_account_file.__func__(CampaignDraftServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignDraftServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignDraftServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -433,10 +442,11 @@ async def promote_campaign_draft( r"""Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v22.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v22/services/services/campaign_draft_service/client.py b/google/ads/googleads/v22/services/services/campaign_draft_service/client.py index dba963bb0..1a6becf63 100644 --- a/google/ads/googleads/v22/services/services/campaign_draft_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_draft_service/client.py @@ -63,10 +63,10 @@ pagers, ) from google.ads.googleads.v22.services.types import campaign_draft_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignDraftServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignDraftServiceGrpcTransport from .transports.grpc_asyncio import CampaignDraftServiceGrpcAsyncIOTransport @@ -152,6 +152,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -365,14 +393,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignDraftServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -380,7 +404,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -412,22 +436,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignDraftServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -899,10 +919,11 @@ def promote_campaign_draft( r"""Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v22.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v22/services/services/campaign_draft_service/pagers.py b/google/ads/googleads/v22/services/services/campaign_draft_service/pagers.py index 1b71dfdcd..960b1b10f 100644 --- a/google/ads/googleads/v22/services/services/campaign_draft_service/pagers.py +++ b/google/ads/googleads/v22/services/services/campaign_draft_service/pagers.py @@ -37,7 +37,7 @@ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_draft_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore class ListCampaignDraftAsyncErrorsPager: diff --git a/google/ads/googleads/v22/services/services/campaign_draft_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_draft_service/transports/base.py index b9be8dc54..d1d74282c 100644 --- a/google/ads/googleads/v22/services/services/campaign_draft_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_draft_service/transports/base.py @@ -83,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_draft_service/transports/grpc.py b/google/ads/googleads/v22/services/services/campaign_draft_service/transports/grpc.py index 80a70c043..d0c86b20e 100644 --- a/google/ads/googleads/v22/services/services/campaign_draft_service/transports/grpc.py +++ b/google/ads/googleads/v22/services/services/campaign_draft_service/transports/grpc.py @@ -410,10 +410,11 @@ def promote_campaign_draft( Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v22.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v22/services/services/campaign_draft_service/transports/grpc_asyncio.py b/google/ads/googleads/v22/services/services/campaign_draft_service/transports/grpc_asyncio.py index b4499a396..18a35aaee 100644 --- a/google/ads/googleads/v22/services/services/campaign_draft_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v22/services/services/campaign_draft_service/transports/grpc_asyncio.py @@ -418,10 +418,11 @@ def promote_campaign_draft( Promotes the changes in a draft back to the base campaign. This method returns a Long Running Operation (LRO) indicating if - the Promote is done. Use [Operations.GetOperation] to poll the - LRO until it is done. Only a done status is returned in the - response. See the status in the Campaign Draft resource to - determine if the promotion was successful. If the LRO failed, + the Promote is done. Use + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + to poll the LRO until it is done. Only a done status is returned + in the response. See the status in the Campaign Draft resource + to determine if the promotion was successful. If the LRO failed, use [CampaignDraftService.ListCampaignDraftAsyncErrors][google.ads.googleads.v22.services.CampaignDraftService.ListCampaignDraftAsyncErrors] to view the list of error reasons. diff --git a/google/ads/googleads/v22/services/services/campaign_goal_config_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_goal_config_service/async_client.py index 9d9a5eb89..6faf9dffd 100644 --- a/google/ads/googleads/v22/services/services/campaign_goal_config_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_goal_config_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_goal_config_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignGoalConfigServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignGoalConfigServiceAsyncClient: The constructed client. """ - return CampaignGoalConfigServiceClient.from_service_account_info.__func__(CampaignGoalConfigServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignGoalConfigServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignGoalConfigServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignGoalConfigServiceAsyncClient: The constructed client. """ - return CampaignGoalConfigServiceClient.from_service_account_file.__func__(CampaignGoalConfigServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignGoalConfigServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignGoalConfigServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_goal_config_service/client.py b/google/ads/googleads/v22/services/services/campaign_goal_config_service/client.py index 31646843c..f4b2ca520 100644 --- a/google/ads/googleads/v22/services/services/campaign_goal_config_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_goal_config_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_goal_config_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignGoalConfigServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignGoalConfigServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignGoalConfigServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_goal_config_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_goal_config_service/transports/base.py index e86e5144a..3afbe9a89 100644 --- a/google/ads/googleads/v22/services/services/campaign_goal_config_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_goal_config_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_group_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_group_service/async_client.py index 14a50d50c..b11310c06 100644 --- a/google/ads/googleads/v22/services/services/campaign_group_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignGroupServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignGroupServiceClient @@ -112,7 +111,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignGroupServiceAsyncClient: The constructed client. """ - return CampaignGroupServiceClient.from_service_account_info.__func__(CampaignGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignGroupServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -128,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignGroupServiceAsyncClient: The constructed client. """ - return CampaignGroupServiceClient.from_service_account_file.__func__(CampaignGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_group_service/client.py b/google/ads/googleads/v22/services/services/campaign_group_service/client.py index c9e71486c..c0f2aebe5 100644 --- a/google/ads/googleads/v22/services/services/campaign_group_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_group_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_group_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignGroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignGroupServiceGrpcTransport from .transports.grpc_asyncio import CampaignGroupServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -339,14 +367,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignGroupServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -354,7 +378,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -386,22 +410,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignGroupServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_group_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_group_service/transports/base.py index 27ff67caa..25e4ce2cb 100644 --- a/google/ads/googleads/v22/services/services/campaign_group_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_group_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_label_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_label_service/async_client.py index 47c489834..9f5f08bc1 100644 --- a/google/ads/googleads/v22/services/services/campaign_label_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignLabelServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignLabelServiceAsyncClient: The constructed client. """ - return CampaignLabelServiceClient.from_service_account_info.__func__(CampaignLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignLabelServiceAsyncClient: The constructed client. """ - return CampaignLabelServiceClient.from_service_account_file.__func__(CampaignLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_label_service/client.py b/google/ads/googleads/v22/services/services/campaign_label_service/client.py index 779d59e4c..4f3bb7b95 100644 --- a/google/ads/googleads/v22/services/services/campaign_label_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignLabelServiceGrpcTransport from .transports.grpc_asyncio import CampaignLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -378,14 +406,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -393,7 +417,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -425,22 +449,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_label_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_label_service/transports/base.py index 6502d5145..85b511336 100644 --- a/google/ads/googleads/v22/services/services/campaign_label_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_label_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/async_client.py index e0c313a3f..5f7fd503e 100644 --- a/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignLifecycleGoalServiceAsyncClient: The constructed client. """ - return CampaignLifecycleGoalServiceClient.from_service_account_info.__func__(CampaignLifecycleGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignLifecycleGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignLifecycleGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignLifecycleGoalServiceAsyncClient: The constructed client. """ - return CampaignLifecycleGoalServiceClient.from_service_account_file.__func__(CampaignLifecycleGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignLifecycleGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignLifecycleGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -337,7 +346,7 @@ async def configure_campaign_lifecycle_goals( Args: request (Optional[Union[google.ads.googleads.v22.services.types.ConfigureCampaignLifecycleGoalsRequest, dict]]): The request object. Request message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v22.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. customer_id (:class:`str`): Required. The ID of the customer performing the upload. @@ -363,7 +372,7 @@ async def configure_campaign_lifecycle_goals( Returns: google.ads.googleads.v22.services.types.ConfigureCampaignLifecycleGoalsResponse: Response message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v22.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/client.py b/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/client.py index da805ac52..f9cec4971 100644 --- a/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -355,14 +383,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignLifecycleGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -370,7 +394,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -402,22 +426,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignLifecycleGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -801,7 +821,7 @@ def configure_campaign_lifecycle_goals( Args: request (Union[google.ads.googleads.v22.services.types.ConfigureCampaignLifecycleGoalsRequest, dict]): The request object. Request message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v22.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. customer_id (str): Required. The ID of the customer performing the upload. @@ -827,7 +847,7 @@ def configure_campaign_lifecycle_goals( Returns: google.ads.googleads.v22.services.types.ConfigureCampaignLifecycleGoalsResponse: Response message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v22.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/transports/base.py index b68d97808..1d4876992 100644 --- a/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_lifecycle_goal_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_service/async_client.py index 417e319a2..67908dbcf 100644 --- a/google/ads/googleads/v22/services/services/campaign_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignServiceTransport, DEFAULT_CLIENT_INFO from .client import CampaignServiceClient @@ -148,7 +147,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignServiceAsyncClient: The constructed client. """ - return CampaignServiceClient.from_service_account_info.__func__(CampaignServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(CampaignServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -164,7 +166,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignServiceAsyncClient: The constructed client. """ - return CampaignServiceClient.from_service_account_file.__func__(CampaignServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_service/client.py b/google/ads/googleads/v22/services/services/campaign_service/client.py index 3a98aad45..303a77e54 100644 --- a/google/ads/googleads/v22/services/services/campaign_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CampaignServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CampaignServiceGrpcTransport from .transports.grpc_asyncio import CampaignServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -479,14 +507,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = CampaignServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -494,7 +516,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -526,22 +548,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = CampaignServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_service/transports/base.py index 9b2f1a624..df30d7e59 100644 --- a/google/ads/googleads/v22/services/services/campaign_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/campaign_shared_set_service/async_client.py b/google/ads/googleads/v22/services/services/campaign_shared_set_service/async_client.py index 71b91c42d..92332d1ee 100644 --- a/google/ads/googleads/v22/services/services/campaign_shared_set_service/async_client.py +++ b/google/ads/googleads/v22/services/services/campaign_shared_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import campaign_shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignSharedSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CampaignSharedSetServiceAsyncClient: The constructed client. """ - return CampaignSharedSetServiceClient.from_service_account_info.__func__(CampaignSharedSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CampaignSharedSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CampaignSharedSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CampaignSharedSetServiceAsyncClient: The constructed client. """ - return CampaignSharedSetServiceClient.from_service_account_file.__func__(CampaignSharedSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CampaignSharedSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CampaignSharedSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/campaign_shared_set_service/client.py b/google/ads/googleads/v22/services/services/campaign_shared_set_service/client.py index c160b36b6..cf1a18250 100644 --- a/google/ads/googleads/v22/services/services/campaign_shared_set_service/client.py +++ b/google/ads/googleads/v22/services/services/campaign_shared_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import campaign_shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CampaignSharedSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -386,14 +414,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CampaignSharedSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -401,7 +425,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -433,22 +457,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CampaignSharedSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/campaign_shared_set_service/transports/base.py b/google/ads/googleads/v22/services/services/campaign_shared_set_service/transports/base.py index 3b3707ac2..19acf57cc 100644 --- a/google/ads/googleads/v22/services/services/campaign_shared_set_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/campaign_shared_set_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/content_creator_insights_service/async_client.py b/google/ads/googleads/v22/services/services/content_creator_insights_service/async_client.py index 4923f1813..97f0add57 100644 --- a/google/ads/googleads/v22/services/services/content_creator_insights_service/async_client.py +++ b/google/ads/googleads/v22/services/services/content_creator_insights_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -116,7 +115,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ContentCreatorInsightsServiceAsyncClient: The constructed client. """ - return ContentCreatorInsightsServiceClient.from_service_account_info.__func__(ContentCreatorInsightsServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ContentCreatorInsightsServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ContentCreatorInsightsServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,7 +136,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ContentCreatorInsightsServiceAsyncClient: The constructed client. """ - return ContentCreatorInsightsServiceClient.from_service_account_file.__func__(ContentCreatorInsightsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ContentCreatorInsightsServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ContentCreatorInsightsServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -405,7 +414,7 @@ async def generate_trending_insights( Args: request (Optional[Union[google.ads.googleads.v22.services.types.GenerateTrendingInsightsRequest, dict]]): The request object. Request message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v22.services.ContentCreatorInsightsService.GenerateTrendingInsights]. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -417,7 +426,7 @@ async def generate_trending_insights( Returns: google.ads.googleads.v22.services.types.GenerateTrendingInsightsResponse: Response message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v22.services.ContentCreatorInsightsService.GenerateTrendingInsights]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/content_creator_insights_service/client.py b/google/ads/googleads/v22/services/services/content_creator_insights_service/client.py index 085809e0b..4393058f0 100644 --- a/google/ads/googleads/v22/services/services/content_creator_insights_service/client.py +++ b/google/ads/googleads/v22/services/services/content_creator_insights_service/client.py @@ -148,6 +148,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -319,14 +347,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ContentCreatorInsightsServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -334,7 +358,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -366,22 +390,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ContentCreatorInsightsServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -839,7 +859,7 @@ def generate_trending_insights( Args: request (Union[google.ads.googleads.v22.services.types.GenerateTrendingInsightsRequest, dict]): The request object. Request message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v22.services.ContentCreatorInsightsService.GenerateTrendingInsights]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -851,7 +871,7 @@ def generate_trending_insights( Returns: google.ads.googleads.v22.services.types.GenerateTrendingInsightsResponse: Response message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v22.services.ContentCreatorInsightsService.GenerateTrendingInsights]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/content_creator_insights_service/transports/base.py b/google/ads/googleads/v22/services/services/content_creator_insights_service/transports/base.py index f7908ae27..2217b4a7c 100644 --- a/google/ads/googleads/v22/services/services/content_creator_insights_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/content_creator_insights_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/conversion_action_service/async_client.py b/google/ads/googleads/v22/services/services/conversion_action_service/async_client.py index 87b85f080..fa26d6a51 100644 --- a/google/ads/googleads/v22/services/services/conversion_action_service/async_client.py +++ b/google/ads/googleads/v22/services/services/conversion_action_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import conversion_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -119,7 +118,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionActionServiceAsyncClient: The constructed client. """ - return ConversionActionServiceClient.from_service_account_info.__func__(ConversionActionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionActionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionActionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -135,7 +139,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionActionServiceAsyncClient: The constructed client. """ - return ConversionActionServiceClient.from_service_account_file.__func__(ConversionActionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionActionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionActionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/conversion_action_service/client.py b/google/ads/googleads/v22/services/services/conversion_action_service/client.py index 587597dc4..22ad184b1 100644 --- a/google/ads/googleads/v22/services/services/conversion_action_service/client.py +++ b/google/ads/googleads/v22/services/services/conversion_action_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import conversion_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -357,14 +385,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionActionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -372,7 +396,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -404,22 +428,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionActionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/conversion_action_service/transports/base.py b/google/ads/googleads/v22/services/services/conversion_action_service/transports/base.py index 7923fa0ad..dd882f753 100644 --- a/google/ads/googleads/v22/services/services/conversion_action_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/conversion_action_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/async_client.py b/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/async_client.py index 3e44a83d1..630d548ba 100644 --- a/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/async_client.py +++ b/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( conversion_adjustment_upload_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionAdjustmentUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionAdjustmentUploadServiceAsyncClient: The constructed client. """ - return ConversionAdjustmentUploadServiceClient.from_service_account_info.__func__(ConversionAdjustmentUploadServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionAdjustmentUploadServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionAdjustmentUploadServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionAdjustmentUploadServiceAsyncClient: The constructed client. """ - return ConversionAdjustmentUploadServiceClient.from_service_account_file.__func__(ConversionAdjustmentUploadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionAdjustmentUploadServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionAdjustmentUploadServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/client.py b/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/client.py index d446beffa..d9dbf73fd 100644 --- a/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/client.py +++ b/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( conversion_adjustment_upload_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionAdjustmentUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -326,14 +354,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionAdjustmentUploadServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -341,7 +365,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -373,22 +397,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionAdjustmentUploadServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/transports/base.py b/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/transports/base.py index 12ada7c86..1d4c4d947 100644 --- a/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/conversion_adjustment_upload_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/conversion_custom_variable_service/async_client.py b/google/ads/googleads/v22/services/services/conversion_custom_variable_service/async_client.py index 66afaa51a..eb1a109e3 100644 --- a/google/ads/googleads/v22/services/services/conversion_custom_variable_service/async_client.py +++ b/google/ads/googleads/v22/services/services/conversion_custom_variable_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( conversion_custom_variable_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionCustomVariableServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionCustomVariableServiceAsyncClient: The constructed client. """ - return ConversionCustomVariableServiceClient.from_service_account_info.__func__(ConversionCustomVariableServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionCustomVariableServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionCustomVariableServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionCustomVariableServiceAsyncClient: The constructed client. """ - return ConversionCustomVariableServiceClient.from_service_account_file.__func__(ConversionCustomVariableServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionCustomVariableServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionCustomVariableServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/conversion_custom_variable_service/client.py b/google/ads/googleads/v22/services/services/conversion_custom_variable_service/client.py index 8047178a2..b303e5f6e 100644 --- a/google/ads/googleads/v22/services/services/conversion_custom_variable_service/client.py +++ b/google/ads/googleads/v22/services/services/conversion_custom_variable_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( conversion_custom_variable_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionCustomVariableServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -361,14 +389,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionCustomVariableServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -376,7 +400,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -408,22 +432,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionCustomVariableServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/conversion_custom_variable_service/transports/base.py b/google/ads/googleads/v22/services/services/conversion_custom_variable_service/transports/base.py index 3da87c91a..ea5d03991 100644 --- a/google/ads/googleads/v22/services/services/conversion_custom_variable_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/conversion_custom_variable_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/async_client.py b/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/async_client.py index bb060dc55..0f56a27be 100644 --- a/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/async_client.py +++ b/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -134,7 +133,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionGoalCampaignConfigServiceAsyncClient: The constructed client. """ - return ConversionGoalCampaignConfigServiceClient.from_service_account_info.__func__(ConversionGoalCampaignConfigServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionGoalCampaignConfigServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionGoalCampaignConfigServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -150,7 +157,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionGoalCampaignConfigServiceAsyncClient: The constructed client. """ - return ConversionGoalCampaignConfigServiceClient.from_service_account_file.__func__(ConversionGoalCampaignConfigServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionGoalCampaignConfigServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionGoalCampaignConfigServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/client.py b/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/client.py index 02ff5af3a..5a75d12d5 100644 --- a/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/client.py +++ b/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/client.py @@ -156,6 +156,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -387,14 +415,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionGoalCampaignConfigServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -402,7 +426,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -434,22 +458,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionGoalCampaignConfigServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/transports/base.py b/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/transports/base.py index a085de462..bba0182f3 100644 --- a/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/conversion_goal_campaign_config_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/conversion_upload_service/async_client.py b/google/ads/googleads/v22/services/services/conversion_upload_service/async_client.py index 32262ba25..99698e259 100644 --- a/google/ads/googleads/v22/services/services/conversion_upload_service/async_client.py +++ b/google/ads/googleads/v22/services/services/conversion_upload_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import conversion_upload_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionUploadServiceAsyncClient: The constructed client. """ - return ConversionUploadServiceClient.from_service_account_info.__func__(ConversionUploadServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionUploadServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionUploadServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionUploadServiceAsyncClient: The constructed client. """ - return ConversionUploadServiceClient.from_service_account_file.__func__(ConversionUploadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionUploadServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionUploadServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/conversion_upload_service/client.py b/google/ads/googleads/v22/services/services/conversion_upload_service/client.py index e0a5850bd..1243feda2 100644 --- a/google/ads/googleads/v22/services/services/conversion_upload_service/client.py +++ b/google/ads/googleads/v22/services/services/conversion_upload_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import conversion_upload_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionUploadServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -342,14 +370,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionUploadServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -357,7 +381,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -389,22 +413,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionUploadServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/conversion_upload_service/transports/base.py b/google/ads/googleads/v22/services/services/conversion_upload_service/transports/base.py index a8d151fd0..c98a16f1d 100644 --- a/google/ads/googleads/v22/services/services/conversion_upload_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/conversion_upload_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/conversion_value_rule_service/async_client.py b/google/ads/googleads/v22/services/services/conversion_value_rule_service/async_client.py index ca8e2e2e7..0716fe91b 100644 --- a/google/ads/googleads/v22/services/services/conversion_value_rule_service/async_client.py +++ b/google/ads/googleads/v22/services/services/conversion_value_rule_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( conversion_value_rule_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleServiceTransport, DEFAULT_CLIENT_INFO, @@ -141,7 +140,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionValueRuleServiceAsyncClient: The constructed client. """ - return ConversionValueRuleServiceClient.from_service_account_info.__func__(ConversionValueRuleServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionValueRuleServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionValueRuleServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -157,7 +161,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionValueRuleServiceAsyncClient: The constructed client. """ - return ConversionValueRuleServiceClient.from_service_account_file.__func__(ConversionValueRuleServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionValueRuleServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionValueRuleServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/conversion_value_rule_service/client.py b/google/ads/googleads/v22/services/services/conversion_value_rule_service/client.py index d3207cec0..4e2daa02d 100644 --- a/google/ads/googleads/v22/services/services/conversion_value_rule_service/client.py +++ b/google/ads/googleads/v22/services/services/conversion_value_rule_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( conversion_value_rule_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -418,14 +446,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionValueRuleServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -433,7 +457,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -465,22 +489,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionValueRuleServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/conversion_value_rule_service/transports/base.py b/google/ads/googleads/v22/services/services/conversion_value_rule_service/transports/base.py index 8a22d33fc..21226ff48 100644 --- a/google/ads/googleads/v22/services/services/conversion_value_rule_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/conversion_value_rule_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/async_client.py b/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/async_client.py index 9626dafe4..5a7242a34 100644 --- a/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/async_client.py +++ b/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( conversion_value_rule_set_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -137,7 +136,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ConversionValueRuleSetServiceAsyncClient: The constructed client. """ - return ConversionValueRuleSetServiceClient.from_service_account_info.__func__(ConversionValueRuleSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ConversionValueRuleSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ConversionValueRuleSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -153,7 +157,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConversionValueRuleSetServiceAsyncClient: The constructed client. """ - return ConversionValueRuleSetServiceClient.from_service_account_file.__func__(ConversionValueRuleSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ConversionValueRuleSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ConversionValueRuleSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/client.py b/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/client.py index f2255d6e8..a62d20d7d 100644 --- a/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/client.py +++ b/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( conversion_value_rule_set_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( ConversionValueRuleSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -401,14 +429,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ConversionValueRuleSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -416,7 +440,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -448,22 +472,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ConversionValueRuleSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/transports/base.py b/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/transports/base.py index 5fb2940ec..bfb00d053 100644 --- a/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/conversion_value_rule_set_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/custom_audience_service/async_client.py b/google/ads/googleads/v22/services/services/custom_audience_service/async_client.py index 91781c7b4..9ee4e2653 100644 --- a/google/ads/googleads/v22/services/services/custom_audience_service/async_client.py +++ b/google/ads/googleads/v22/services/services/custom_audience_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomAudienceServiceAsyncClient: The constructed client. """ - return CustomAudienceServiceClient.from_service_account_info.__func__(CustomAudienceServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomAudienceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomAudienceServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomAudienceServiceAsyncClient: The constructed client. """ - return CustomAudienceServiceClient.from_service_account_file.__func__(CustomAudienceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomAudienceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomAudienceServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/custom_audience_service/client.py b/google/ads/googleads/v22/services/services/custom_audience_service/client.py index fc0fc9ad0..52349baeb 100644 --- a/google/ads/googleads/v22/services/services/custom_audience_service/client.py +++ b/google/ads/googleads/v22/services/services/custom_audience_service/client.py @@ -145,6 +145,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -336,14 +364,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomAudienceServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -351,7 +375,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -383,22 +407,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomAudienceServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/custom_audience_service/transports/base.py b/google/ads/googleads/v22/services/services/custom_audience_service/transports/base.py index 4b8bb1eb3..109855887 100644 --- a/google/ads/googleads/v22/services/services/custom_audience_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/custom_audience_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/custom_conversion_goal_service/async_client.py b/google/ads/googleads/v22/services/services/custom_conversion_goal_service/async_client.py index c35d31e2d..e9eb5b30c 100644 --- a/google/ads/googleads/v22/services/services/custom_conversion_goal_service/async_client.py +++ b/google/ads/googleads/v22/services/services/custom_conversion_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomConversionGoalServiceAsyncClient: The constructed client. """ - return CustomConversionGoalServiceClient.from_service_account_info.__func__(CustomConversionGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomConversionGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomConversionGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomConversionGoalServiceAsyncClient: The constructed client. """ - return CustomConversionGoalServiceClient.from_service_account_file.__func__(CustomConversionGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomConversionGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomConversionGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/custom_conversion_goal_service/client.py b/google/ads/googleads/v22/services/services/custom_conversion_goal_service/client.py index 8a9baef58..bc31281c6 100644 --- a/google/ads/googleads/v22/services/services/custom_conversion_goal_service/client.py +++ b/google/ads/googleads/v22/services/services/custom_conversion_goal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -365,14 +393,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomConversionGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -380,7 +404,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -412,22 +436,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomConversionGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/custom_conversion_goal_service/transports/base.py b/google/ads/googleads/v22/services/services/custom_conversion_goal_service/transports/base.py index 97558425a..318034839 100644 --- a/google/ads/googleads/v22/services/services/custom_conversion_goal_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/custom_conversion_goal_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/custom_interest_service/async_client.py b/google/ads/googleads/v22/services/services/custom_interest_service/async_client.py index 8f9576eb6..811537195 100644 --- a/google/ads/googleads/v22/services/services/custom_interest_service/async_client.py +++ b/google/ads/googleads/v22/services/services/custom_interest_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomInterestServiceAsyncClient: The constructed client. """ - return CustomInterestServiceClient.from_service_account_info.__func__(CustomInterestServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomInterestServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomInterestServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomInterestServiceAsyncClient: The constructed client. """ - return CustomInterestServiceClient.from_service_account_file.__func__(CustomInterestServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomInterestServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomInterestServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/custom_interest_service/client.py b/google/ads/googleads/v22/services/services/custom_interest_service/client.py index f6075762e..87d66a136 100644 --- a/google/ads/googleads/v22/services/services/custom_interest_service/client.py +++ b/google/ads/googleads/v22/services/services/custom_interest_service/client.py @@ -145,6 +145,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -336,14 +364,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomInterestServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -351,7 +375,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -383,22 +407,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomInterestServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/custom_interest_service/transports/base.py b/google/ads/googleads/v22/services/services/custom_interest_service/transports/base.py index acec67404..1d88509de 100644 --- a/google/ads/googleads/v22/services/services/custom_interest_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/custom_interest_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_asset_service/async_client.py b/google/ads/googleads/v22/services/services/customer_asset_service/async_client.py index d90c7b545..1b3f9d0b9 100644 --- a/google/ads/googleads/v22/services/services/customer_asset_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_asset_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import customer_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerAssetServiceTransport, DEFAULT_CLIENT_INFO from .client import CustomerAssetServiceClient @@ -114,7 +113,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerAssetServiceAsyncClient: The constructed client. """ - return CustomerAssetServiceClient.from_service_account_info.__func__(CustomerAssetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerAssetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerAssetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +134,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerAssetServiceAsyncClient: The constructed client. """ - return CustomerAssetServiceClient.from_service_account_file.__func__(CustomerAssetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerAssetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerAssetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_asset_service/client.py b/google/ads/googleads/v22/services/services/customer_asset_service/client.py index d6e3bc1f0..1c8b14251 100644 --- a/google/ads/googleads/v22/services/services/customer_asset_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_asset_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import customer_asset_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerAssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CustomerAssetServiceGrpcTransport from .transports.grpc_asyncio import CustomerAssetServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -358,14 +386,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerAssetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -373,7 +397,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -405,22 +429,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerAssetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_asset_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_asset_service/transports/base.py index 0be6d218f..62dde6a37 100644 --- a/google/ads/googleads/v22/services/services/customer_asset_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_asset_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_asset_set_service/async_client.py b/google/ads/googleads/v22/services/services/customer_asset_set_service/async_client.py index 12de110a9..dade09f10 100644 --- a/google/ads/googleads/v22/services/services/customer_asset_set_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_asset_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import customer_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerAssetSetServiceAsyncClient: The constructed client. """ - return CustomerAssetSetServiceClient.from_service_account_info.__func__(CustomerAssetSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerAssetSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerAssetSetServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerAssetSetServiceAsyncClient: The constructed client. """ - return CustomerAssetSetServiceClient.from_service_account_file.__func__(CustomerAssetSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerAssetSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerAssetSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_asset_set_service/client.py b/google/ads/googleads/v22/services/services/customer_asset_set_service/client.py index 71daed85f..32eca917c 100644 --- a/google/ads/googleads/v22/services/services/customer_asset_set_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_asset_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import customer_asset_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerAssetSetServiceTransport, DEFAULT_CLIENT_INFO, @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -379,14 +407,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerAssetSetServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -394,7 +418,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -426,22 +450,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerAssetSetServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_asset_set_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_asset_set_service/transports/base.py index 20ee65951..83338d0b0 100644 --- a/google/ads/googleads/v22/services/services/customer_asset_set_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_asset_set_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_client_link_service/async_client.py b/google/ads/googleads/v22/services/services/customer_client_link_service/async_client.py index 68b967c5e..452732216 100644 --- a/google/ads/googleads/v22/services/services/customer_client_link_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_client_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerClientLinkServiceAsyncClient: The constructed client. """ - return CustomerClientLinkServiceClient.from_service_account_info.__func__(CustomerClientLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerClientLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerClientLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerClientLinkServiceAsyncClient: The constructed client. """ - return CustomerClientLinkServiceClient.from_service_account_file.__func__(CustomerClientLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerClientLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerClientLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_client_link_service/client.py b/google/ads/googleads/v22/services/services/customer_client_link_service/client.py index f28f625fd..34df889f0 100644 --- a/google/ads/googleads/v22/services/services/customer_client_link_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_client_link_service/client.py @@ -142,6 +142,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -350,14 +378,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerClientLinkServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -365,7 +389,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -397,22 +421,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerClientLinkServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_client_link_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_client_link_service/transports/base.py index 46d237613..894d0de2c 100644 --- a/google/ads/googleads/v22/services/services/customer_client_link_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_client_link_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_conversion_goal_service/async_client.py b/google/ads/googleads/v22/services/services/customer_conversion_goal_service/async_client.py index 4c6a4fbc6..7b29b28cd 100644 --- a/google/ads/googleads/v22/services/services/customer_conversion_goal_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_conversion_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerConversionGoalServiceAsyncClient: The constructed client. """ - return CustomerConversionGoalServiceClient.from_service_account_info.__func__(CustomerConversionGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerConversionGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerConversionGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerConversionGoalServiceAsyncClient: The constructed client. """ - return CustomerConversionGoalServiceClient.from_service_account_file.__func__(CustomerConversionGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerConversionGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerConversionGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_conversion_goal_service/client.py b/google/ads/googleads/v22/services/services/customer_conversion_goal_service/client.py index 5040f5b01..e3e6d2413 100644 --- a/google/ads/googleads/v22/services/services/customer_conversion_goal_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_conversion_goal_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -347,14 +375,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerConversionGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -362,7 +386,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -394,22 +418,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerConversionGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_conversion_goal_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_conversion_goal_service/transports/base.py index e1b12a08b..81f9d19ff 100644 --- a/google/ads/googleads/v22/services/services/customer_conversion_goal_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_conversion_goal_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_customizer_service/async_client.py b/google/ads/googleads/v22/services/services/customer_customizer_service/async_client.py index 420749553..8a9bfe944 100644 --- a/google/ads/googleads/v22/services/services/customer_customizer_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_customizer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import customer_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerCustomizerServiceAsyncClient: The constructed client. """ - return CustomerCustomizerServiceClient.from_service_account_info.__func__(CustomerCustomizerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerCustomizerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerCustomizerServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerCustomizerServiceAsyncClient: The constructed client. """ - return CustomerCustomizerServiceClient.from_service_account_file.__func__(CustomerCustomizerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerCustomizerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerCustomizerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_customizer_service/client.py b/google/ads/googleads/v22/services/services/customer_customizer_service/client.py index 0ab2f7d70..3d07e19ad 100644 --- a/google/ads/googleads/v22/services/services/customer_customizer_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_customizer_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import customer_customizer_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerCustomizerServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -364,14 +392,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerCustomizerServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -379,7 +403,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -411,22 +435,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerCustomizerServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_customizer_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_customizer_service/transports/base.py index 375a2eb07..567ba5e36 100644 --- a/google/ads/googleads/v22/services/services/customer_customizer_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_customizer_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_label_service/async_client.py b/google/ads/googleads/v22/services/services/customer_label_service/async_client.py index 22c007c33..a993600e5 100644 --- a/google/ads/googleads/v22/services/services/customer_label_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import customer_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerLabelServiceTransport, DEFAULT_CLIENT_INFO from .client import CustomerLabelServiceClient @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerLabelServiceAsyncClient: The constructed client. """ - return CustomerLabelServiceClient.from_service_account_info.__func__(CustomerLabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerLabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerLabelServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerLabelServiceAsyncClient: The constructed client. """ - return CustomerLabelServiceClient.from_service_account_file.__func__(CustomerLabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerLabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerLabelServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_label_service/client.py b/google/ads/googleads/v22/services/services/customer_label_service/client.py index 43a4d94d4..6dbf85380 100644 --- a/google/ads/googleads/v22/services/services/customer_label_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import customer_label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import CustomerLabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CustomerLabelServiceGrpcTransport from .transports.grpc_asyncio import CustomerLabelServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -371,14 +399,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerLabelServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -386,7 +410,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -418,22 +442,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerLabelServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_label_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_label_service/transports/base.py index ace200eb3..4c3f8a93c 100644 --- a/google/ads/googleads/v22/services/services/customer_label_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_label_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/async_client.py b/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/async_client.py index 6a1dc50d8..f5e2d88f5 100644 --- a/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerLifecycleGoalServiceAsyncClient: The constructed client. """ - return CustomerLifecycleGoalServiceClient.from_service_account_info.__func__(CustomerLifecycleGoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerLifecycleGoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerLifecycleGoalServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerLifecycleGoalServiceAsyncClient: The constructed client. """ - return CustomerLifecycleGoalServiceClient.from_service_account_file.__func__(CustomerLifecycleGoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerLifecycleGoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerLifecycleGoalServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -337,7 +346,7 @@ async def configure_customer_lifecycle_goals( Args: request (Optional[Union[google.ads.googleads.v22.services.types.ConfigureCustomerLifecycleGoalsRequest, dict]]): The request object. Request message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v22.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. customer_id (:class:`str`): Required. The ID of the customer performing the upload. @@ -363,7 +372,7 @@ async def configure_customer_lifecycle_goals( Returns: google.ads.googleads.v22.services.types.ConfigureCustomerLifecycleGoalsResponse: Response message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v22.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/client.py b/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/client.py index 81c656a6c..ce4edce71 100644 --- a/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -347,14 +375,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerLifecycleGoalServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -362,7 +386,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -394,22 +418,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerLifecycleGoalServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -793,7 +813,7 @@ def configure_customer_lifecycle_goals( Args: request (Union[google.ads.googleads.v22.services.types.ConfigureCustomerLifecycleGoalsRequest, dict]): The request object. Request message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v22.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. customer_id (str): Required. The ID of the customer performing the upload. @@ -819,7 +839,7 @@ def configure_customer_lifecycle_goals( Returns: google.ads.googleads.v22.services.types.ConfigureCustomerLifecycleGoalsResponse: Response message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v22.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/transports/base.py index 36a45e572..45a772e47 100644 --- a/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_lifecycle_goal_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_manager_link_service/async_client.py b/google/ads/googleads/v22/services/services/customer_manager_link_service/async_client.py index c5e3e7003..f4296bbc5 100644 --- a/google/ads/googleads/v22/services/services/customer_manager_link_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_manager_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerManagerLinkServiceAsyncClient: The constructed client. """ - return CustomerManagerLinkServiceClient.from_service_account_info.__func__(CustomerManagerLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerManagerLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerManagerLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerManagerLinkServiceAsyncClient: The constructed client. """ - return CustomerManagerLinkServiceClient.from_service_account_file.__func__(CustomerManagerLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerManagerLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerManagerLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_manager_link_service/client.py b/google/ads/googleads/v22/services/services/customer_manager_link_service/client.py index 0f01bc5ab..077901ba5 100644 --- a/google/ads/googleads/v22/services/services/customer_manager_link_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_manager_link_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -362,14 +390,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerManagerLinkServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -377,7 +401,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -409,22 +433,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerManagerLinkServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_manager_link_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_manager_link_service/transports/base.py index ca16658e4..59de9414d 100644 --- a/google/ads/googleads/v22/services/services/customer_manager_link_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_manager_link_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_negative_criterion_service/async_client.py b/google/ads/googleads/v22/services/services/customer_negative_criterion_service/async_client.py index 7d77e769d..8571f9a3e 100644 --- a/google/ads/googleads/v22/services/services/customer_negative_criterion_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_negative_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( customer_negative_criterion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerNegativeCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerNegativeCriterionServiceAsyncClient: The constructed client. """ - return CustomerNegativeCriterionServiceClient.from_service_account_info.__func__(CustomerNegativeCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerNegativeCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerNegativeCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerNegativeCriterionServiceAsyncClient: The constructed client. """ - return CustomerNegativeCriterionServiceClient.from_service_account_file.__func__(CustomerNegativeCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerNegativeCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerNegativeCriterionServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_negative_criterion_service/client.py b/google/ads/googleads/v22/services/services/customer_negative_criterion_service/client.py index 4bc238efb..92561c801 100644 --- a/google/ads/googleads/v22/services/services/customer_negative_criterion_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_negative_criterion_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( customer_negative_criterion_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerNegativeCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -364,14 +392,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerNegativeCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -379,7 +403,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -411,22 +435,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerNegativeCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_negative_criterion_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_negative_criterion_service/transports/base.py index 5df2622f3..3b1af46e4 100644 --- a/google/ads/googleads/v22/services/services/customer_negative_criterion_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_negative_criterion_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_service/async_client.py b/google/ads/googleads/v22/services/services/customer_service/async_client.py index 4bcc9fe2b..dc5a680e6 100644 --- a/google/ads/googleads/v22/services/services/customer_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -114,7 +113,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerServiceAsyncClient: The constructed client. """ - return CustomerServiceClient.from_service_account_info.__func__(CustomerServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(CustomerServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerServiceAsyncClient: The constructed client. """ - return CustomerServiceClient.from_service_account_file.__func__(CustomerServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_service/client.py b/google/ads/googleads/v22/services/services/customer_service/client.py index 892526259..5b516f6d2 100644 --- a/google/ads/googleads/v22/services/services/customer_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_service/client.py @@ -134,6 +134,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -340,14 +368,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = CustomerServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -355,7 +377,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -387,22 +409,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = CustomerServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_service/transports/base.py index 82b9712a7..93429e0c5 100644 --- a/google/ads/googleads/v22/services/services/customer_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py b/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py index 541b0d16a..301272399 100644 --- a/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( customer_sk_ad_network_conversion_value_schema_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerSkAdNetworkConversionValueSchemaServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient: The constructed client. """ - return CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_info.__func__(CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +146,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient: The constructed client. """ - return CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_file.__func__(CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerSkAdNetworkConversionValueSchemaServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py b/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py index 08fc3052c..f5ad07761 100644 --- a/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/client.py @@ -52,7 +52,7 @@ from google.ads.googleads.v22.services.types import ( customer_sk_ad_network_conversion_value_schema_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomerSkAdNetworkConversionValueSchemaServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +383,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +415,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerSkAdNetworkConversionValueSchemaServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py index 0f604e8e7..847d4633d 100644 --- a/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_sk_ad_network_conversion_value_schema_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/async_client.py b/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/async_client.py index 4618f23a7..72cd3c0a7 100644 --- a/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,15 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerUserAccessInvitationServiceAsyncClient: The constructed client. """ - return CustomerUserAccessInvitationServiceClient.from_service_account_info.__func__(CustomerUserAccessInvitationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerUserAccessInvitationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerUserAccessInvitationServiceAsyncClient, + info, + *args, + **kwargs, + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +147,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerUserAccessInvitationServiceAsyncClient: The constructed client. """ - return CustomerUserAccessInvitationServiceClient.from_service_account_file.__func__(CustomerUserAccessInvitationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerUserAccessInvitationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerUserAccessInvitationServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/client.py b/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/client.py index 0d6e3b3cc..2d5229858 100644 --- a/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/client.py @@ -148,6 +148,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -339,14 +367,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerUserAccessInvitationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -354,7 +378,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -386,22 +410,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerUserAccessInvitationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/transports/base.py index 4ce891490..4539cc71b 100644 --- a/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_user_access_invitation_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customer_user_access_service/async_client.py b/google/ads/googleads/v22/services/services/customer_user_access_service/async_client.py index e11ae7abb..d2a18eaa9 100644 --- a/google/ads/googleads/v22/services/services/customer_user_access_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customer_user_access_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomerUserAccessServiceAsyncClient: The constructed client. """ - return CustomerUserAccessServiceClient.from_service_account_info.__func__(CustomerUserAccessServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomerUserAccessServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomerUserAccessServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomerUserAccessServiceAsyncClient: The constructed client. """ - return CustomerUserAccessServiceClient.from_service_account_file.__func__(CustomerUserAccessServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomerUserAccessServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomerUserAccessServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customer_user_access_service/client.py b/google/ads/googleads/v22/services/services/customer_user_access_service/client.py index 4048813a2..56e2f940d 100644 --- a/google/ads/googleads/v22/services/services/customer_user_access_service/client.py +++ b/google/ads/googleads/v22/services/services/customer_user_access_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomerUserAccessServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +374,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +406,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomerUserAccessServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customer_user_access_service/transports/base.py b/google/ads/googleads/v22/services/services/customer_user_access_service/transports/base.py index 610903b03..b1793e66a 100644 --- a/google/ads/googleads/v22/services/services/customer_user_access_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customer_user_access_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/customizer_attribute_service/async_client.py b/google/ads/googleads/v22/services/services/customizer_attribute_service/async_client.py index bcdd04354..28cd5c314 100644 --- a/google/ads/googleads/v22/services/services/customizer_attribute_service/async_client.py +++ b/google/ads/googleads/v22/services/services/customizer_attribute_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import customizer_attribute_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomizerAttributeServiceTransport, DEFAULT_CLIENT_INFO, @@ -117,7 +116,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: CustomizerAttributeServiceAsyncClient: The constructed client. """ - return CustomizerAttributeServiceClient.from_service_account_info.__func__(CustomizerAttributeServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + CustomizerAttributeServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + CustomizerAttributeServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -133,7 +137,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CustomizerAttributeServiceAsyncClient: The constructed client. """ - return CustomizerAttributeServiceClient.from_service_account_file.__func__(CustomizerAttributeServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + CustomizerAttributeServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + CustomizerAttributeServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/customizer_attribute_service/client.py b/google/ads/googleads/v22/services/services/customizer_attribute_service/client.py index 7d8ae9ca4..04b04c9be 100644 --- a/google/ads/googleads/v22/services/services/customizer_attribute_service/client.py +++ b/google/ads/googleads/v22/services/services/customizer_attribute_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import customizer_attribute_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( CustomizerAttributeServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + CustomizerAttributeServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +383,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +415,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + CustomizerAttributeServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/customizer_attribute_service/transports/base.py b/google/ads/googleads/v22/services/services/customizer_attribute_service/transports/base.py index 2cf0764de..8eeef837e 100644 --- a/google/ads/googleads/v22/services/services/customizer_attribute_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/customizer_attribute_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/data_link_service/async_client.py b/google/ads/googleads/v22/services/services/data_link_service/async_client.py index 557d4ea22..a306850cc 100644 --- a/google/ads/googleads/v22/services/services/data_link_service/async_client.py +++ b/google/ads/googleads/v22/services/services/data_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -113,7 +112,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: DataLinkServiceAsyncClient: The constructed client. """ - return DataLinkServiceClient.from_service_account_info.__func__(DataLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + DataLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(DataLinkServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -129,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: DataLinkServiceAsyncClient: The constructed client. """ - return DataLinkServiceClient.from_service_account_file.__func__(DataLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + DataLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + DataLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/data_link_service/client.py b/google/ads/googleads/v22/services/services/data_link_service/client.py index 89c93abc7..f35cab10b 100644 --- a/google/ads/googleads/v22/services/services/data_link_service/client.py +++ b/google/ads/googleads/v22/services/services/data_link_service/client.py @@ -139,6 +139,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -332,14 +360,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = DataLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -347,7 +369,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -379,22 +401,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = DataLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/data_link_service/transports/base.py b/google/ads/googleads/v22/services/services/data_link_service/transports/base.py index f0fcd2eeb..e86735d19 100644 --- a/google/ads/googleads/v22/services/services/data_link_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/data_link_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/experiment_arm_service/async_client.py b/google/ads/googleads/v22/services/services/experiment_arm_service/async_client.py index f88e60297..709193cb7 100644 --- a/google/ads/googleads/v22/services/services/experiment_arm_service/async_client.py +++ b/google/ads/googleads/v22/services/services/experiment_arm_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import experiment_arm_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentArmServiceTransport, DEFAULT_CLIENT_INFO from .client import ExperimentArmServiceClient @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ExperimentArmServiceAsyncClient: The constructed client. """ - return ExperimentArmServiceClient.from_service_account_info.__func__(ExperimentArmServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ExperimentArmServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ExperimentArmServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ExperimentArmServiceAsyncClient: The constructed client. """ - return ExperimentArmServiceClient.from_service_account_file.__func__(ExperimentArmServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ExperimentArmServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ExperimentArmServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/experiment_arm_service/client.py b/google/ads/googleads/v22/services/services/experiment_arm_service/client.py index 1db8a4f0c..a33d0f138 100644 --- a/google/ads/googleads/v22/services/services/experiment_arm_service/client.py +++ b/google/ads/googleads/v22/services/services/experiment_arm_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import experiment_arm_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentArmServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ExperimentArmServiceGrpcTransport from .transports.grpc_asyncio import ExperimentArmServiceGrpcAsyncIOTransport @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -379,14 +407,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ExperimentArmServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -394,7 +418,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -426,22 +450,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ExperimentArmServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/experiment_arm_service/transports/base.py b/google/ads/googleads/v22/services/services/experiment_arm_service/transports/base.py index 784cb4106..455dd8e72 100644 --- a/google/ads/googleads/v22/services/services/experiment_arm_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/experiment_arm_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/experiment_service/async_client.py b/google/ads/googleads/v22/services/services/experiment_service/async_client.py index 6ade00ea0..5315b9afe 100644 --- a/google/ads/googleads/v22/services/services/experiment_service/async_client.py +++ b/google/ads/googleads/v22/services/services/experiment_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -35,10 +34,10 @@ from google.ads.googleads.v22.services.services.experiment_service import pagers from google.ads.googleads.v22.services.types import experiment_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO from .client import ExperimentServiceClient @@ -124,7 +123,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ExperimentServiceAsyncClient: The constructed client. """ - return ExperimentServiceClient.from_service_account_info.__func__(ExperimentServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ExperimentServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(ExperimentServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +142,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ExperimentServiceAsyncClient: The constructed client. """ - return ExperimentServiceClient.from_service_account_file.__func__(ExperimentServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ExperimentServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ExperimentServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/experiment_service/client.py b/google/ads/googleads/v22/services/services/experiment_service/client.py index dc3ea335d..5e3a6817d 100644 --- a/google/ads/googleads/v22/services/services/experiment_service/client.py +++ b/google/ads/googleads/v22/services/services/experiment_service/client.py @@ -61,10 +61,10 @@ from google.ads.googleads.v22.services.services.experiment_service import pagers from google.ads.googleads.v22.services.types import experiment_service -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ExperimentServiceGrpcTransport from .transports.grpc_asyncio import ExperimentServiceGrpcAsyncIOTransport @@ -148,6 +148,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -379,14 +407,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = ExperimentServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -394,7 +416,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -426,22 +448,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ExperimentServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/experiment_service/pagers.py b/google/ads/googleads/v22/services/services/experiment_service/pagers.py index e7030f27d..2e5a4bc03 100644 --- a/google/ads/googleads/v22/services/services/experiment_service/pagers.py +++ b/google/ads/googleads/v22/services/services/experiment_service/pagers.py @@ -37,7 +37,7 @@ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import experiment_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore class ListExperimentAsyncErrorsPager: diff --git a/google/ads/googleads/v22/services/services/experiment_service/transports/base.py b/google/ads/googleads/v22/services/services/experiment_service/transports/base.py index 0baa35f85..9353fe03d 100644 --- a/google/ads/googleads/v22/services/services/experiment_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/experiment_service/transports/base.py @@ -28,7 +28,7 @@ from google.ads.googleads.v22.services.types import experiment_service from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/experiment_service/transports/grpc.py b/google/ads/googleads/v22/services/services/experiment_service/transports/grpc.py index 4e73f1052..46f26a120 100644 --- a/google/ads/googleads/v22/services/services/experiment_service/transports/grpc.py +++ b/google/ads/googleads/v22/services/services/experiment_service/transports/grpc.py @@ -32,7 +32,7 @@ from google.ads.googleads.v22.services.types import experiment_service from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO try: diff --git a/google/ads/googleads/v22/services/services/experiment_service/transports/grpc_asyncio.py b/google/ads/googleads/v22/services/services/experiment_service/transports/grpc_asyncio.py index d4695513e..24794f7aa 100644 --- a/google/ads/googleads/v22/services/services/experiment_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v22/services/services/experiment_service/transports/grpc_asyncio.py @@ -33,7 +33,7 @@ from google.ads.googleads.v22.services.types import experiment_service from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import ExperimentServiceTransport, DEFAULT_CLIENT_INFO try: diff --git a/google/ads/googleads/v22/services/services/geo_target_constant_service/async_client.py b/google/ads/googleads/v22/services/services/geo_target_constant_service/async_client.py index 9477ec195..ab61554f6 100644 --- a/google/ads/googleads/v22/services/services/geo_target_constant_service/async_client.py +++ b/google/ads/googleads/v22/services/services/geo_target_constant_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -114,7 +113,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GeoTargetConstantServiceAsyncClient: The constructed client. """ - return GeoTargetConstantServiceClient.from_service_account_info.__func__(GeoTargetConstantServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GeoTargetConstantServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + GeoTargetConstantServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -130,7 +134,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GeoTargetConstantServiceAsyncClient: The constructed client. """ - return GeoTargetConstantServiceClient.from_service_account_file.__func__(GeoTargetConstantServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GeoTargetConstantServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + GeoTargetConstantServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/geo_target_constant_service/client.py b/google/ads/googleads/v22/services/services/geo_target_constant_service/client.py index 5e0099525..68d97cffd 100644 --- a/google/ads/googleads/v22/services/services/geo_target_constant_service/client.py +++ b/google/ads/googleads/v22/services/services/geo_target_constant_service/client.py @@ -142,6 +142,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -328,14 +356,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + GeoTargetConstantServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -343,7 +367,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -375,22 +399,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + GeoTargetConstantServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/geo_target_constant_service/transports/base.py b/google/ads/googleads/v22/services/services/geo_target_constant_service/transports/base.py index 812acf676..53157b8af 100644 --- a/google/ads/googleads/v22/services/services/geo_target_constant_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/geo_target_constant_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/goal_service/async_client.py b/google/ads/googleads/v22/services/services/goal_service/async_client.py index e6aea4fe2..575867b7b 100644 --- a/google/ads/googleads/v22/services/services/goal_service/async_client.py +++ b/google/ads/googleads/v22/services/services/goal_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import goal_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import GoalServiceTransport, DEFAULT_CLIENT_INFO from .client import GoalServiceClient @@ -102,7 +101,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GoalServiceAsyncClient: The constructed client. """ - return GoalServiceClient.from_service_account_info.__func__(GoalServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GoalServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(GoalServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -118,7 +120,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GoalServiceAsyncClient: The constructed client. """ - return GoalServiceClient.from_service_account_file.__func__(GoalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GoalServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(GoalServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/goal_service/client.py b/google/ads/googleads/v22/services/services/goal_service/client.py index 8cf554c43..1451f47d0 100644 --- a/google/ads/googleads/v22/services/services/goal_service/client.py +++ b/google/ads/googleads/v22/services/services/goal_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import goal_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import GoalServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import GoalServiceGrpcTransport from .transports.grpc_asyncio import GoalServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -350,14 +378,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = GoalServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -365,7 +387,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -397,22 +419,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = GoalServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/goal_service/transports/base.py b/google/ads/googleads/v22/services/services/goal_service/transports/base.py index 0d5ae467b..5d34c5dc8 100644 --- a/google/ads/googleads/v22/services/services/goal_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/goal_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/google_ads_field_service/async_client.py b/google/ads/googleads/v22/services/services/google_ads_field_service/async_client.py index 1f9997a95..570907b6b 100644 --- a/google/ads/googleads/v22/services/services/google_ads_field_service/async_client.py +++ b/google/ads/googleads/v22/services/services/google_ads_field_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GoogleAdsFieldServiceAsyncClient: The constructed client. """ - return GoogleAdsFieldServiceClient.from_service_account_info.__func__(GoogleAdsFieldServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GoogleAdsFieldServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + GoogleAdsFieldServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GoogleAdsFieldServiceAsyncClient: The constructed client. """ - return GoogleAdsFieldServiceClient.from_service_account_file.__func__(GoogleAdsFieldServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GoogleAdsFieldServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + GoogleAdsFieldServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/google_ads_field_service/client.py b/google/ads/googleads/v22/services/services/google_ads_field_service/client.py index c02d17dac..392715748 100644 --- a/google/ads/googleads/v22/services/services/google_ads_field_service/client.py +++ b/google/ads/googleads/v22/services/services/google_ads_field_service/client.py @@ -139,6 +139,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -325,14 +353,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + GoogleAdsFieldServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -340,7 +364,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -372,22 +396,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + GoogleAdsFieldServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/google_ads_field_service/transports/base.py b/google/ads/googleads/v22/services/services/google_ads_field_service/transports/base.py index 61106862d..e00a3f307 100644 --- a/google/ads/googleads/v22/services/services/google_ads_field_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/google_ads_field_service/transports/base.py @@ -83,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -100,12 +98,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/google_ads_service/async_client.py b/google/ads/googleads/v22/services/services/google_ads_service/async_client.py index 7554770b8..2b218050d 100644 --- a/google/ads/googleads/v22/services/services/google_ads_service/async_client.py +++ b/google/ads/googleads/v22/services/services/google_ads_service/async_client.py @@ -34,7 +34,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -44,8 +43,8 @@ from google.ads.googleads.v22.services.services.google_ads_service import pagers from google.ads.googleads.v22.services.types import google_ads_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import GoogleAdsServiceTransport, DEFAULT_CLIENT_INFO from .client import GoogleAdsServiceClient @@ -1097,7 +1096,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: GoogleAdsServiceAsyncClient: The constructed client. """ - return GoogleAdsServiceClient.from_service_account_info.__func__(GoogleAdsServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + GoogleAdsServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(GoogleAdsServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -1113,7 +1115,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GoogleAdsServiceAsyncClient: The constructed client. """ - return GoogleAdsServiceClient.from_service_account_file.__func__(GoogleAdsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + GoogleAdsServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + GoogleAdsServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/google_ads_service/client.py b/google/ads/googleads/v22/services/services/google_ads_service/client.py index dc5e3ffe4..7b8bfc78e 100644 --- a/google/ads/googleads/v22/services/services/google_ads_service/client.py +++ b/google/ads/googleads/v22/services/services/google_ads_service/client.py @@ -62,8 +62,8 @@ from google.ads.googleads.v22.services.services.google_ads_service import pagers from google.ads.googleads.v22.services.types import google_ads_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import GoogleAdsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import GoogleAdsServiceGrpcTransport from .transports.grpc_asyncio import GoogleAdsServiceGrpcAsyncIOTransport @@ -147,6 +147,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -4114,14 +4142,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = GoogleAdsServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -4129,7 +4151,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -4161,22 +4183,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = GoogleAdsServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/google_ads_service/transports/base.py b/google/ads/googleads/v22/services/services/google_ads_service/transports/base.py index 509566613..f72ebcd7f 100644 --- a/google/ads/googleads/v22/services/services/google_ads_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/google_ads_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/identity_verification_service/async_client.py b/google/ads/googleads/v22/services/services/identity_verification_service/async_client.py index 818d7515b..597897c19 100644 --- a/google/ads/googleads/v22/services/services/identity_verification_service/async_client.py +++ b/google/ads/googleads/v22/services/services/identity_verification_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -113,7 +112,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: IdentityVerificationServiceAsyncClient: The constructed client. """ - return IdentityVerificationServiceClient.from_service_account_info.__func__(IdentityVerificationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + IdentityVerificationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + IdentityVerificationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -129,7 +133,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: IdentityVerificationServiceAsyncClient: The constructed client. """ - return IdentityVerificationServiceClient.from_service_account_file.__func__(IdentityVerificationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + IdentityVerificationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + IdentityVerificationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -324,7 +333,7 @@ async def start_identity_verification( Args: request (Optional[Union[google.ads.googleads.v22.services.types.StartIdentityVerificationRequest, dict]]): The request object. Request message for - [IdentityVerificationService.StartIdentityVerification]. + [StartIdentityVerification][google.ads.googleads.v22.services.IdentityVerificationService.StartIdentityVerification]. customer_id (:class:`str`): Required. The Id of the customer for whom we are creating this verification. @@ -428,7 +437,7 @@ async def get_identity_verification( Args: request (Optional[Union[google.ads.googleads.v22.services.types.GetIdentityVerificationRequest, dict]]): The request object. Request message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v22.services.IdentityVerificationService.GetIdentityVerification]. customer_id (:class:`str`): Required. The ID of the customer for whom we are requesting verification @@ -448,7 +457,7 @@ async def get_identity_verification( Returns: google.ads.googleads.v22.services.types.GetIdentityVerificationResponse: Response message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v22.services.IdentityVerificationService.GetIdentityVerification]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/identity_verification_service/client.py b/google/ads/googleads/v22/services/services/identity_verification_service/client.py index 2a0edd960..a40d73c46 100644 --- a/google/ads/googleads/v22/services/services/identity_verification_service/client.py +++ b/google/ads/googleads/v22/services/services/identity_verification_service/client.py @@ -145,6 +145,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -316,14 +344,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + IdentityVerificationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -331,7 +355,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -363,22 +387,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + IdentityVerificationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -758,7 +778,7 @@ def start_identity_verification( Args: request (Union[google.ads.googleads.v22.services.types.StartIdentityVerificationRequest, dict]): The request object. Request message for - [IdentityVerificationService.StartIdentityVerification]. + [StartIdentityVerification][google.ads.googleads.v22.services.IdentityVerificationService.StartIdentityVerification]. customer_id (str): Required. The Id of the customer for whom we are creating this verification. @@ -861,7 +881,7 @@ def get_identity_verification( Args: request (Union[google.ads.googleads.v22.services.types.GetIdentityVerificationRequest, dict]): The request object. Request message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v22.services.IdentityVerificationService.GetIdentityVerification]. customer_id (str): Required. The ID of the customer for whom we are requesting verification @@ -881,7 +901,7 @@ def get_identity_verification( Returns: google.ads.googleads.v22.services.types.GetIdentityVerificationResponse: Response message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v22.services.IdentityVerificationService.GetIdentityVerification]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/identity_verification_service/transports/base.py b/google/ads/googleads/v22/services/services/identity_verification_service/transports/base.py index 04d9c87ab..cd5f43e60 100644 --- a/google/ads/googleads/v22/services/services/identity_verification_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/identity_verification_service/transports/base.py @@ -29,7 +29,7 @@ from google.ads.googleads.v22.services.types import ( identity_verification_service, ) -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -85,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -102,12 +100,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/identity_verification_service/transports/grpc.py b/google/ads/googleads/v22/services/services/identity_verification_service/transports/grpc.py index 64e1e3f3e..d945d8848 100644 --- a/google/ads/googleads/v22/services/services/identity_verification_service/transports/grpc.py +++ b/google/ads/googleads/v22/services/services/identity_verification_service/transports/grpc.py @@ -32,7 +32,7 @@ from google.ads.googleads.v22.services.types import ( identity_verification_service, ) -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import IdentityVerificationServiceTransport, DEFAULT_CLIENT_INFO try: diff --git a/google/ads/googleads/v22/services/services/identity_verification_service/transports/grpc_asyncio.py b/google/ads/googleads/v22/services/services/identity_verification_service/transports/grpc_asyncio.py index 51c6b044f..78f7969ad 100644 --- a/google/ads/googleads/v22/services/services/identity_verification_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v22/services/services/identity_verification_service/transports/grpc_asyncio.py @@ -33,7 +33,7 @@ from google.ads.googleads.v22.services.types import ( identity_verification_service, ) -from google.protobuf import empty_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from .base import IdentityVerificationServiceTransport, DEFAULT_CLIENT_INFO try: diff --git a/google/ads/googleads/v22/services/services/invoice_service/async_client.py b/google/ads/googleads/v22/services/services/invoice_service/async_client.py index 81b38f0b0..ba277cb2b 100644 --- a/google/ads/googleads/v22/services/services/invoice_service/async_client.py +++ b/google/ads/googleads/v22/services/services/invoice_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -104,7 +103,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: InvoiceServiceAsyncClient: The constructed client. """ - return InvoiceServiceClient.from_service_account_info.__func__(InvoiceServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + InvoiceServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(InvoiceServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -120,7 +122,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: InvoiceServiceAsyncClient: The constructed client. """ - return InvoiceServiceClient.from_service_account_file.__func__(InvoiceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + InvoiceServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + InvoiceServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/invoice_service/client.py b/google/ads/googleads/v22/services/services/invoice_service/client.py index 5eafbd090..0bd0c1e8d 100644 --- a/google/ads/googleads/v22/services/services/invoice_service/client.py +++ b/google/ads/googleads/v22/services/services/invoice_service/client.py @@ -136,6 +136,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -327,14 +355,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = InvoiceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -342,7 +364,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -374,22 +396,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = InvoiceServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/invoice_service/transports/base.py b/google/ads/googleads/v22/services/services/invoice_service/transports/base.py index feacae91e..020ad2dd3 100644 --- a/google/ads/googleads/v22/services/services/invoice_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/invoice_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/async_client.py b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/async_client.py index 111f13421..26d334c02 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/async_client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( keyword_plan_ad_group_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -132,7 +131,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanAdGroupKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupKeywordServiceClient.from_service_account_info.__func__(KeywordPlanAdGroupKeywordServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanAdGroupKeywordServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanAdGroupKeywordServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -148,7 +152,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanAdGroupKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupKeywordServiceClient.from_service_account_file.__func__(KeywordPlanAdGroupKeywordServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanAdGroupKeywordServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanAdGroupKeywordServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/client.py b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/client.py index c5bf707f1..a0d9248a5 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( keyword_plan_ad_group_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -162,6 +162,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -373,14 +401,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanAdGroupKeywordServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -388,7 +412,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -420,22 +444,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanAdGroupKeywordServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/transports/base.py b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/transports/base.py index a85fe458a..df2028302 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_keyword_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/async_client.py b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/async_client.py index 24e1ec666..d698db82b 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/async_client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( keyword_plan_ad_group_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanAdGroupServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupServiceClient.from_service_account_info.__func__(KeywordPlanAdGroupServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanAdGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanAdGroupServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanAdGroupServiceAsyncClient: The constructed client. """ - return KeywordPlanAdGroupServiceClient.from_service_account_file.__func__(KeywordPlanAdGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanAdGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanAdGroupServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/client.py b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/client.py index 8afec35c4..ae24c7fd0 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( keyword_plan_ad_group_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanAdGroupServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -366,14 +394,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanAdGroupServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -381,7 +405,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -413,22 +437,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanAdGroupServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/transports/base.py b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/transports/base.py index d2a0bef5c..618a0c89c 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_ad_group_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/async_client.py b/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/async_client.py index 5c7fa8745..b60dc5aa0 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/async_client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( keyword_plan_campaign_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -132,7 +131,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanCampaignKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignKeywordServiceClient.from_service_account_info.__func__(KeywordPlanCampaignKeywordServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanCampaignKeywordServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanCampaignKeywordServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -148,7 +152,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanCampaignKeywordServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignKeywordServiceClient.from_service_account_file.__func__(KeywordPlanCampaignKeywordServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanCampaignKeywordServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanCampaignKeywordServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/client.py b/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/client.py index 58dd1f787..9e05c0d55 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( keyword_plan_campaign_keyword_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignKeywordServiceTransport, DEFAULT_CLIENT_INFO, @@ -160,6 +160,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -371,14 +399,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanCampaignKeywordServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -386,7 +410,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -418,22 +442,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanCampaignKeywordServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/transports/base.py b/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/transports/base.py index e8e5ba3c5..e708224ac 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_campaign_keyword_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/async_client.py b/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/async_client.py index 529a1469b..d049191f9 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/async_client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( keyword_plan_campaign_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignServiceTransport, DEFAULT_CLIENT_INFO, @@ -137,7 +136,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanCampaignServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignServiceClient.from_service_account_info.__func__(KeywordPlanCampaignServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanCampaignServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanCampaignServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -153,7 +157,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanCampaignServiceAsyncClient: The constructed client. """ - return KeywordPlanCampaignServiceClient.from_service_account_file.__func__(KeywordPlanCampaignServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanCampaignServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanCampaignServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/client.py b/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/client.py index cd18682ad..bec618e20 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( keyword_plan_campaign_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( KeywordPlanCampaignServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -396,14 +424,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanCampaignServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -411,7 +435,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -443,22 +467,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanCampaignServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/transports/base.py b/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/transports/base.py index 6b8da327f..7e7aa89b8 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_campaign_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_idea_service/async_client.py b/google/ads/googleads/v22/services/services/keyword_plan_idea_service/async_client.py index bf1933eab..a5da4046f 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_idea_service/async_client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_idea_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanIdeaServiceAsyncClient: The constructed client. """ - return KeywordPlanIdeaServiceClient.from_service_account_info.__func__(KeywordPlanIdeaServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanIdeaServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanIdeaServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +131,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanIdeaServiceAsyncClient: The constructed client. """ - return KeywordPlanIdeaServiceClient.from_service_account_file.__func__(KeywordPlanIdeaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanIdeaServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanIdeaServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -603,7 +612,7 @@ async def generate_keyword_forecast_metrics( Args: request (Optional[Union[google.ads.googleads.v22.services.types.GenerateKeywordForecastMetricsRequest, dict]]): The request object. Request message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v22.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. campaign (:class:`google.ads.googleads.v22.services.types.CampaignToForecast`): Required. The campaign used in the forecast. @@ -622,7 +631,7 @@ async def generate_keyword_forecast_metrics( Returns: google.ads.googleads.v22.services.types.GenerateKeywordForecastMetricsResponse: Response message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v22.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/keyword_plan_idea_service/client.py b/google/ads/googleads/v22/services/services/keyword_plan_idea_service/client.py index bacac35d3..86b938e9a 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_idea_service/client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_idea_service/client.py @@ -151,6 +151,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -322,14 +350,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordPlanIdeaServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -337,7 +361,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -369,22 +393,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordPlanIdeaServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -1039,7 +1059,7 @@ def generate_keyword_forecast_metrics( Args: request (Union[google.ads.googleads.v22.services.types.GenerateKeywordForecastMetricsRequest, dict]): The request object. Request message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v22.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. campaign (google.ads.googleads.v22.services.types.CampaignToForecast): Required. The campaign used in the forecast. @@ -1058,7 +1078,7 @@ def generate_keyword_forecast_metrics( Returns: google.ads.googleads.v22.services.types.GenerateKeywordForecastMetricsResponse: Response message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v22.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/keyword_plan_idea_service/transports/base.py b/google/ads/googleads/v22/services/services/keyword_plan_idea_service/transports/base.py index 754c40be7..2852f5130 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_idea_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_idea_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_service/async_client.py b/google/ads/googleads/v22/services/services/keyword_plan_service/async_client.py index 800c8c089..68def1651 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_service/async_client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import keyword_plan_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import KeywordPlanServiceTransport, DEFAULT_CLIENT_INFO from .client import KeywordPlanServiceClient @@ -110,7 +109,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordPlanServiceAsyncClient: The constructed client. """ - return KeywordPlanServiceClient.from_service_account_info.__func__(KeywordPlanServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordPlanServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordPlanServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -126,7 +130,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordPlanServiceAsyncClient: The constructed client. """ - return KeywordPlanServiceClient.from_service_account_file.__func__(KeywordPlanServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordPlanServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordPlanServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/keyword_plan_service/client.py b/google/ads/googleads/v22/services/services/keyword_plan_service/client.py index 9f9c62d6f..2befbaf03 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_service/client.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import keyword_plan_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import KeywordPlanServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import KeywordPlanServiceGrpcTransport from .transports.grpc_asyncio import KeywordPlanServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = KeywordPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = KeywordPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/keyword_plan_service/transports/base.py b/google/ads/googleads/v22/services/services/keyword_plan_service/transports/base.py index be24d85c6..c1f96b19e 100644 --- a/google/ads/googleads/v22/services/services/keyword_plan_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/keyword_plan_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/keyword_theme_constant_service/async_client.py b/google/ads/googleads/v22/services/services/keyword_theme_constant_service/async_client.py index db4f16ca5..748f5f061 100644 --- a/google/ads/googleads/v22/services/services/keyword_theme_constant_service/async_client.py +++ b/google/ads/googleads/v22/services/services/keyword_theme_constant_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: KeywordThemeConstantServiceAsyncClient: The constructed client. """ - return KeywordThemeConstantServiceClient.from_service_account_info.__func__(KeywordThemeConstantServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + KeywordThemeConstantServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + KeywordThemeConstantServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: KeywordThemeConstantServiceAsyncClient: The constructed client. """ - return KeywordThemeConstantServiceClient.from_service_account_file.__func__(KeywordThemeConstantServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + KeywordThemeConstantServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + KeywordThemeConstantServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/keyword_theme_constant_service/client.py b/google/ads/googleads/v22/services/services/keyword_theme_constant_service/client.py index a35f85f2f..df9cfa7aa 100644 --- a/google/ads/googleads/v22/services/services/keyword_theme_constant_service/client.py +++ b/google/ads/googleads/v22/services/services/keyword_theme_constant_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + KeywordThemeConstantServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +374,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +406,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + KeywordThemeConstantServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/keyword_theme_constant_service/transports/base.py b/google/ads/googleads/v22/services/services/keyword_theme_constant_service/transports/base.py index a7c5736e4..11a53815f 100644 --- a/google/ads/googleads/v22/services/services/keyword_theme_constant_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/keyword_theme_constant_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/label_service/async_client.py b/google/ads/googleads/v22/services/services/label_service/async_client.py index d2189799d..f9b3d44a9 100644 --- a/google/ads/googleads/v22/services/services/label_service/async_client.py +++ b/google/ads/googleads/v22/services/services/label_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import LabelServiceTransport, DEFAULT_CLIENT_INFO from .client import LabelServiceClient @@ -100,7 +99,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: LabelServiceAsyncClient: The constructed client. """ - return LabelServiceClient.from_service_account_info.__func__(LabelServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + LabelServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(LabelServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -116,7 +118,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LabelServiceAsyncClient: The constructed client. """ - return LabelServiceClient.from_service_account_file.__func__(LabelServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + LabelServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(LabelServiceAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/label_service/client.py b/google/ads/googleads/v22/services/services/label_service/client.py index 52f34eda2..1099c6b15 100644 --- a/google/ads/googleads/v22/services/services/label_service/client.py +++ b/google/ads/googleads/v22/services/services/label_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import label_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import LabelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import LabelServiceGrpcTransport from .transports.grpc_asyncio import LabelServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -334,14 +362,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = LabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -349,7 +371,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -381,22 +403,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = LabelServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/label_service/transports/base.py b/google/ads/googleads/v22/services/services/label_service/transports/base.py index 3a4d774eb..6452fc558 100644 --- a/google/ads/googleads/v22/services/services/label_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/label_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/local_services_lead_service/async_client.py b/google/ads/googleads/v22/services/services/local_services_lead_service/async_client.py index d1d8b982d..85439a2d3 100644 --- a/google/ads/googleads/v22/services/services/local_services_lead_service/async_client.py +++ b/google/ads/googleads/v22/services/services/local_services_lead_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -116,7 +115,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: LocalServicesLeadServiceAsyncClient: The constructed client. """ - return LocalServicesLeadServiceClient.from_service_account_info.__func__(LocalServicesLeadServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + LocalServicesLeadServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + LocalServicesLeadServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -132,7 +136,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LocalServicesLeadServiceAsyncClient: The constructed client. """ - return LocalServicesLeadServiceClient.from_service_account_file.__func__(LocalServicesLeadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + LocalServicesLeadServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + LocalServicesLeadServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/local_services_lead_service/client.py b/google/ads/googleads/v22/services/services/local_services_lead_service/client.py index 494c36c96..1e9c8f4a0 100644 --- a/google/ads/googleads/v22/services/services/local_services_lead_service/client.py +++ b/google/ads/googleads/v22/services/services/local_services_lead_service/client.py @@ -154,6 +154,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -345,14 +373,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + LocalServicesLeadServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -360,7 +384,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -392,22 +416,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + LocalServicesLeadServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/local_services_lead_service/transports/base.py b/google/ads/googleads/v22/services/services/local_services_lead_service/transports/base.py index 863eecde7..78f436509 100644 --- a/google/ads/googleads/v22/services/services/local_services_lead_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/local_services_lead_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/offline_user_data_job_service/async_client.py b/google/ads/googleads/v22/services/services/offline_user_data_job_service/async_client.py index 168d7fa27..8583c11b7 100644 --- a/google/ads/googleads/v22/services/services/offline_user_data_job_service/async_client.py +++ b/google/ads/googleads/v22/services/services/offline_user_data_job_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -37,10 +36,10 @@ from google.ads.googleads.v22.services.types import ( offline_user_data_job_service, ) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( OfflineUserDataJobServiceTransport, DEFAULT_CLIENT_INFO, @@ -123,7 +122,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: OfflineUserDataJobServiceAsyncClient: The constructed client. """ - return OfflineUserDataJobServiceClient.from_service_account_info.__func__(OfflineUserDataJobServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + OfflineUserDataJobServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + OfflineUserDataJobServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -139,7 +143,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: OfflineUserDataJobServiceAsyncClient: The constructed client. """ - return OfflineUserDataJobServiceClient.from_service_account_file.__func__(OfflineUserDataJobServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + OfflineUserDataJobServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + OfflineUserDataJobServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/offline_user_data_job_service/client.py b/google/ads/googleads/v22/services/services/offline_user_data_job_service/client.py index c71983bd9..a9af364b2 100644 --- a/google/ads/googleads/v22/services/services/offline_user_data_job_service/client.py +++ b/google/ads/googleads/v22/services/services/offline_user_data_job_service/client.py @@ -63,10 +63,10 @@ from google.ads.googleads.v22.services.types import ( offline_user_data_job_service, ) -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( OfflineUserDataJobServiceTransport, DEFAULT_CLIENT_INFO, @@ -159,6 +159,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -350,14 +378,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + OfflineUserDataJobServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -365,7 +389,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -397,22 +421,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + OfflineUserDataJobServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/offline_user_data_job_service/transports/base.py b/google/ads/googleads/v22/services/services/offline_user_data_job_service/transports/base.py index de53d0dab..c2c361e0b 100644 --- a/google/ads/googleads/v22/services/services/offline_user_data_job_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/offline_user_data_job_service/transports/base.py @@ -85,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -102,12 +100,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/payments_account_service/async_client.py b/google/ads/googleads/v22/services/services/payments_account_service/async_client.py index ab6e2fd1c..45cb058f1 100644 --- a/google/ads/googleads/v22/services/services/payments_account_service/async_client.py +++ b/google/ads/googleads/v22/services/services/payments_account_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -120,7 +119,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: PaymentsAccountServiceAsyncClient: The constructed client. """ - return PaymentsAccountServiceClient.from_service_account_info.__func__(PaymentsAccountServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + PaymentsAccountServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + PaymentsAccountServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -136,7 +140,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: PaymentsAccountServiceAsyncClient: The constructed client. """ - return PaymentsAccountServiceClient.from_service_account_file.__func__(PaymentsAccountServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + PaymentsAccountServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + PaymentsAccountServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/payments_account_service/client.py b/google/ads/googleads/v22/services/services/payments_account_service/client.py index c3527c5a5..19d65288e 100644 --- a/google/ads/googleads/v22/services/services/payments_account_service/client.py +++ b/google/ads/googleads/v22/services/services/payments_account_service/client.py @@ -140,6 +140,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -346,14 +374,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + PaymentsAccountServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -361,7 +385,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -393,22 +417,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + PaymentsAccountServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/payments_account_service/transports/base.py b/google/ads/googleads/v22/services/services/payments_account_service/transports/base.py index 24c25bc17..615256cf5 100644 --- a/google/ads/googleads/v22/services/services/payments_account_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/payments_account_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/product_link_invitation_service/async_client.py b/google/ads/googleads/v22/services/services/product_link_invitation_service/async_client.py index a42d5b0af..042db3d72 100644 --- a/google/ads/googleads/v22/services/services/product_link_invitation_service/async_client.py +++ b/google/ads/googleads/v22/services/services/product_link_invitation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -132,7 +131,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ProductLinkInvitationServiceAsyncClient: The constructed client. """ - return ProductLinkInvitationServiceClient.from_service_account_info.__func__(ProductLinkInvitationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ProductLinkInvitationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ProductLinkInvitationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -148,7 +152,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductLinkInvitationServiceAsyncClient: The constructed client. """ - return ProductLinkInvitationServiceClient.from_service_account_file.__func__(ProductLinkInvitationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ProductLinkInvitationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ProductLinkInvitationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @@ -570,7 +579,7 @@ async def remove_product_link_invitation( Args: request (Optional[Union[google.ads.googleads.v22.services.types.RemoveProductLinkInvitationRequest, dict]]): The request object. Request message for - [ProductLinkinvitationService.RemoveProductLinkInvitation][]. + [ProductLinkInvitationService.RemoveProductLinkInvitation][google.ads.googleads.v22.services.ProductLinkInvitationService.RemoveProductLinkInvitation]. customer_id (:class:`str`): Required. The ID of the product link invitation being removed. @@ -582,7 +591,7 @@ async def remove_product_link_invitation( Required. The resource name of the product link invitation being removed. expected, in this format: - ```` + ``customers/{customer_id}/productLinkInvitations/{product_link_invitation_id}`` This corresponds to the ``resource_name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v22/services/services/product_link_invitation_service/client.py b/google/ads/googleads/v22/services/services/product_link_invitation_service/client.py index ac31cdee8..f50cc5433 100644 --- a/google/ads/googleads/v22/services/services/product_link_invitation_service/client.py +++ b/google/ads/googleads/v22/services/services/product_link_invitation_service/client.py @@ -152,6 +152,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -358,14 +386,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ProductLinkInvitationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -373,7 +397,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -405,22 +429,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ProductLinkInvitationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -1027,7 +1047,7 @@ def remove_product_link_invitation( Args: request (Union[google.ads.googleads.v22.services.types.RemoveProductLinkInvitationRequest, dict]): The request object. Request message for - [ProductLinkinvitationService.RemoveProductLinkInvitation][]. + [ProductLinkInvitationService.RemoveProductLinkInvitation][google.ads.googleads.v22.services.ProductLinkInvitationService.RemoveProductLinkInvitation]. customer_id (str): Required. The ID of the product link invitation being removed. @@ -1039,7 +1059,7 @@ def remove_product_link_invitation( Required. The resource name of the product link invitation being removed. expected, in this format: - ```` + ``customers/{customer_id}/productLinkInvitations/{product_link_invitation_id}`` This corresponds to the ``resource_name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/ads/googleads/v22/services/services/product_link_invitation_service/transports/base.py b/google/ads/googleads/v22/services/services/product_link_invitation_service/transports/base.py index 372162320..074f1ac42 100644 --- a/google/ads/googleads/v22/services/services/product_link_invitation_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/product_link_invitation_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/product_link_service/async_client.py b/google/ads/googleads/v22/services/services/product_link_service/async_client.py index cf799aaf5..f1cd70a0f 100644 --- a/google/ads/googleads/v22/services/services/product_link_service/async_client.py +++ b/google/ads/googleads/v22/services/services/product_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -118,7 +117,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ProductLinkServiceAsyncClient: The constructed client. """ - return ProductLinkServiceClient.from_service_account_info.__func__(ProductLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ProductLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ProductLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -134,7 +138,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductLinkServiceAsyncClient: The constructed client. """ - return ProductLinkServiceClient.from_service_account_file.__func__(ProductLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ProductLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ProductLinkServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/product_link_service/client.py b/google/ads/googleads/v22/services/services/product_link_service/client.py index b38b835ce..c61655f6b 100644 --- a/google/ads/googleads/v22/services/services/product_link_service/client.py +++ b/google/ads/googleads/v22/services/services/product_link_service/client.py @@ -138,6 +138,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = ProductLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +381,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +413,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ProductLinkServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/product_link_service/transports/base.py b/google/ads/googleads/v22/services/services/product_link_service/transports/base.py index 453618c33..ce28a27c8 100644 --- a/google/ads/googleads/v22/services/services/product_link_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/product_link_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/reach_plan_service/async_client.py b/google/ads/googleads/v22/services/services/reach_plan_service/async_client.py index fb2c9595f..4adf975a9 100644 --- a/google/ads/googleads/v22/services/services/reach_plan_service/async_client.py +++ b/google/ads/googleads/v22/services/services/reach_plan_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -109,7 +108,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ReachPlanServiceAsyncClient: The constructed client. """ - return ReachPlanServiceClient.from_service_account_info.__func__(ReachPlanServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ReachPlanServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(ReachPlanServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -125,7 +127,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ReachPlanServiceAsyncClient: The constructed client. """ - return ReachPlanServiceClient.from_service_account_file.__func__(ReachPlanServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ReachPlanServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ReachPlanServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/reach_plan_service/client.py b/google/ads/googleads/v22/services/services/reach_plan_service/client.py index 285b6b0dd..bc1ef2796 100644 --- a/google/ads/googleads/v22/services/services/reach_plan_service/client.py +++ b/google/ads/googleads/v22/services/services/reach_plan_service/client.py @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -320,14 +348,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = ReachPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -335,7 +357,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -367,22 +389,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ReachPlanServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/reach_plan_service/transports/base.py b/google/ads/googleads/v22/services/services/reach_plan_service/transports/base.py index 4e3950457..5ff1a9e7d 100644 --- a/google/ads/googleads/v22/services/services/reach_plan_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/reach_plan_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/recommendation_service/async_client.py b/google/ads/googleads/v22/services/services/recommendation_service/async_client.py index 5270325bb..4cfb0cc4d 100644 --- a/google/ads/googleads/v22/services/services/recommendation_service/async_client.py +++ b/google/ads/googleads/v22/services/services/recommendation_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -38,7 +37,7 @@ ) from google.ads.googleads.v22.enums.types import recommendation_type from google.ads.googleads.v22.services.types import recommendation_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO from .client import RecommendationServiceClient @@ -142,7 +141,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: RecommendationServiceAsyncClient: The constructed client. """ - return RecommendationServiceClient.from_service_account_info.__func__(RecommendationServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + RecommendationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + RecommendationServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -158,7 +162,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RecommendationServiceAsyncClient: The constructed client. """ - return RecommendationServiceClient.from_service_account_file.__func__(RecommendationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + RecommendationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + RecommendationServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/recommendation_service/client.py b/google/ads/googleads/v22/services/services/recommendation_service/client.py index 6ac01768d..deda65c06 100644 --- a/google/ads/googleads/v22/services/services/recommendation_service/client.py +++ b/google/ads/googleads/v22/services/services/recommendation_service/client.py @@ -64,7 +64,7 @@ ) from google.ads.googleads.v22.enums.types import recommendation_type from google.ads.googleads.v22.services.types import recommendation_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import RecommendationServiceGrpcTransport from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport @@ -150,6 +150,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -459,14 +487,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + RecommendationServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -474,7 +498,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -506,22 +530,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + RecommendationServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/recommendation_service/transports/base.py b/google/ads/googleads/v22/services/services/recommendation_service/transports/base.py index b313dee64..1a98f8ccd 100644 --- a/google/ads/googleads/v22/services/services/recommendation_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/recommendation_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/recommendation_subscription_service/async_client.py b/google/ads/googleads/v22/services/services/recommendation_subscription_service/async_client.py index 00cd35f03..e9aa13124 100644 --- a/google/ads/googleads/v22/services/services/recommendation_subscription_service/async_client.py +++ b/google/ads/googleads/v22/services/services/recommendation_subscription_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( recommendation_subscription_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RecommendationSubscriptionServiceTransport, DEFAULT_CLIENT_INFO, @@ -121,7 +120,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: RecommendationSubscriptionServiceAsyncClient: The constructed client. """ - return RecommendationSubscriptionServiceClient.from_service_account_info.__func__(RecommendationSubscriptionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + RecommendationSubscriptionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + RecommendationSubscriptionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -137,7 +141,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RecommendationSubscriptionServiceAsyncClient: The constructed client. """ - return RecommendationSubscriptionServiceClient.from_service_account_file.__func__(RecommendationSubscriptionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + RecommendationSubscriptionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + RecommendationSubscriptionServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file @@ -333,13 +345,14 @@ async def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Args: request (Optional[Union[google.ads.googleads.v22.services.types.MutateRecommendationSubscriptionRequest, dict]]): The request object. Request message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v22.services.RecommendationSubscriptionService.MutateRecommendationSubscription] customer_id (:class:`str`): Required. The ID of the subscribing customer. @@ -365,7 +378,7 @@ async def mutate_recommendation_subscription( Returns: google.ads.googleads.v22.services.types.MutateRecommendationSubscriptionResponse: Response message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v22.services.RecommendationSubscriptionService.MutateRecommendationSubscription] """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/recommendation_subscription_service/client.py b/google/ads/googleads/v22/services/services/recommendation_subscription_service/client.py index 3009ca24d..6b0891951 100644 --- a/google/ads/googleads/v22/services/services/recommendation_subscription_service/client.py +++ b/google/ads/googleads/v22/services/services/recommendation_subscription_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( recommendation_subscription_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RecommendationSubscriptionServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -346,14 +374,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + RecommendationSubscriptionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -361,7 +385,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -393,22 +417,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + RecommendationSubscriptionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): @@ -793,13 +813,14 @@ def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Args: request (Union[google.ads.googleads.v22.services.types.MutateRecommendationSubscriptionRequest, dict]): The request object. Request message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v22.services.RecommendationSubscriptionService.MutateRecommendationSubscription] customer_id (str): Required. The ID of the subscribing customer. @@ -825,7 +846,7 @@ def mutate_recommendation_subscription( Returns: google.ads.googleads.v22.services.types.MutateRecommendationSubscriptionResponse: Response message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v22.services.RecommendationSubscriptionService.MutateRecommendationSubscription] """ # Create or coerce a protobuf request object. diff --git a/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/base.py b/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/base.py index c3b98bcec..b45a0539e 100644 --- a/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/grpc.py b/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/grpc.py index 534b1e324..f217913f9 100644 --- a/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/grpc.py +++ b/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/grpc.py @@ -365,7 +365,8 @@ def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Returns: diff --git a/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/grpc_asyncio.py b/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/grpc_asyncio.py index 0620df92a..63938902d 100644 --- a/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/grpc_asyncio.py +++ b/google/ads/googleads/v22/services/services/recommendation_subscription_service/transports/grpc_asyncio.py @@ -373,7 +373,8 @@ def mutate_recommendation_subscription( List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `FieldError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ - `QuotaError <>`__ `RecommendationError <>`__ `RequestError <>`__ + `QuotaError <>`__ `RecommendationError <>`__ + `RecommendationSubscriptionError <>`__ `RequestError <>`__ `UrlFieldError <>`__ Returns: diff --git a/google/ads/googleads/v22/services/services/remarketing_action_service/async_client.py b/google/ads/googleads/v22/services/services/remarketing_action_service/async_client.py index 58f4cc74b..49cb6d0cd 100644 --- a/google/ads/googleads/v22/services/services/remarketing_action_service/async_client.py +++ b/google/ads/googleads/v22/services/services/remarketing_action_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import remarketing_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RemarketingActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -115,7 +114,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: RemarketingActionServiceAsyncClient: The constructed client. """ - return RemarketingActionServiceClient.from_service_account_info.__func__(RemarketingActionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + RemarketingActionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + RemarketingActionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -131,7 +135,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RemarketingActionServiceAsyncClient: The constructed client. """ - return RemarketingActionServiceClient.from_service_account_file.__func__(RemarketingActionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + RemarketingActionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + RemarketingActionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/remarketing_action_service/client.py b/google/ads/googleads/v22/services/services/remarketing_action_service/client.py index cbb636d7e..eb91065fa 100644 --- a/google/ads/googleads/v22/services/services/remarketing_action_service/client.py +++ b/google/ads/googleads/v22/services/services/remarketing_action_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import remarketing_action_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( RemarketingActionServiceTransport, DEFAULT_CLIENT_INFO, @@ -153,6 +153,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -344,14 +372,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + RemarketingActionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -359,7 +383,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -391,22 +415,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + RemarketingActionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/remarketing_action_service/transports/base.py b/google/ads/googleads/v22/services/services/remarketing_action_service/transports/base.py index dc30fa701..102699078 100644 --- a/google/ads/googleads/v22/services/services/remarketing_action_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/remarketing_action_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/shareable_preview_service/async_client.py b/google/ads/googleads/v22/services/services/shareable_preview_service/async_client.py index e15d66285..bddc3a0b5 100644 --- a/google/ads/googleads/v22/services/services/shareable_preview_service/async_client.py +++ b/google/ads/googleads/v22/services/services/shareable_preview_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -108,7 +107,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ShareablePreviewServiceAsyncClient: The constructed client. """ - return ShareablePreviewServiceClient.from_service_account_info.__func__(ShareablePreviewServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ShareablePreviewServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ShareablePreviewServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +128,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ShareablePreviewServiceAsyncClient: The constructed client. """ - return ShareablePreviewServiceClient.from_service_account_file.__func__(ShareablePreviewServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ShareablePreviewServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ShareablePreviewServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/shareable_preview_service/client.py b/google/ads/googleads/v22/services/services/shareable_preview_service/client.py index ca64eed88..128b63e23 100644 --- a/google/ads/googleads/v22/services/services/shareable_preview_service/client.py +++ b/google/ads/googleads/v22/services/services/shareable_preview_service/client.py @@ -150,6 +150,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -321,14 +349,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ShareablePreviewServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -336,7 +360,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -368,22 +392,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ShareablePreviewServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/shareable_preview_service/transports/base.py b/google/ads/googleads/v22/services/services/shareable_preview_service/transports/base.py index 403be4f86..52e6ff05d 100644 --- a/google/ads/googleads/v22/services/services/shareable_preview_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/shareable_preview_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/shared_criterion_service/async_client.py b/google/ads/googleads/v22/services/services/shared_criterion_service/async_client.py index 4d2807587..62c92c253 100644 --- a/google/ads/googleads/v22/services/services/shared_criterion_service/async_client.py +++ b/google/ads/googleads/v22/services/services/shared_criterion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import shared_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SharedCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SharedCriterionServiceAsyncClient: The constructed client. """ - return SharedCriterionServiceClient.from_service_account_info.__func__(SharedCriterionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SharedCriterionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SharedCriterionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SharedCriterionServiceAsyncClient: The constructed client. """ - return SharedCriterionServiceClient.from_service_account_file.__func__(SharedCriterionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SharedCriterionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SharedCriterionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/shared_criterion_service/client.py b/google/ads/googleads/v22/services/services/shared_criterion_service/client.py index c533ebf2b..a162f14cc 100644 --- a/google/ads/googleads/v22/services/services/shared_criterion_service/client.py +++ b/google/ads/googleads/v22/services/services/shared_criterion_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import shared_criterion_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SharedCriterionServiceTransport, DEFAULT_CLIENT_INFO, @@ -149,6 +149,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -380,14 +408,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + SharedCriterionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -395,7 +419,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -427,22 +451,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + SharedCriterionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/shared_criterion_service/transports/base.py b/google/ads/googleads/v22/services/services/shared_criterion_service/transports/base.py index 87fb50e1b..f02bd7a44 100644 --- a/google/ads/googleads/v22/services/services/shared_criterion_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/shared_criterion_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/shared_set_service/async_client.py b/google/ads/googleads/v22/services/services/shared_set_service/async_client.py index 3a623e052..d4b8d0318 100644 --- a/google/ads/googleads/v22/services/services/shared_set_service/async_client.py +++ b/google/ads/googleads/v22/services/services/shared_set_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import SharedSetServiceTransport, DEFAULT_CLIENT_INFO from .client import SharedSetServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SharedSetServiceAsyncClient: The constructed client. """ - return SharedSetServiceClient.from_service_account_info.__func__(SharedSetServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SharedSetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SharedSetServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SharedSetServiceAsyncClient: The constructed client. """ - return SharedSetServiceClient.from_service_account_file.__func__(SharedSetServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SharedSetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SharedSetServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/shared_set_service/client.py b/google/ads/googleads/v22/services/services/shared_set_service/client.py index 78aa4347c..248d7a89a 100644 --- a/google/ads/googleads/v22/services/services/shared_set_service/client.py +++ b/google/ads/googleads/v22/services/services/shared_set_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import shared_set_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import SharedSetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SharedSetServiceGrpcTransport from .transports.grpc_asyncio import SharedSetServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = SharedSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = SharedSetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/shared_set_service/transports/base.py b/google/ads/googleads/v22/services/services/shared_set_service/transports/base.py index 9cec4bbea..c5488ea5e 100644 --- a/google/ads/googleads/v22/services/services/shared_set_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/shared_set_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/smart_campaign_setting_service/async_client.py b/google/ads/googleads/v22/services/services/smart_campaign_setting_service/async_client.py index 86086582d..ba03f2859 100644 --- a/google/ads/googleads/v22/services/services/smart_campaign_setting_service/async_client.py +++ b/google/ads/googleads/v22/services/services/smart_campaign_setting_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( smart_campaign_setting_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SmartCampaignSettingServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SmartCampaignSettingServiceAsyncClient: The constructed client. """ - return SmartCampaignSettingServiceClient.from_service_account_info.__func__(SmartCampaignSettingServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SmartCampaignSettingServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SmartCampaignSettingServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SmartCampaignSettingServiceAsyncClient: The constructed client. """ - return SmartCampaignSettingServiceClient.from_service_account_file.__func__(SmartCampaignSettingServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SmartCampaignSettingServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SmartCampaignSettingServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/smart_campaign_setting_service/client.py b/google/ads/googleads/v22/services/services/smart_campaign_setting_service/client.py index 11f8f366e..3d9a04a2f 100644 --- a/google/ads/googleads/v22/services/services/smart_campaign_setting_service/client.py +++ b/google/ads/googleads/v22/services/services/smart_campaign_setting_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( smart_campaign_setting_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( SmartCampaignSettingServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -366,14 +394,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + SmartCampaignSettingServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -381,7 +405,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -413,22 +437,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + SmartCampaignSettingServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/smart_campaign_setting_service/transports/base.py b/google/ads/googleads/v22/services/services/smart_campaign_setting_service/transports/base.py index fb0fb3869..674ac9c91 100644 --- a/google/ads/googleads/v22/services/services/smart_campaign_setting_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/smart_campaign_setting_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/async_client.py b/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/async_client.py index 34f306809..321343a69 100644 --- a/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/async_client.py +++ b/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -124,7 +123,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: SmartCampaignSuggestServiceAsyncClient: The constructed client. """ - return SmartCampaignSuggestServiceClient.from_service_account_info.__func__(SmartCampaignSuggestServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + SmartCampaignSuggestServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SmartCampaignSuggestServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -140,7 +144,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: SmartCampaignSuggestServiceAsyncClient: The constructed client. """ - return SmartCampaignSuggestServiceClient.from_service_account_file.__func__(SmartCampaignSuggestServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + SmartCampaignSuggestServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SmartCampaignSuggestServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/client.py b/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/client.py index 5d79055fa..72af10471 100644 --- a/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/client.py +++ b/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -355,14 +383,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + SmartCampaignSuggestServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -370,7 +394,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -402,22 +426,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + SmartCampaignSuggestServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/transports/base.py b/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/transports/base.py index 8e78397bb..7535649d1 100644 --- a/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/smart_campaign_suggest_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/async_client.py b/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/async_client.py index f2a7fbf92..f2151b470 100644 --- a/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/async_client.py +++ b/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -122,7 +121,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: ThirdPartyAppAnalyticsLinkServiceAsyncClient: The constructed client. """ - return ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_info.__func__(ThirdPartyAppAnalyticsLinkServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + ThirdPartyAppAnalyticsLinkServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -138,7 +142,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ThirdPartyAppAnalyticsLinkServiceAsyncClient: The constructed client. """ - return ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_file.__func__(ThirdPartyAppAnalyticsLinkServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + ThirdPartyAppAnalyticsLinkServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + ThirdPartyAppAnalyticsLinkServiceAsyncClient, + filename, + *args, + **kwargs, + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/client.py b/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/client.py index 745ca9e34..5ced3586c 100644 --- a/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/client.py +++ b/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/client.py @@ -146,6 +146,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -337,14 +365,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + ThirdPartyAppAnalyticsLinkServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -352,7 +376,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -384,22 +408,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + ThirdPartyAppAnalyticsLinkServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/transports/base.py b/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/transports/base.py index 5c231416a..6084c090d 100644 --- a/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/third_party_app_analytics_link_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/async_client.py b/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/async_client.py index 92dff385e..8b72fe033 100644 --- a/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/async_client.py +++ b/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -112,7 +111,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: TravelAssetSuggestionServiceAsyncClient: The constructed client. """ - return TravelAssetSuggestionServiceClient.from_service_account_info.__func__(TravelAssetSuggestionServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + TravelAssetSuggestionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + TravelAssetSuggestionServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -128,7 +132,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: TravelAssetSuggestionServiceAsyncClient: The constructed client. """ - return TravelAssetSuggestionServiceClient.from_service_account_file.__func__(TravelAssetSuggestionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + TravelAssetSuggestionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + TravelAssetSuggestionServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/client.py b/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/client.py index c95a3df51..9ecbb389a 100644 --- a/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/client.py +++ b/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/client.py @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -315,14 +343,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + TravelAssetSuggestionServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -330,7 +354,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -362,22 +386,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + TravelAssetSuggestionServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/transports/base.py b/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/transports/base.py index a62b83ebd..baa249b41 100644 --- a/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/travel_asset_suggestion_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/user_data_service/async_client.py b/google/ads/googleads/v22/services/services/user_data_service/async_client.py index b54f44298..edd7c6753 100644 --- a/google/ads/googleads/v22/services/services/user_data_service/async_client.py +++ b/google/ads/googleads/v22/services/services/user_data_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -111,7 +110,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: UserDataServiceAsyncClient: The constructed client. """ - return UserDataServiceClient.from_service_account_info.__func__(UserDataServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + UserDataServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(UserDataServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -127,7 +129,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserDataServiceAsyncClient: The constructed client. """ - return UserDataServiceClient.from_service_account_file.__func__(UserDataServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + UserDataServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + UserDataServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/user_data_service/client.py b/google/ads/googleads/v22/services/services/user_data_service/client.py index 6c2cf7976..3805bfdec 100644 --- a/google/ads/googleads/v22/services/services/user_data_service/client.py +++ b/google/ads/googleads/v22/services/services/user_data_service/client.py @@ -141,6 +141,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -312,14 +340,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = UserDataServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -327,7 +349,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -359,22 +381,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = UserDataServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/user_data_service/transports/base.py b/google/ads/googleads/v22/services/services/user_data_service/transports/base.py index 377e4c180..a0c652b60 100644 --- a/google/ads/googleads/v22/services/services/user_data_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/user_data_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/user_list_customer_type_service/async_client.py b/google/ads/googleads/v22/services/services/user_list_customer_type_service/async_client.py index 791a96196..63f235718 100644 --- a/google/ads/googleads/v22/services/services/user_list_customer_type_service/async_client.py +++ b/google/ads/googleads/v22/services/services/user_list_customer_type_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -36,7 +35,7 @@ from google.ads.googleads.v22.services.types import ( user_list_customer_type_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( UserListCustomerTypeServiceTransport, DEFAULT_CLIENT_INFO, @@ -125,7 +124,12 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: UserListCustomerTypeServiceAsyncClient: The constructed client. """ - return UserListCustomerTypeServiceClient.from_service_account_info.__func__(UserListCustomerTypeServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + UserListCustomerTypeServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + UserListCustomerTypeServiceAsyncClient, info, *args, **kwargs + ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -141,7 +145,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserListCustomerTypeServiceAsyncClient: The constructed client. """ - return UserListCustomerTypeServiceClient.from_service_account_file.__func__(UserListCustomerTypeServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + UserListCustomerTypeServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + UserListCustomerTypeServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/user_list_customer_type_service/client.py b/google/ads/googleads/v22/services/services/user_list_customer_type_service/client.py index 296745977..5864dec27 100644 --- a/google/ads/googleads/v22/services/services/user_list_customer_type_service/client.py +++ b/google/ads/googleads/v22/services/services/user_list_customer_type_service/client.py @@ -62,7 +62,7 @@ from google.ads.googleads.v22.services.types import ( user_list_customer_type_service, ) -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import ( UserListCustomerTypeServiceTransport, DEFAULT_CLIENT_INFO, @@ -155,6 +155,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -368,14 +396,10 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + use_client_cert = ( + UserListCustomerTypeServiceClient._use_client_cert_effective() ) use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -383,7 +407,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -415,22 +439,18 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = ( + UserListCustomerTypeServiceClient._use_client_cert_effective() + ) use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/user_list_customer_type_service/transports/base.py b/google/ads/googleads/v22/services/services/user_list_customer_type_service/transports/base.py index dae7f073d..b2c67cab9 100644 --- a/google/ads/googleads/v22/services/services/user_list_customer_type_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/user_list_customer_type_service/transports/base.py @@ -84,8 +84,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -101,12 +99,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/services/user_list_service/async_client.py b/google/ads/googleads/v22/services/services/user_list_service/async_client.py index f852bb764..958eae31c 100644 --- a/google/ads/googleads/v22/services/services/user_list_service/async_client.py +++ b/google/ads/googleads/v22/services/services/user_list_service/async_client.py @@ -25,7 +25,6 @@ from google.oauth2 import service_account # type: ignore import google.protobuf - try: OptionalRetry = Union[ retries.AsyncRetry, gapic_v1.method._MethodDefault, None @@ -34,7 +33,7 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.ads.googleads.v22.services.types import user_list_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import UserListServiceTransport, DEFAULT_CLIENT_INFO from .client import UserListServiceClient @@ -108,7 +107,10 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: UserListServiceAsyncClient: The constructed client. """ - return UserListServiceClient.from_service_account_info.__func__(UserListServiceAsyncClient, info, *args, **kwargs) # type: ignore + sa_info_func = ( + UserListServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(UserListServiceAsyncClient, info, *args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): @@ -124,7 +126,12 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserListServiceAsyncClient: The constructed client. """ - return UserListServiceClient.from_service_account_file.__func__(UserListServiceAsyncClient, filename, *args, **kwargs) # type: ignore + sa_file_func = ( + UserListServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + UserListServiceAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file diff --git a/google/ads/googleads/v22/services/services/user_list_service/client.py b/google/ads/googleads/v22/services/services/user_list_service/client.py index 8f5b3c45a..03e4042c4 100644 --- a/google/ads/googleads/v22/services/services/user_list_service/client.py +++ b/google/ads/googleads/v22/services/services/user_list_service/client.py @@ -60,7 +60,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.ads.googleads.v22.services.types import user_list_service -from google.rpc import status_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from .transports.base import UserListServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import UserListServiceGrpcTransport from .transports.grpc_asyncio import UserListServiceGrpcAsyncIOTransport @@ -144,6 +144,34 @@ def _get_default_mtls_endpoint(api_endpoint): _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" _DEFAULT_UNIVERSE = "googleapis.com" + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -335,14 +363,8 @@ def get_mtls_endpoint_and_cert_source( ) if client_options is None: client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ) + use_client_cert = UserListServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" @@ -350,7 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out the client cert source to use. client_cert_source = None - if use_client_cert == "true": + if use_client_cert: if client_options.client_cert_source: client_cert_source = client_options.client_cert_source elif mtls.has_default_client_cert_source(): @@ -382,22 +404,16 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert = UserListServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" ) - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod def _get_client_cert_source(provided_cert_source, use_cert_flag): diff --git a/google/ads/googleads/v22/services/services/user_list_service/transports/base.py b/google/ads/googleads/v22/services/services/user_list_service/transports/base.py index 12a458337..ddf34b2fb 100644 --- a/google/ads/googleads/v22/services/services/user_list_service/transports/base.py +++ b/google/ads/googleads/v22/services/services/user_list_service/transports/base.py @@ -82,8 +82,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -99,12 +97,15 @@ def __init__( if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, - **scopes_kwargs, + scopes=scopes, quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) elif credentials is None and not self._ignore_credentials: credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): diff --git a/google/ads/googleads/v22/services/types/account_budget_proposal_service.py b/google/ads/googleads/v22/services/types/account_budget_proposal_service.py index a0443207f..48e1fc83e 100644 --- a/google/ads/googleads/v22/services/types/account_budget_proposal_service.py +++ b/google/ads/googleads/v22/services/types/account_budget_proposal_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import account_budget_proposal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/account_link_service.py b/google/ads/googleads/v22/services/types/account_link_service.py index 9317e8f2f..ff6817865 100644 --- a/google/ads/googleads/v22/services/types/account_link_service.py +++ b/google/ads/googleads/v22/services/types/account_link_service.py @@ -21,9 +21,8 @@ from google.ads.googleads.v22.resources.types import ( account_link as gagr_account_link, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_ad_label_service.py b/google/ads/googleads/v22/services/types/ad_group_ad_label_service.py index b8657c84a..65228a565 100644 --- a/google/ads/googleads/v22/services/types/ad_group_ad_label_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_ad_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import ad_group_ad_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_ad_service.py b/google/ads/googleads/v22/services/types/ad_group_ad_service.py index 520ffd607..ccef23933 100644 --- a/google/ads/googleads/v22/services/types/ad_group_ad_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_ad_service.py @@ -29,9 +29,8 @@ from google.ads.googleads.v22.resources.types import ( ad_group_ad as gagr_ad_group_ad, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", @@ -216,7 +215,7 @@ class MutateAdGroupAdResult(proto.Message): class RemoveAutomaticallyCreatedAssetsRequest(proto.Message): r"""Request message for - [AdGroupAdService.RemoveAutomaticallyCreatedAssetsRequest][]. + [AdGroupAdService.RemoveAutomaticallyCreatedAssets][google.ads.googleads.v22.services.AdGroupAdService.RemoveAutomaticallyCreatedAssets]. Attributes: ad_group_ad (str): diff --git a/google/ads/googleads/v22/services/types/ad_group_asset_service.py b/google/ads/googleads/v22/services/types/ad_group_asset_service.py index 0727ba063..fbcc79583 100644 --- a/google/ads/googleads/v22/services/types/ad_group_asset_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_asset_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( ad_group_asset as gagr_ad_group_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_asset_set_service.py b/google/ads/googleads/v22/services/types/ad_group_asset_set_service.py index 72ed03ee6..870b4b90f 100644 --- a/google/ads/googleads/v22/services/types/ad_group_asset_set_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_asset_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( ad_group_asset_set as gagr_ad_group_asset_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_bid_modifier_service.py b/google/ads/googleads/v22/services/types/ad_group_bid_modifier_service.py index 64958c650..110a41df5 100644 --- a/google/ads/googleads/v22/services/types/ad_group_bid_modifier_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_bid_modifier_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( ad_group_bid_modifier as gagr_ad_group_bid_modifier, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_criterion_customizer_service.py b/google/ads/googleads/v22/services/types/ad_group_criterion_customizer_service.py index 2ce2d0c78..9977a7bc9 100644 --- a/google/ads/googleads/v22/services/types/ad_group_criterion_customizer_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_criterion_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( ad_group_criterion_customizer as gagr_ad_group_criterion_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_criterion_label_service.py b/google/ads/googleads/v22/services/types/ad_group_criterion_label_service.py index 5b1abb085..2cc429f5d 100644 --- a/google/ads/googleads/v22/services/types/ad_group_criterion_label_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_criterion_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import ad_group_criterion_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_criterion_service.py b/google/ads/googleads/v22/services/types/ad_group_criterion_service.py index 54d455070..4e0790489 100644 --- a/google/ads/googleads/v22/services/types/ad_group_criterion_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_criterion_service.py @@ -26,9 +26,8 @@ from google.ads.googleads.v22.resources.types import ( ad_group_criterion as gagr_ad_group_criterion, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_customizer_service.py b/google/ads/googleads/v22/services/types/ad_group_customizer_service.py index 1affa46ef..533f10bd3 100644 --- a/google/ads/googleads/v22/services/types/ad_group_customizer_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( ad_group_customizer as gagr_ad_group_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_label_service.py b/google/ads/googleads/v22/services/types/ad_group_label_service.py index 57bd24ad4..3da2c6304 100644 --- a/google/ads/googleads/v22/services/types/ad_group_label_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import ad_group_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_group_service.py b/google/ads/googleads/v22/services/types/ad_group_service.py index 0b5c192b3..6f6cd2073 100644 --- a/google/ads/googleads/v22/services/types/ad_group_service.py +++ b/google/ads/googleads/v22/services/types/ad_group_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v22.resources.types import ad_group as gagr_ad_group -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_parameter_service.py b/google/ads/googleads/v22/services/types/ad_parameter_service.py index 352a346df..3b4078f86 100644 --- a/google/ads/googleads/v22/services/types/ad_parameter_service.py +++ b/google/ads/googleads/v22/services/types/ad_parameter_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( ad_parameter as gagr_ad_parameter, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/ad_service.py b/google/ads/googleads/v22/services/types/ad_service.py index 71faf9b87..4aee45612 100644 --- a/google/ads/googleads/v22/services/types/ad_service.py +++ b/google/ads/googleads/v22/services/types/ad_service.py @@ -24,9 +24,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v22.resources.types import ad as gagr_ad -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/asset_group_asset_service.py b/google/ads/googleads/v22/services/types/asset_group_asset_service.py index 9a7d17e6e..6cc65f99c 100644 --- a/google/ads/googleads/v22/services/types/asset_group_asset_service.py +++ b/google/ads/googleads/v22/services/types/asset_group_asset_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import asset_group_asset -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/asset_group_listing_group_filter_service.py b/google/ads/googleads/v22/services/types/asset_group_listing_group_filter_service.py index 25938f8e7..1fcdd6e84 100644 --- a/google/ads/googleads/v22/services/types/asset_group_listing_group_filter_service.py +++ b/google/ads/googleads/v22/services/types/asset_group_listing_group_filter_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( asset_group_listing_group_filter as gagr_asset_group_listing_group_filter, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/asset_group_service.py b/google/ads/googleads/v22/services/types/asset_group_service.py index 0cbe75606..6c7ee69cd 100644 --- a/google/ads/googleads/v22/services/types/asset_group_service.py +++ b/google/ads/googleads/v22/services/types/asset_group_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import asset_group -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/asset_group_signal_service.py b/google/ads/googleads/v22/services/types/asset_group_signal_service.py index 615cb8d85..ece35023b 100644 --- a/google/ads/googleads/v22/services/types/asset_group_signal_service.py +++ b/google/ads/googleads/v22/services/types/asset_group_signal_service.py @@ -26,8 +26,7 @@ from google.ads.googleads.v22.resources.types import ( asset_group_signal as gagr_asset_group_signal, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/asset_service.py b/google/ads/googleads/v22/services/types/asset_service.py index 0f67348a9..967673735 100644 --- a/google/ads/googleads/v22/services/types/asset_service.py +++ b/google/ads/googleads/v22/services/types/asset_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v22.resources.types import asset as gagr_asset -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/asset_set_asset_service.py b/google/ads/googleads/v22/services/types/asset_set_asset_service.py index 57b763bde..8d78f51b8 100644 --- a/google/ads/googleads/v22/services/types/asset_set_asset_service.py +++ b/google/ads/googleads/v22/services/types/asset_set_asset_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( asset_set_asset as gagr_asset_set_asset, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/asset_set_service.py b/google/ads/googleads/v22/services/types/asset_set_service.py index ef0d484dd..9792ae7f9 100644 --- a/google/ads/googleads/v22/services/types/asset_set_service.py +++ b/google/ads/googleads/v22/services/types/asset_set_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v22.resources.types import asset_set as gagr_asset_set -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/audience_insights_service.py b/google/ads/googleads/v22/services/types/audience_insights_service.py index ca365da09..73fca9843 100644 --- a/google/ads/googleads/v22/services/types/audience_insights_service.py +++ b/google/ads/googleads/v22/services/types/audience_insights_service.py @@ -28,7 +28,6 @@ audience_insights_marketing_objective, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.services", marshal="google.ads.googleads.v22", @@ -731,7 +730,7 @@ class GenerateTargetingSuggestionMetricsResponse(proto.Message): suggestions (MutableSequence[google.ads.googleads.v22.services.types.TargetingSuggestionMetrics]): Suggested targetable audiences. There will be one suggestion for each - [GenerateTargetingSuggestionMetricsRequest.audiences] + [GenerateTargetingSuggestionMetricsRequest.audiences][google.ads.googleads.v22.services.GenerateTargetingSuggestionMetricsRequest.audiences] requested, matching the order requested. """ diff --git a/google/ads/googleads/v22/services/types/audience_service.py b/google/ads/googleads/v22/services/types/audience_service.py index 41b290216..a9c3cca44 100644 --- a/google/ads/googleads/v22/services/types/audience_service.py +++ b/google/ads/googleads/v22/services/types/audience_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v22.resources.types import audience as gagr_audience -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/automatically_created_asset_removal_service.py b/google/ads/googleads/v22/services/types/automatically_created_asset_removal_service.py index 4087bad32..41de81468 100644 --- a/google/ads/googleads/v22/services/types/automatically_created_asset_removal_service.py +++ b/google/ads/googleads/v22/services/types/automatically_created_asset_removal_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.enums.types import asset_field_type -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/batch_job_service.py b/google/ads/googleads/v22/services/types/batch_job_service.py index bce9d174e..024668c9e 100644 --- a/google/ads/googleads/v22/services/types/batch_job_service.py +++ b/google/ads/googleads/v22/services/types/batch_job_service.py @@ -24,8 +24,7 @@ ) from google.ads.googleads.v22.resources.types import batch_job from google.ads.googleads.v22.services.types import google_ads_service -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/bidding_data_exclusion_service.py b/google/ads/googleads/v22/services/types/bidding_data_exclusion_service.py index 6d1d7b62d..9dc8399c0 100644 --- a/google/ads/googleads/v22/services/types/bidding_data_exclusion_service.py +++ b/google/ads/googleads/v22/services/types/bidding_data_exclusion_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( bidding_data_exclusion as gagr_bidding_data_exclusion, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/bidding_seasonality_adjustment_service.py b/google/ads/googleads/v22/services/types/bidding_seasonality_adjustment_service.py index 64e1f8fe0..7c01539c9 100644 --- a/google/ads/googleads/v22/services/types/bidding_seasonality_adjustment_service.py +++ b/google/ads/googleads/v22/services/types/bidding_seasonality_adjustment_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( bidding_seasonality_adjustment as gagr_bidding_seasonality_adjustment, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/bidding_strategy_service.py b/google/ads/googleads/v22/services/types/bidding_strategy_service.py index 4d9cdb3da..77d0519a6 100644 --- a/google/ads/googleads/v22/services/types/bidding_strategy_service.py +++ b/google/ads/googleads/v22/services/types/bidding_strategy_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( bidding_strategy as gagr_bidding_strategy, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_asset_service.py b/google/ads/googleads/v22/services/types/campaign_asset_service.py index 83b78928e..b2a39bf62 100644 --- a/google/ads/googleads/v22/services/types/campaign_asset_service.py +++ b/google/ads/googleads/v22/services/types/campaign_asset_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( campaign_asset as gagr_campaign_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_asset_set_service.py b/google/ads/googleads/v22/services/types/campaign_asset_set_service.py index fa40c9f27..b5454691e 100644 --- a/google/ads/googleads/v22/services/types/campaign_asset_set_service.py +++ b/google/ads/googleads/v22/services/types/campaign_asset_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( campaign_asset_set as gagr_campaign_asset_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_bid_modifier_service.py b/google/ads/googleads/v22/services/types/campaign_bid_modifier_service.py index 5940dc074..18aa2ceea 100644 --- a/google/ads/googleads/v22/services/types/campaign_bid_modifier_service.py +++ b/google/ads/googleads/v22/services/types/campaign_bid_modifier_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( campaign_bid_modifier as gagr_campaign_bid_modifier, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_budget_service.py b/google/ads/googleads/v22/services/types/campaign_budget_service.py index 0a06c2e86..45e4009d1 100644 --- a/google/ads/googleads/v22/services/types/campaign_budget_service.py +++ b/google/ads/googleads/v22/services/types/campaign_budget_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( campaign_budget as gagr_campaign_budget, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_conversion_goal_service.py b/google/ads/googleads/v22/services/types/campaign_conversion_goal_service.py index 806bf141b..8cbe7b30b 100644 --- a/google/ads/googleads/v22/services/types/campaign_conversion_goal_service.py +++ b/google/ads/googleads/v22/services/types/campaign_conversion_goal_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import campaign_conversion_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_criterion_service.py b/google/ads/googleads/v22/services/types/campaign_criterion_service.py index 78724096f..4377e958e 100644 --- a/google/ads/googleads/v22/services/types/campaign_criterion_service.py +++ b/google/ads/googleads/v22/services/types/campaign_criterion_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( campaign_criterion as gagr_campaign_criterion, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_customizer_service.py b/google/ads/googleads/v22/services/types/campaign_customizer_service.py index d9568bff1..7d7357f2e 100644 --- a/google/ads/googleads/v22/services/types/campaign_customizer_service.py +++ b/google/ads/googleads/v22/services/types/campaign_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( campaign_customizer as gagr_campaign_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_draft_service.py b/google/ads/googleads/v22/services/types/campaign_draft_service.py index 9bbe79798..b4c38358e 100644 --- a/google/ads/googleads/v22/services/types/campaign_draft_service.py +++ b/google/ads/googleads/v22/services/types/campaign_draft_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( campaign_draft as gagr_campaign_draft, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_goal_config_service.py b/google/ads/googleads/v22/services/types/campaign_goal_config_service.py index 6043f73a9..2d062d7d3 100644 --- a/google/ads/googleads/v22/services/types/campaign_goal_config_service.py +++ b/google/ads/googleads/v22/services/types/campaign_goal_config_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import campaign_goal_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_group_service.py b/google/ads/googleads/v22/services/types/campaign_group_service.py index 6fdacd739..6deda7745 100644 --- a/google/ads/googleads/v22/services/types/campaign_group_service.py +++ b/google/ads/googleads/v22/services/types/campaign_group_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( campaign_group as gagr_campaign_group, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_label_service.py b/google/ads/googleads/v22/services/types/campaign_label_service.py index 19348184a..ebdc9d51a 100644 --- a/google/ads/googleads/v22/services/types/campaign_label_service.py +++ b/google/ads/googleads/v22/services/types/campaign_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import campaign_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_lifecycle_goal_service.py b/google/ads/googleads/v22/services/types/campaign_lifecycle_goal_service.py index 86924ec63..5bfb4812e 100644 --- a/google/ads/googleads/v22/services/types/campaign_lifecycle_goal_service.py +++ b/google/ads/googleads/v22/services/types/campaign_lifecycle_goal_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import campaign_lifecycle_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", @@ -36,7 +35,7 @@ class ConfigureCampaignLifecycleGoalsRequest(proto.Message): r"""Request message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v22.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. Attributes: customer_id (str): @@ -115,7 +114,7 @@ class CampaignLifecycleGoalOperation(proto.Message): class ConfigureCampaignLifecycleGoalsResponse(proto.Message): r"""Response message for - [CampaignLifecycleGoalService.configureCampaignLifecycleGoals][]. + [CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals][google.ads.googleads.v22.services.CampaignLifecycleGoalService.ConfigureCampaignLifecycleGoals]. Attributes: result (google.ads.googleads.v22.services.types.ConfigureCampaignLifecycleGoalsResult): diff --git a/google/ads/googleads/v22/services/types/campaign_service.py b/google/ads/googleads/v22/services/types/campaign_service.py index 63072440c..5bfe5bf44 100644 --- a/google/ads/googleads/v22/services/types/campaign_service.py +++ b/google/ads/googleads/v22/services/types/campaign_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v22.resources.types import campaign as gagr_campaign -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/campaign_shared_set_service.py b/google/ads/googleads/v22/services/types/campaign_shared_set_service.py index b5cd06265..a0b300f2d 100644 --- a/google/ads/googleads/v22/services/types/campaign_shared_set_service.py +++ b/google/ads/googleads/v22/services/types/campaign_shared_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( campaign_shared_set as gagr_campaign_shared_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/content_creator_insights_service.py b/google/ads/googleads/v22/services/types/content_creator_insights_service.py index e82b24139..0aa463e94 100644 --- a/google/ads/googleads/v22/services/types/content_creator_insights_service.py +++ b/google/ads/googleads/v22/services/types/content_creator_insights_service.py @@ -24,7 +24,6 @@ from google.ads.googleads.v22.common.types import criteria from google.ads.googleads.v22.enums.types import insights_trend - __protobuf__ = proto.module( package="google.ads.googleads.v22.services", marshal="google.ads.googleads.v22", @@ -69,24 +68,28 @@ class GenerateCreatorInsightsRequest(proto.Message): to the criteria. sub_country_locations (MutableSequence[google.ads.googleads.v22.common.types.LocationInfo]): The sub-country geographic locations to search that apply to - the criteria. Only supported for [SearchAttributes] + the criteria. Only supported for + [SearchAttributes][google.ads.googleads.v22.services.GenerateCreatorInsightsRequest.SearchAttributes] criteria. search_attributes (google.ads.googleads.v22.services.types.GenerateCreatorInsightsRequest.SearchAttributes): The attributes used to identify top creators. Data fetched is based on the list of countries or sub-country locations - specified in [country_locations] or [sub_country_locations]. + specified in + [country_locations][google.ads.googleads.v22.services.GenerateCreatorInsightsRequest.country_locations] + or + [sub_country_locations][google.ads.googleads.v22.services.GenerateCreatorInsightsRequest.sub_country_locations]. This field is a member of `oneof`_ ``criteria``. search_brand (google.ads.googleads.v22.services.types.GenerateCreatorInsightsRequest.SearchBrand): A brand used to search for top creators. Data fetched is based on the list of countries specified in - [country_locations]. + [country_locations][google.ads.googleads.v22.services.GenerateCreatorInsightsRequest.country_locations]. This field is a member of `oneof`_ ``criteria``. search_channels (google.ads.googleads.v22.services.types.GenerateCreatorInsightsRequest.YouTubeChannels): YouTube Channel IDs for Creator Insights. Data fetched for channels is based on the list of countries specified in - [country_locations]. + [country_locations][google.ads.googleads.v22.services.GenerateCreatorInsightsRequest.country_locations]. This field is a member of `oneof`_ ``criteria``. """ @@ -109,7 +112,7 @@ class SearchAttributes(proto.Message): types of content. This is used to search for creators whose content matches the input creator attributes. Only Knowledge Graph Entities tagged with - [InsightsKnowledgeGraphEntityCapabilities.CREATOR_ATTRIBUTE][] + [CREATOR_ATTRIBUTE][google.ads.googleads.v22.enums.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities.CREATOR_ATTRIBUTE] are supported. Use [AudienceInsightsService.ListAudienceInsightsAttributes][google.ads.googleads.v22.services.AudienceInsightsService.ListAudienceInsightsAttributes] to get the list of supported entities. Other attributes @@ -141,9 +144,10 @@ class SearchBrand(proto.Message): find insights. include_related_topics (bool): Optional. When true, we will expand the search to beyond - just the entities specified in [brand_entities] to other - related knowledge graph entities similar to the brand. The - default value is ``false``. + just the entities specified in + [brand_entities][google.ads.googleads.v22.services.GenerateCreatorInsightsRequest.SearchBrand.brand_entities] + to other related knowledge graph entities similar to the + brand. The default value is ``false``. """ brand_entities: MutableSequence[ @@ -246,7 +250,7 @@ class GenerateCreatorInsightsResponse(proto.Message): class GenerateTrendingInsightsRequest(proto.Message): r"""Request message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v22.services.ContentCreatorInsightsService.GenerateTrendingInsights]. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -314,7 +318,7 @@ class GenerateTrendingInsightsRequest(proto.Message): class GenerateTrendingInsightsResponse(proto.Message): r"""Response message for - [ContentCreatorInsightsService.GenerateTrendingInsights] + [ContentCreatorInsightsService.GenerateTrendingInsights][google.ads.googleads.v22.services.ContentCreatorInsightsService.GenerateTrendingInsights]. Attributes: trend_insights (MutableSequence[google.ads.googleads.v22.services.types.TrendInsight]): @@ -618,7 +622,10 @@ class SearchTopics(proto.Message): entities (MutableSequence[google.ads.googleads.v22.common.types.AudienceInsightsEntity]): Required. A list of knowledge graph entities to retrieve trend information for. Supported entities are tagged with - [InsightsKnowledgeGraphEntityCapabilities.CONTENT_TRENDING_INSIGHTS][]. + [CONTENT_TRENDING_INSIGHTS][google.ads.googleads.v22.enums.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities.CONTENT_TRENDING_INSIGHTS]. + Use + [AudienceInsightsService.ListAudienceInsightsAttributes][google.ads.googleads.v22.services.AudienceInsightsService.ListAudienceInsightsAttributes] + to get the list of supported entities. """ entities: MutableSequence[ @@ -637,7 +644,9 @@ class TrendInsight(proto.Message): trend_attribute (google.ads.googleads.v22.common.types.AudienceInsightsAttributeMetadata): The attribute this trend is for. trend_metrics (google.ads.googleads.v22.services.types.TrendInsightMetrics): - Metrics associated with this trend. + Metrics associated with this trend. These + metrics are for the latest available month and + the comparison period is 3 months. trend (google.ads.googleads.v22.enums.types.InsightsTrendEnum.InsightsTrend): The direction of trend (such as RISING or DECLINING). diff --git a/google/ads/googleads/v22/services/types/conversion_action_service.py b/google/ads/googleads/v22/services/types/conversion_action_service.py index 98fcb003d..c83ae070d 100644 --- a/google/ads/googleads/v22/services/types/conversion_action_service.py +++ b/google/ads/googleads/v22/services/types/conversion_action_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( conversion_action as gagr_conversion_action, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/conversion_adjustment_upload_service.py b/google/ads/googleads/v22/services/types/conversion_adjustment_upload_service.py index 6bd0d243c..ee90a99dd 100644 --- a/google/ads/googleads/v22/services/types/conversion_adjustment_upload_service.py +++ b/google/ads/googleads/v22/services/types/conversion_adjustment_upload_service.py @@ -21,8 +21,7 @@ from google.ads.googleads.v22.common.types import offline_user_data from google.ads.googleads.v22.enums.types import conversion_adjustment_type -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/conversion_custom_variable_service.py b/google/ads/googleads/v22/services/types/conversion_custom_variable_service.py index f6ca3d76d..c81645750 100644 --- a/google/ads/googleads/v22/services/types/conversion_custom_variable_service.py +++ b/google/ads/googleads/v22/services/types/conversion_custom_variable_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( conversion_custom_variable as gagr_conversion_custom_variable, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/conversion_goal_campaign_config_service.py b/google/ads/googleads/v22/services/types/conversion_goal_campaign_config_service.py index cd2ef9f85..f44a78d5d 100644 --- a/google/ads/googleads/v22/services/types/conversion_goal_campaign_config_service.py +++ b/google/ads/googleads/v22/services/types/conversion_goal_campaign_config_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( conversion_goal_campaign_config as gagr_conversion_goal_campaign_config, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/conversion_upload_service.py b/google/ads/googleads/v22/services/types/conversion_upload_service.py index 65f650f4f..b2b20645c 100644 --- a/google/ads/googleads/v22/services/types/conversion_upload_service.py +++ b/google/ads/googleads/v22/services/types/conversion_upload_service.py @@ -23,8 +23,7 @@ from google.ads.googleads.v22.common.types import offline_user_data from google.ads.googleads.v22.enums.types import conversion_customer_type from google.ads.googleads.v22.enums.types import conversion_environment_enum -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", @@ -241,13 +240,11 @@ class ClickConversion(proto.Message): This field is a member of `oneof`_ ``_gclid``. gbraid (str): - The click identifier for clicks associated - with app conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + app conversions. wbraid (str): - The click identifier for clicks associated - with web conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + web conversions. conversion_action (str): Resource name of the conversion action associated with this conversion. Note: Although @@ -324,7 +321,10 @@ class ClickConversion(proto.Message): consent where required by law or any applicable Google policies. See the https://support.google.com/google-ads/answer/2998031 - page for more details. + page for more details. This field is only + available to allowlisted users. To include this + field in conversion imports, upgrade to the Data + Manager API. This field is a member of `oneof`_ ``_user_ip_address``. session_attributes_encoded (bytes): @@ -332,12 +332,17 @@ class ClickConversion(proto.Message): base64-encoded JSON string. The content should be generated by Google-provided library. To set session attributes individually, use session_attributes_key_value_pairs - instead. + instead. This field is only available to allowlisted users. + To include this field in conversion imports, upgrade to the + Data Manager API. This field is a member of `oneof`_ ``session_attributes``. session_attributes_key_value_pairs (google.ads.googleads.v22.services.types.SessionAttributesKeyValuePairs): The session attributes for the event, - represented as key-value pairs. + represented as key-value pairs. This field is + only available to allowlisted users. To include + this field in conversion imports, upgrade to the + Data Manager API. This field is a member of `oneof`_ ``session_attributes``. """ @@ -581,13 +586,11 @@ class ClickConversionResult(proto.Message): This field is a member of `oneof`_ ``_gclid``. gbraid (str): - The click identifier for clicks associated - with app conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + app conversions. wbraid (str): - The click identifier for clicks associated - with web conversions and originating from iOS - devices starting with iOS14. + The URL parameter for clicks associated with + web conversions. conversion_action (str): Resource name of the conversion action associated with this conversion. diff --git a/google/ads/googleads/v22/services/types/conversion_value_rule_service.py b/google/ads/googleads/v22/services/types/conversion_value_rule_service.py index 4b13e7ae8..5cd255863 100644 --- a/google/ads/googleads/v22/services/types/conversion_value_rule_service.py +++ b/google/ads/googleads/v22/services/types/conversion_value_rule_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( conversion_value_rule as gagr_conversion_value_rule, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/conversion_value_rule_set_service.py b/google/ads/googleads/v22/services/types/conversion_value_rule_set_service.py index c3556b882..6901135c3 100644 --- a/google/ads/googleads/v22/services/types/conversion_value_rule_set_service.py +++ b/google/ads/googleads/v22/services/types/conversion_value_rule_set_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( conversion_value_rule_set as gagr_conversion_value_rule_set, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/custom_audience_service.py b/google/ads/googleads/v22/services/types/custom_audience_service.py index c6c478f79..dae2224c8 100644 --- a/google/ads/googleads/v22/services/types/custom_audience_service.py +++ b/google/ads/googleads/v22/services/types/custom_audience_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import custom_audience -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/custom_conversion_goal_service.py b/google/ads/googleads/v22/services/types/custom_conversion_goal_service.py index e5b741659..ddf3a7ac5 100644 --- a/google/ads/googleads/v22/services/types/custom_conversion_goal_service.py +++ b/google/ads/googleads/v22/services/types/custom_conversion_goal_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( custom_conversion_goal as gagr_custom_conversion_goal, ) -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/custom_interest_service.py b/google/ads/googleads/v22/services/types/custom_interest_service.py index b042cf9e2..9b6fbf8f1 100644 --- a/google/ads/googleads/v22/services/types/custom_interest_service.py +++ b/google/ads/googleads/v22/services/types/custom_interest_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import custom_interest -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_asset_service.py b/google/ads/googleads/v22/services/types/customer_asset_service.py index 6e5ee75d8..91682e696 100644 --- a/google/ads/googleads/v22/services/types/customer_asset_service.py +++ b/google/ads/googleads/v22/services/types/customer_asset_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( customer_asset as gagr_customer_asset, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_asset_set_service.py b/google/ads/googleads/v22/services/types/customer_asset_set_service.py index 374fe486f..bb6da397d 100644 --- a/google/ads/googleads/v22/services/types/customer_asset_set_service.py +++ b/google/ads/googleads/v22/services/types/customer_asset_set_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( customer_asset_set as gagr_customer_asset_set, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_client_link_service.py b/google/ads/googleads/v22/services/types/customer_client_link_service.py index 33d91ffc4..948853f88 100644 --- a/google/ads/googleads/v22/services/types/customer_client_link_service.py +++ b/google/ads/googleads/v22/services/types/customer_client_link_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import customer_client_link -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_conversion_goal_service.py b/google/ads/googleads/v22/services/types/customer_conversion_goal_service.py index 950e182e1..f575b052a 100644 --- a/google/ads/googleads/v22/services/types/customer_conversion_goal_service.py +++ b/google/ads/googleads/v22/services/types/customer_conversion_goal_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import customer_conversion_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_customizer_service.py b/google/ads/googleads/v22/services/types/customer_customizer_service.py index cfbe5c1f7..a34e1d6ff 100644 --- a/google/ads/googleads/v22/services/types/customer_customizer_service.py +++ b/google/ads/googleads/v22/services/types/customer_customizer_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( customer_customizer as gagr_customer_customizer, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_label_service.py b/google/ads/googleads/v22/services/types/customer_label_service.py index 5f4f04ccd..b66cb8bf5 100644 --- a/google/ads/googleads/v22/services/types/customer_label_service.py +++ b/google/ads/googleads/v22/services/types/customer_label_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import customer_label -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_lifecycle_goal_service.py b/google/ads/googleads/v22/services/types/customer_lifecycle_goal_service.py index b1cab3005..885023818 100644 --- a/google/ads/googleads/v22/services/types/customer_lifecycle_goal_service.py +++ b/google/ads/googleads/v22/services/types/customer_lifecycle_goal_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import customer_lifecycle_goal -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", @@ -36,7 +35,7 @@ class ConfigureCustomerLifecycleGoalsRequest(proto.Message): r"""Request message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v22.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. Attributes: customer_id (str): @@ -113,7 +112,7 @@ class CustomerLifecycleGoalOperation(proto.Message): class ConfigureCustomerLifecycleGoalsResponse(proto.Message): r"""Response message for - [CustomerLifecycleGoalService.configureCustomerLifecycleGoals][]. + [CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals][google.ads.googleads.v22.services.CustomerLifecycleGoalService.ConfigureCustomerLifecycleGoals]. Attributes: result (google.ads.googleads.v22.services.types.ConfigureCustomerLifecycleGoalsResult): diff --git a/google/ads/googleads/v22/services/types/customer_manager_link_service.py b/google/ads/googleads/v22/services/types/customer_manager_link_service.py index 5d8907cca..7c83ade01 100644 --- a/google/ads/googleads/v22/services/types/customer_manager_link_service.py +++ b/google/ads/googleads/v22/services/types/customer_manager_link_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import customer_manager_link -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_negative_criterion_service.py b/google/ads/googleads/v22/services/types/customer_negative_criterion_service.py index b4829f52b..c3ae79c98 100644 --- a/google/ads/googleads/v22/services/types/customer_negative_criterion_service.py +++ b/google/ads/googleads/v22/services/types/customer_negative_criterion_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( customer_negative_criterion as gagr_customer_negative_criterion, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_service.py b/google/ads/googleads/v22/services/types/customer_service.py index bf56497c7..adc811866 100644 --- a/google/ads/googleads/v22/services/types/customer_service.py +++ b/google/ads/googleads/v22/services/types/customer_service.py @@ -24,8 +24,7 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v22.resources.types import customer as gagr_customer -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_sk_ad_network_conversion_value_schema_service.py b/google/ads/googleads/v22/services/types/customer_sk_ad_network_conversion_value_schema_service.py index ca2b1c039..7bf840e23 100644 --- a/google/ads/googleads/v22/services/types/customer_sk_ad_network_conversion_value_schema_service.py +++ b/google/ads/googleads/v22/services/types/customer_sk_ad_network_conversion_value_schema_service.py @@ -21,8 +21,7 @@ from google.ads.googleads.v22.resources.types import ( customer_sk_ad_network_conversion_value_schema, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customer_user_access_service.py b/google/ads/googleads/v22/services/types/customer_user_access_service.py index 50958ca4a..7b1bb47d4 100644 --- a/google/ads/googleads/v22/services/types/customer_user_access_service.py +++ b/google/ads/googleads/v22/services/types/customer_user_access_service.py @@ -19,8 +19,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import customer_user_access -from google.protobuf import field_mask_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/customizer_attribute_service.py b/google/ads/googleads/v22/services/types/customizer_attribute_service.py index 4983b19aa..29dc653a8 100644 --- a/google/ads/googleads/v22/services/types/customizer_attribute_service.py +++ b/google/ads/googleads/v22/services/types/customizer_attribute_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( customizer_attribute as gagr_customizer_attribute, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/experiment_arm_service.py b/google/ads/googleads/v22/services/types/experiment_arm_service.py index 6e92ec9f4..861ba6258 100644 --- a/google/ads/googleads/v22/services/types/experiment_arm_service.py +++ b/google/ads/googleads/v22/services/types/experiment_arm_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( experiment_arm as gagr_experiment_arm, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/experiment_service.py b/google/ads/googleads/v22/services/types/experiment_service.py index 77f486a19..65ae6a9f7 100644 --- a/google/ads/googleads/v22/services/types/experiment_service.py +++ b/google/ads/googleads/v22/services/types/experiment_service.py @@ -22,9 +22,8 @@ from google.ads.googleads.v22.resources.types import ( experiment as gagr_experiment, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/goal_service.py b/google/ads/googleads/v22/services/types/goal_service.py index 2cf55485a..eb5ac13a0 100644 --- a/google/ads/googleads/v22/services/types/goal_service.py +++ b/google/ads/googleads/v22/services/types/goal_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import goal -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/google_ads_service.py b/google/ads/googleads/v22/services/types/google_ads_service.py index c0934438a..841b1abe5 100644 --- a/google/ads/googleads/v22/services/types/google_ads_service.py +++ b/google/ads/googleads/v22/services/types/google_ads_service.py @@ -631,9 +631,8 @@ smart_campaign_setting_service, ) from google.ads.googleads.v22.services.types import user_list_service -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/identity_verification_service.py b/google/ads/googleads/v22/services/types/identity_verification_service.py index ce07d2a7a..6a1a9fec1 100644 --- a/google/ads/googleads/v22/services/types/identity_verification_service.py +++ b/google/ads/googleads/v22/services/types/identity_verification_service.py @@ -24,7 +24,6 @@ identity_verification_program_status, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.services", marshal="google.ads.googleads.v22", @@ -41,7 +40,7 @@ class StartIdentityVerificationRequest(proto.Message): r"""Request message for - [IdentityVerificationService.StartIdentityVerification]. + [StartIdentityVerification][google.ads.googleads.v22.services.IdentityVerificationService.StartIdentityVerification]. Attributes: customer_id (str): @@ -67,7 +66,7 @@ class StartIdentityVerificationRequest(proto.Message): class GetIdentityVerificationRequest(proto.Message): r"""Request message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v22.services.IdentityVerificationService.GetIdentityVerification]. Attributes: customer_id (str): @@ -83,7 +82,7 @@ class GetIdentityVerificationRequest(proto.Message): class GetIdentityVerificationResponse(proto.Message): r"""Response message for - [IdentityVerificationService.GetIdentityVerification]. + [GetIdentityVerification][google.ads.googleads.v22.services.IdentityVerificationService.GetIdentityVerification]. Attributes: identity_verification (MutableSequence[google.ads.googleads.v22.services.types.IdentityVerification]): diff --git a/google/ads/googleads/v22/services/types/keyword_plan_ad_group_keyword_service.py b/google/ads/googleads/v22/services/types/keyword_plan_ad_group_keyword_service.py index f3bf37dee..b6cc95f16 100644 --- a/google/ads/googleads/v22/services/types/keyword_plan_ad_group_keyword_service.py +++ b/google/ads/googleads/v22/services/types/keyword_plan_ad_group_keyword_service.py @@ -22,9 +22,8 @@ from google.ads.googleads.v22.resources.types import ( keyword_plan_ad_group_keyword, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/keyword_plan_ad_group_service.py b/google/ads/googleads/v22/services/types/keyword_plan_ad_group_service.py index a4c7a6fd7..c03d9267f 100644 --- a/google/ads/googleads/v22/services/types/keyword_plan_ad_group_service.py +++ b/google/ads/googleads/v22/services/types/keyword_plan_ad_group_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import keyword_plan_ad_group -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/keyword_plan_campaign_keyword_service.py b/google/ads/googleads/v22/services/types/keyword_plan_campaign_keyword_service.py index 24493d539..c9621148f 100644 --- a/google/ads/googleads/v22/services/types/keyword_plan_campaign_keyword_service.py +++ b/google/ads/googleads/v22/services/types/keyword_plan_campaign_keyword_service.py @@ -22,9 +22,8 @@ from google.ads.googleads.v22.resources.types import ( keyword_plan_campaign_keyword, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/keyword_plan_campaign_service.py b/google/ads/googleads/v22/services/types/keyword_plan_campaign_service.py index 1afd64950..9e1565d1d 100644 --- a/google/ads/googleads/v22/services/types/keyword_plan_campaign_service.py +++ b/google/ads/googleads/v22/services/types/keyword_plan_campaign_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import keyword_plan_campaign -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/keyword_plan_idea_service.py b/google/ads/googleads/v22/services/types/keyword_plan_idea_service.py index 54798719f..66ccb244f 100644 --- a/google/ads/googleads/v22/services/types/keyword_plan_idea_service.py +++ b/google/ads/googleads/v22/services/types/keyword_plan_idea_service.py @@ -28,7 +28,6 @@ keyword_plan_network as gage_keyword_plan_network, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.services", marshal="google.ads.googleads.v22", @@ -688,7 +687,7 @@ class UnusableAdGroup(proto.Message): class GenerateKeywordForecastMetricsRequest(proto.Message): r"""Request message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v22.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -1049,7 +1048,7 @@ class MaximizeConversionsBiddingStrategy(proto.Message): class GenerateKeywordForecastMetricsResponse(proto.Message): r"""Response message for - [KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. + [KeywordPlanIdeaService.GenerateKeywordForecastMetrics][google.ads.googleads.v22.services.KeywordPlanIdeaService.GenerateKeywordForecastMetrics]. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v22/services/types/keyword_plan_service.py b/google/ads/googleads/v22/services/types/keyword_plan_service.py index f79249683..2f5016e71 100644 --- a/google/ads/googleads/v22/services/types/keyword_plan_service.py +++ b/google/ads/googleads/v22/services/types/keyword_plan_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import keyword_plan -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/label_service.py b/google/ads/googleads/v22/services/types/label_service.py index 4342e3a8c..44a2bb1ee 100644 --- a/google/ads/googleads/v22/services/types/label_service.py +++ b/google/ads/googleads/v22/services/types/label_service.py @@ -23,9 +23,8 @@ response_content_type as gage_response_content_type, ) from google.ads.googleads.v22.resources.types import label as gagr_label -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/local_services_lead_service.py b/google/ads/googleads/v22/services/types/local_services_lead_service.py index aac8bcbd6..1ee451294 100644 --- a/google/ads/googleads/v22/services/types/local_services_lead_service.py +++ b/google/ads/googleads/v22/services/types/local_services_lead_service.py @@ -31,8 +31,7 @@ from google.ads.googleads.v22.enums.types import ( local_services_lead_survey_satisfied_reason, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/offline_user_data_job_service.py b/google/ads/googleads/v22/services/types/offline_user_data_job_service.py index 50f7a26de..48d097257 100644 --- a/google/ads/googleads/v22/services/types/offline_user_data_job_service.py +++ b/google/ads/googleads/v22/services/types/offline_user_data_job_service.py @@ -21,8 +21,7 @@ from google.ads.googleads.v22.common.types import offline_user_data from google.ads.googleads.v22.resources.types import offline_user_data_job -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/product_link_invitation_service.py b/google/ads/googleads/v22/services/types/product_link_invitation_service.py index 274ec50d3..2df7bb76d 100644 --- a/google/ads/googleads/v22/services/types/product_link_invitation_service.py +++ b/google/ads/googleads/v22/services/types/product_link_invitation_service.py @@ -25,7 +25,6 @@ product_link_invitation as gagr_product_link_invitation, ) - __protobuf__ = proto.module( package="google.ads.googleads.v22.services", marshal="google.ads.googleads.v22", @@ -129,7 +128,7 @@ class UpdateProductLinkInvitationResponse(proto.Message): class RemoveProductLinkInvitationRequest(proto.Message): r"""Request message for - [ProductLinkinvitationService.RemoveProductLinkInvitation][]. + [ProductLinkInvitationService.RemoveProductLinkInvitation][google.ads.googleads.v22.services.ProductLinkInvitationService.RemoveProductLinkInvitation]. Attributes: customer_id (str): @@ -139,7 +138,7 @@ class RemoveProductLinkInvitationRequest(proto.Message): Required. The resource name of the product link invitation being removed. expected, in this format: - ```` + ``customers/{customer_id}/productLinkInvitations/{product_link_invitation_id}`` """ customer_id: str = proto.Field( diff --git a/google/ads/googleads/v22/services/types/recommendation_service.py b/google/ads/googleads/v22/services/types/recommendation_service.py index 63bf7c37b..98399c65c 100644 --- a/google/ads/googleads/v22/services/types/recommendation_service.py +++ b/google/ads/googleads/v22/services/types/recommendation_service.py @@ -39,8 +39,7 @@ from google.ads.googleads.v22.resources.types import ad as gagr_ad from google.ads.googleads.v22.resources.types import asset from google.ads.googleads.v22.resources.types import recommendation -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/recommendation_subscription_service.py b/google/ads/googleads/v22/services/types/recommendation_subscription_service.py index c99dad1d2..d79e2a416 100644 --- a/google/ads/googleads/v22/services/types/recommendation_subscription_service.py +++ b/google/ads/googleads/v22/services/types/recommendation_subscription_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( recommendation_subscription as gagr_recommendation_subscription, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", @@ -43,7 +42,7 @@ class MutateRecommendationSubscriptionRequest(proto.Message): r"""Request message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v22.services.RecommendationSubscriptionService.MutateRecommendationSubscription] Attributes: customer_id (str): @@ -100,7 +99,7 @@ class MutateRecommendationSubscriptionRequest(proto.Message): class RecommendationSubscriptionOperation(proto.Message): r"""A single operation (create, update) on a recommendation subscription. - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v22.services.RecommendationSubscriptionService.MutateRecommendationSubscription] This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -150,7 +149,7 @@ class RecommendationSubscriptionOperation(proto.Message): class MutateRecommendationSubscriptionResponse(proto.Message): r"""Response message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v22.services.RecommendationSubscriptionService.MutateRecommendationSubscription] Attributes: results (MutableSequence[google.ads.googleads.v22.services.types.MutateRecommendationSubscriptionResult]): @@ -179,7 +178,7 @@ class MutateRecommendationSubscriptionResponse(proto.Message): class MutateRecommendationSubscriptionResult(proto.Message): r"""Result message for - [RecommendationSubscriptionService.MutateRecommendationSubscription] + [RecommendationSubscriptionService.MutateRecommendationSubscription][google.ads.googleads.v22.services.RecommendationSubscriptionService.MutateRecommendationSubscription] Attributes: resource_name (str): diff --git a/google/ads/googleads/v22/services/types/remarketing_action_service.py b/google/ads/googleads/v22/services/types/remarketing_action_service.py index a5bcd163c..3778666ac 100644 --- a/google/ads/googleads/v22/services/types/remarketing_action_service.py +++ b/google/ads/googleads/v22/services/types/remarketing_action_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import remarketing_action -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/shareable_preview_service.py b/google/ads/googleads/v22/services/types/shareable_preview_service.py index 07ae810d3..d86bf3849 100644 --- a/google/ads/googleads/v22/services/types/shareable_preview_service.py +++ b/google/ads/googleads/v22/services/types/shareable_preview_service.py @@ -19,8 +19,7 @@ import proto # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/shared_criterion_service.py b/google/ads/googleads/v22/services/types/shared_criterion_service.py index ec4532d4c..d9e1d9597 100644 --- a/google/ads/googleads/v22/services/types/shared_criterion_service.py +++ b/google/ads/googleads/v22/services/types/shared_criterion_service.py @@ -25,8 +25,7 @@ from google.ads.googleads.v22.resources.types import ( shared_criterion as gagr_shared_criterion, ) -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/shared_set_service.py b/google/ads/googleads/v22/services/types/shared_set_service.py index b54c82ab5..516836f5f 100644 --- a/google/ads/googleads/v22/services/types/shared_set_service.py +++ b/google/ads/googleads/v22/services/types/shared_set_service.py @@ -25,9 +25,8 @@ from google.ads.googleads.v22.resources.types import ( shared_set as gagr_shared_set, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/smart_campaign_setting_service.py b/google/ads/googleads/v22/services/types/smart_campaign_setting_service.py index d44a05f0b..540d8d40d 100644 --- a/google/ads/googleads/v22/services/types/smart_campaign_setting_service.py +++ b/google/ads/googleads/v22/services/types/smart_campaign_setting_service.py @@ -31,9 +31,8 @@ from google.ads.googleads.v22.resources.types import ( smart_campaign_setting as gagr_smart_campaign_setting, ) -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/user_list_customer_type_service.py b/google/ads/googleads/v22/services/types/user_list_customer_type_service.py index 53dd40a62..8573d11bb 100644 --- a/google/ads/googleads/v22/services/types/user_list_customer_type_service.py +++ b/google/ads/googleads/v22/services/types/user_list_customer_type_service.py @@ -20,8 +20,7 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import user_list_customer_type -from google.rpc import status_pb2 # type: ignore - +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v22/services/types/user_list_service.py b/google/ads/googleads/v22/services/types/user_list_service.py index 1cd7014d7..4ecf55683 100644 --- a/google/ads/googleads/v22/services/types/user_list_service.py +++ b/google/ads/googleads/v22/services/types/user_list_service.py @@ -20,9 +20,8 @@ import proto # type: ignore from google.ads.googleads.v22.resources.types import user_list -from google.protobuf import field_mask_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v22.services", diff --git a/google/ads/googleads/v23/common/types/additional_application_info.py b/google/ads/googleads/v23/common/types/additional_application_info.py index ce291737a..c4ebde340 100644 --- a/google/ads/googleads/v23/common/types/additional_application_info.py +++ b/google/ads/googleads/v23/common/types/additional_application_info.py @@ -34,8 +34,12 @@ class AdditionalApplicationInfo(proto.Message): r"""Additional information about the application/tool issuing the - request. This field is only used by [ContentCreatorInsightsService], - [AudienceInsightsService], and [ReachPlanService] APIs. + request. This field is only used by + [ContentCreatorInsightsService][google.ads.googleads.v23.services.ContentCreatorInsightsService], + [AudienceInsightsService][google.ads.googleads.v23.services.AudienceInsightsService], + and + [ReachPlanService][google.ads.googleads.v23.services.ReachPlanService] + APIs. Attributes: application_id (str): diff --git a/google/ads/googleads/v23/common/types/audience_insights_attribute.py b/google/ads/googleads/v23/common/types/audience_insights_attribute.py index b1dda4f80..b1a29d6d0 100644 --- a/google/ads/googleads/v23/common/types/audience_insights_attribute.py +++ b/google/ads/googleads/v23/common/types/audience_insights_attribute.py @@ -593,7 +593,7 @@ class KnowledgeGraphAttributeMetadata(proto.Message): Attributes: entity_capabilities (MutableSequence[google.ads.googleads.v23.enums.types.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities]): The capabilities of the entity used in - [ContentCreatorInsightsService][]. + [ContentCreatorInsightsService][google.ads.googleads.v23.services.ContentCreatorInsightsService]. related_categories (MutableSequence[google.ads.googleads.v23.common.types.AudienceInsightsAttributeMetadata]): A list of CATEGORY attributes related to this entity. diff --git a/google/ads/googleads/v23/common/types/metrics.py b/google/ads/googleads/v23/common/types/metrics.py index d2573671c..bfd700e83 100644 --- a/google/ads/googleads/v23/common/types/metrics.py +++ b/google/ads/googleads/v23/common/types/metrics.py @@ -1705,6 +1705,46 @@ class Metrics(proto.Message): customer. This field is a member of `oneof`_ ``_cost_converted_currency_per_platform_comparable_conversion``. + unique_users_two_plus (int): + This metric counts the unique individuals who + were shown your video ad two or more times + within the selected date range. This metric + cannot be aggregated, and can only be requested + for date ranges of 31 days or less. + + This field is a member of `oneof`_ ``_unique_users_two_plus``. + unique_users_three_plus (int): + This metric counts the unique individuals who + were shown your video ad three or more times + within the selected date range. This metric + cannot be aggregated, and can only be requested + for date ranges of 31 days or less. + + This field is a member of `oneof`_ ``_unique_users_three_plus``. + unique_users_four_plus (int): + This metric counts the unique individuals who + were shown your video ad four or more times + within the selected date range. This metric + cannot be aggregated, and can only be requested + for date ranges of 31 days or less. + + This field is a member of `oneof`_ ``_unique_users_four_plus``. + unique_users_five_plus (int): + This metric counts the unique individuals who + were shown your video ad five or more times + within the selected date range. This metric + cannot be aggregated, and can only be requested + for date ranges of 31 days or less. + + This field is a member of `oneof`_ ``_unique_users_five_plus``. + unique_users_ten_plus (int): + This metric counts the unique individuals who + were shown your video ad ten or more times + within the selected date range. This metric + cannot be aggregated, and can only be requested + for date ranges of 31 days or less. + + This field is a member of `oneof`_ ``_unique_users_ten_plus``. value_adjustment (float): The conversion value rule adjustment from biddable conversions in all conversion @@ -2904,6 +2944,31 @@ class Metrics(proto.Message): optional=True, ) ) + unique_users_two_plus: int = proto.Field( + proto.INT64, + number=393, + optional=True, + ) + unique_users_three_plus: int = proto.Field( + proto.INT64, + number=394, + optional=True, + ) + unique_users_four_plus: int = proto.Field( + proto.INT64, + number=395, + optional=True, + ) + unique_users_five_plus: int = proto.Field( + proto.INT64, + number=396, + optional=True, + ) + unique_users_ten_plus: int = proto.Field( + proto.INT64, + number=397, + optional=True, + ) value_adjustment: float = proto.Field( proto.DOUBLE, number=398, diff --git a/google/ads/googleads/v23/enums/__init__.py b/google/ads/googleads/v23/enums/__init__.py index cfcd96e80..f9b7cb39d 100644 --- a/google/ads/googleads/v23/enums/__init__.py +++ b/google/ads/googleads/v23/enums/__init__.py @@ -125,6 +125,7 @@ BenchmarksMarketingObjectiveEnum, ) from .types.benchmarks_source_type import BenchmarksSourceTypeEnum +from .types.benchmarks_time_granularity import BenchmarksTimeGranularityEnum from .types.bid_modifier_source import BidModifierSourceEnum from .types.bidding_source import BiddingSourceEnum from .types.bidding_strategy_status import BiddingStrategyStatusEnum @@ -133,6 +134,7 @@ ) from .types.bidding_strategy_type import BiddingStrategyTypeEnum from .types.billing_setup_status import BillingSetupStatusEnum +from .types.booking_status import BookingStatusEnum from .types.brand_request_rejection_reason import ( BrandRequestRejectionReasonEnum, ) @@ -399,6 +401,7 @@ from .types.manager_link_status import ManagerLinkStatusEnum from .types.match_type import MatchTypeEnum from .types.media_type import MediaTypeEnum +from .types.messaging_restriction_type import MessagingRestrictionTypeEnum from .types.mime_type import MimeTypeEnum from .types.minute_of_hour import MinuteOfHourEnum from .types.mobile_app_vendor import MobileAppVendorEnum @@ -597,7 +600,9 @@ from .types.video_thumbnail import VideoThumbnailEnum from .types.webpage_condition_operand import WebpageConditionOperandEnum from .types.webpage_condition_operator import WebpageConditionOperatorEnum +from .types.youtube_video_privacy import YouTubeVideoPrivacyEnum from .types.youtube_video_property import YouTubeVideoPropertyEnum +from .types.youtube_video_upload_state import YouTubeVideoUploadStateEnum if hasattr(api_core, "check_python_version") and hasattr( api_core, "check_dependency_versions" @@ -763,12 +768,14 @@ def _get_version(dependency_name): "BatchJobStatusEnum", "BenchmarksMarketingObjectiveEnum", "BenchmarksSourceTypeEnum", + "BenchmarksTimeGranularityEnum", "BidModifierSourceEnum", "BiddingSourceEnum", "BiddingStrategyStatusEnum", "BiddingStrategySystemStatusEnum", "BiddingStrategyTypeEnum", "BillingSetupStatusEnum", + "BookingStatusEnum", "BrandRequestRejectionReasonEnum", "BrandSafetySuitabilityEnum", "BrandStateEnum", @@ -933,6 +940,7 @@ def _get_version(dependency_name): "ManagerLinkStatusEnum", "MatchTypeEnum", "MediaTypeEnum", + "MessagingRestrictionTypeEnum", "MimeTypeEnum", "MinuteOfHourEnum", "MobileAppVendorEnum", @@ -1055,5 +1063,7 @@ def _get_version(dependency_name): "VideoThumbnailEnum", "WebpageConditionOperandEnum", "WebpageConditionOperatorEnum", + "YouTubeVideoPrivacyEnum", "YouTubeVideoPropertyEnum", + "YouTubeVideoUploadStateEnum", ) diff --git a/google/ads/googleads/v23/enums/types/__init__.py b/google/ads/googleads/v23/enums/types/__init__.py index 2053d0700..3aaafeebc 100644 --- a/google/ads/googleads/v23/enums/types/__init__.py +++ b/google/ads/googleads/v23/enums/types/__init__.py @@ -214,6 +214,9 @@ from .benchmarks_source_type import ( BenchmarksSourceTypeEnum, ) +from .benchmarks_time_granularity import ( + BenchmarksTimeGranularityEnum, +) from .bid_modifier_source import ( BidModifierSourceEnum, ) @@ -232,6 +235,9 @@ from .billing_setup_status import ( BillingSetupStatusEnum, ) +from .booking_status import ( + BookingStatusEnum, +) from .brand_request_rejection_reason import ( BrandRequestRejectionReasonEnum, ) @@ -724,6 +730,9 @@ from .media_type import ( MediaTypeEnum, ) +from .messaging_restriction_type import ( + MessagingRestrictionTypeEnum, +) from .mime_type import ( MimeTypeEnum, ) @@ -1090,9 +1099,15 @@ from .webpage_condition_operator import ( WebpageConditionOperatorEnum, ) +from .youtube_video_privacy import ( + YouTubeVideoPrivacyEnum, +) from .youtube_video_property import ( YouTubeVideoPropertyEnum, ) +from .youtube_video_upload_state import ( + YouTubeVideoUploadStateEnum, +) __all__ = ( "AccessInvitationStatusEnum", @@ -1162,12 +1177,14 @@ "BatchJobStatusEnum", "BenchmarksMarketingObjectiveEnum", "BenchmarksSourceTypeEnum", + "BenchmarksTimeGranularityEnum", "BidModifierSourceEnum", "BiddingSourceEnum", "BiddingStrategyStatusEnum", "BiddingStrategySystemStatusEnum", "BiddingStrategyTypeEnum", "BillingSetupStatusEnum", + "BookingStatusEnum", "BrandRequestRejectionReasonEnum", "BrandSafetySuitabilityEnum", "BrandStateEnum", @@ -1332,6 +1349,7 @@ "ManagerLinkStatusEnum", "MatchTypeEnum", "MediaTypeEnum", + "MessagingRestrictionTypeEnum", "MimeTypeEnum", "MinuteOfHourEnum", "MobileAppVendorEnum", @@ -1454,5 +1472,7 @@ "VideoThumbnailEnum", "WebpageConditionOperandEnum", "WebpageConditionOperatorEnum", + "YouTubeVideoPrivacyEnum", "YouTubeVideoPropertyEnum", + "YouTubeVideoUploadStateEnum", ) diff --git a/google/ads/googleads/v23/enums/types/benchmarks_time_granularity.py b/google/ads/googleads/v23/enums/types/benchmarks_time_granularity.py new file mode 100644 index 000000000..fcd22d057 --- /dev/null +++ b/google/ads/googleads/v23/enums/types/benchmarks_time_granularity.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.ads.googleads.v23.enums", + marshal="google.ads.googleads.v23", + manifest={ + "BenchmarksTimeGranularityEnum", + }, +) + + +class BenchmarksTimeGranularityEnum(proto.Message): + r"""Container for enum describing time granularities for + aggregating YouTube ad benchmarks data. + + """ + + class BenchmarksTimeGranularity(proto.Enum): + r"""Possible time granularities for aggregating YouTube ad + benchmarks data. + + Values: + UNSPECIFIED (0): + Not specified. + UNKNOWN (1): + Used as a return value only. Represents value + unknown in this version. + WEEK (2): + Aggregate by week. + MONTH (3): + Aggregate by month. + QUARTER (4): + Aggregate by quarter. + """ + + UNSPECIFIED = 0 + UNKNOWN = 1 + WEEK = 2 + MONTH = 3 + QUARTER = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/enums/types/booking_status.py b/google/ads/googleads/v23/enums/types/booking_status.py new file mode 100644 index 000000000..f2a4c7f20 --- /dev/null +++ b/google/ads/googleads/v23/enums/types/booking_status.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.ads.googleads.v23.enums", + marshal="google.ads.googleads.v23", + manifest={ + "BookingStatusEnum", + }, +) + + +class BookingStatusEnum(proto.Message): + r"""Container for enum with booking status.""" + + class BookingStatus(proto.Enum): + r"""Booking status. + + Values: + UNSPECIFIED (0): + Not specified. + UNKNOWN (1): + Used for return value only. Represents value + unknown in this version. + BOOKED (2): + The booking is active and holds inventory for + the campaign. + HELD (3): + The campaign is holding inventory, but the + booking is not confirmed. + CAMPAIGN_ENDED (4): + The campaign has ended and is no longer + holding inventory. + HOLD_EXPIRED (5): + The hold on the inventory has expired. + BOOKING_CANCELLED (6): + The campaign was booked, but was in a + non-servable state for too long and the booking + was cancelled by the system. + """ + + UNSPECIFIED = 0 + UNKNOWN = 1 + BOOKED = 2 + HELD = 3 + CAMPAIGN_ENDED = 4 + HOLD_EXPIRED = 5 + BOOKING_CANCELLED = 6 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/enums/types/campaign_primary_status_reason.py b/google/ads/googleads/v23/enums/types/campaign_primary_status_reason.py index db9e08c64..5d1c6f05a 100644 --- a/google/ads/googleads/v23/enums/types/campaign_primary_status_reason.py +++ b/google/ads/googleads/v23/enums/types/campaign_primary_status_reason.py @@ -154,6 +154,26 @@ class CampaignPrimaryStatusReason(proto.Enum): MISSING_LOCATION_TARGETING (39): The campaign has location restrictions but does not specify location targeting. + CAMPAIGN_NOT_BOOKED (40): + The campaign is a campaign with the FIXED_CPM bidding + strategy but is not booked. Contributes to + CampaignPrimaryStatus.NOT_ELIGIBLE when the campaign is not + paused, and CampaignPrimaryStatus.PAUSED when the campaign + is paused. + BOOKING_HOLD_EXPIRING (41): + The campaign is a campaign with the FIXED_CPM bidding + strategy for which inventory was held, with the hold + expiring. The hold expiry time can be read from + Campaign.booking_details.hold_expiration_date_time. + Contributes to CampaignPrimaryStatus.PAUSED. + BOOKING_HOLD_EXPIRED (42): + The campaign is a campaign with the FIXED_CPM bidding + strategy with the inventory hold expired. Contributes to + CampaignPrimaryStatus.PAUSED. + BOOKING_CANCELLED (43): + The campaign is a campaign with the FIXED_CPM bidding + strategy that has been auto-cancelled. Contributes to + CampaignPrimaryStatus.NOT_ELIGIBLE. """ UNSPECIFIED = 0 @@ -196,6 +216,10 @@ class CampaignPrimaryStatusReason(proto.Enum): NO_ASSET_GROUPS = 37 ASSET_GROUPS_PAUSED = 38 MISSING_LOCATION_TARGETING = 39 + CAMPAIGN_NOT_BOOKED = 40 + BOOKING_HOLD_EXPIRING = 41 + BOOKING_HOLD_EXPIRED = 42 + BOOKING_CANCELLED = 43 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/enums/types/conversion_action_category.py b/google/ads/googleads/v23/enums/types/conversion_action_category.py index 8d1b6d6af..53ae76484 100644 --- a/google/ads/googleads/v23/enums/types/conversion_action_category.py +++ b/google/ads/googleads/v23/enums/types/conversion_action_category.py @@ -108,6 +108,10 @@ class ConversionActionCategory(proto.Enum): source into Google Ads, that has further completed a chosen stage as defined by the lead gen advertiser. + YOUTUBE_FOLLOW_ON_VIEWS (24): + User watches an ad from a channel and later + watches either the same video or a video from + the same channel as the ad. """ UNSPECIFIED = 0 @@ -133,6 +137,7 @@ class ConversionActionCategory(proto.Enum): STORE_SALE = 21 QUALIFIED_LEAD = 22 CONVERTED_LEAD = 23 + YOUTUBE_FOLLOW_ON_VIEWS = 24 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/enums/types/messaging_restriction_type.py b/google/ads/googleads/v23/enums/types/messaging_restriction_type.py new file mode 100644 index 000000000..990244763 --- /dev/null +++ b/google/ads/googleads/v23/enums/types/messaging_restriction_type.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.ads.googleads.v23.enums", + marshal="google.ads.googleads.v23", + manifest={ + "MessagingRestrictionTypeEnum", + }, +) + + +class MessagingRestrictionTypeEnum(proto.Message): + r"""Container for enum describing the type of a text generation + restriction. + + """ + + class MessagingRestrictionType(proto.Enum): + r"""The type of a text generation restriction. + + Values: + UNSPECIFIED (0): + Not specified. + UNKNOWN (1): + Used for return value only. Represents value + unknown in this version. + RESTRICTION_BASED_EXCLUSION (2): + Exclude text assets that are not compliant + with this restriction. + """ + + UNSPECIFIED = 0 + UNKNOWN = 1 + RESTRICTION_BASED_EXCLUSION = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/enums/types/reach_plan_surface.py b/google/ads/googleads/v23/enums/types/reach_plan_surface.py index 1ae940e80..fe20b262d 100644 --- a/google/ads/googleads/v23/enums/types/reach_plan_surface.py +++ b/google/ads/googleads/v23/enums/types/reach_plan_surface.py @@ -57,6 +57,8 @@ class ReachPlanSurface(proto.Enum): In-Stream skippable ad surface. SHORTS (6): Shorts ad surface. + GOOGLE_DISPLAY_NETWORK (9): + Google Display Network ad surface. """ UNSPECIFIED = 0 @@ -68,6 +70,7 @@ class ReachPlanSurface(proto.Enum): IN_STREAM_NON_SKIPPABLE = 4 IN_STREAM_SKIPPABLE = 5 SHORTS = 6 + GOOGLE_DISPLAY_NETWORK = 9 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/enums/types/search_term_match_source.py b/google/ads/googleads/v23/enums/types/search_term_match_source.py index 70ff710c0..7cfda44f7 100644 --- a/google/ads/googleads/v23/enums/types/search_term_match_source.py +++ b/google/ads/googleads/v23/enums/types/search_term_match_source.py @@ -56,6 +56,9 @@ class SearchTermMatchSource(proto.Enum): PERFORMANCE_MAX (6): The match is from the search term matching functionality in PMax. + VERTICAL_ADS_DATA_FEED (7): + The match is from a vertical ads data feed + (e.g. Travel Ads entity targeting). """ UNSPECIFIED = 0 @@ -65,6 +68,7 @@ class SearchTermMatchSource(proto.Enum): AI_MAX_BROAD_MATCH = 4 DYNAMIC_SEARCH_ADS = 5 PERFORMANCE_MAX = 6 + VERTICAL_ADS_DATA_FEED = 7 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/enums/types/youtube_video_privacy.py b/google/ads/googleads/v23/enums/types/youtube_video_privacy.py new file mode 100644 index 000000000..7e250d3fe --- /dev/null +++ b/google/ads/googleads/v23/enums/types/youtube_video_privacy.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.ads.googleads.v23.enums", + marshal="google.ads.googleads.v23", + manifest={ + "YouTubeVideoPrivacyEnum", + }, +) + + +class YouTubeVideoPrivacyEnum(proto.Message): + r"""Container for enum describing the privacy status of a YouTube + video. + + """ + + class YouTubeVideoPrivacy(proto.Enum): + r"""Describes the privacy status of a YouTube video. + + Values: + UNSPECIFIED (0): + Not specified. + UNKNOWN (1): + The value is unknown in this version. + PUBLIC (2): + Video is public. + UNLISTED (3): + Video is unlisted. + """ + + UNSPECIFIED = 0 + UNKNOWN = 1 + PUBLIC = 2 + UNLISTED = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/enums/types/youtube_video_upload_state.py b/google/ads/googleads/v23/enums/types/youtube_video_upload_state.py new file mode 100644 index 000000000..8e04dc957 --- /dev/null +++ b/google/ads/googleads/v23/enums/types/youtube_video_upload_state.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.ads.googleads.v23.enums", + marshal="google.ads.googleads.v23", + manifest={ + "YouTubeVideoUploadStateEnum", + }, +) + + +class YouTubeVideoUploadStateEnum(proto.Message): + r"""Container for enum describing the state of a YouTube video + upload. + + """ + + class YouTubeVideoUploadState(proto.Enum): + r"""Represents the current state of a video within its upload and + processing lifecycle. It tracks the full progression from upload + initiation through processing and completion, including failure, + rejection, or deletion outcomes. It helps determine whether a + video is still being uploaded, ready for use, or no longer + available. + + Values: + UNSPECIFIED (0): + Not specified. + UNKNOWN (1): + The value is unknown in this version. + PENDING (2): + The video is currently being uploaded. + UPLOADED (3): + The video was uploaded and is being + processed. + PROCESSED (4): + The video was successfully uploaded and + processed. + FAILED (5): + The video upload or processing did not + complete successfully. + REJECTED (6): + The video was not accepted due to validation + or policy reasons. + UNAVAILABLE (7): + The video upload state is unavailable. It may + have been removed from YouTube. + """ + + UNSPECIFIED = 0 + UNKNOWN = 1 + PENDING = 2 + UPLOADED = 3 + PROCESSED = 4 + FAILED = 5 + REJECTED = 6 + UNAVAILABLE = 7 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/errors/types/criterion_error.py b/google/ads/googleads/v23/errors/types/criterion_error.py index bc551c938..2085b01b8 100644 --- a/google/ads/googleads/v23/errors/types/criterion_error.py +++ b/google/ads/googleads/v23/errors/types/criterion_error.py @@ -470,6 +470,10 @@ class CriterionError(proto.Enum): ONLY_EXCLUSION_BRAND_LIST_ALLOWED_FOR_CAMPAIGN_TYPE (158): Brand list can only be negatively targeted for the campaign type. + CANNOT_TARGET_ONLY_UNDETERMINED (165): + The combination of demographic criteria would + result in only targeting the "undetermined" + segment, which is prohibited. LOCATION_TARGETING_NOT_ELIGIBLE_FOR_RESTRICTED_CAMPAIGN (166): Cannot positively target locations outside of restricted area for campaign. @@ -671,6 +675,7 @@ class CriterionError(proto.Enum): BRAND_SHARED_SET_DOES_NOT_EXIST = 156 CANNOT_ADD_REMOVED_BRAND_SHARED_SET = 157 ONLY_EXCLUSION_BRAND_LIST_ALLOWED_FOR_CAMPAIGN_TYPE = 158 + CANNOT_TARGET_ONLY_UNDETERMINED = 165 LOCATION_TARGETING_NOT_ELIGIBLE_FOR_RESTRICTED_CAMPAIGN = 166 ONLY_INCLUSION_BRAND_LIST_ALLOWED_FOR_AD_GROUPS = 171 CANNOT_ADD_REMOVED_PLACEMENT_LIST_SHARED_SET = 172 diff --git a/google/ads/googleads/v23/errors/types/incentive_error.py b/google/ads/googleads/v23/errors/types/incentive_error.py index 0a1b103ac..d5dfe73e5 100644 --- a/google/ads/googleads/v23/errors/types/incentive_error.py +++ b/google/ads/googleads/v23/errors/types/incentive_error.py @@ -43,11 +43,20 @@ class IncentiveError(proto.Enum): INVALID_INCENTIVE_ID (2): The incentive ID is either invalid or not supported for the given country. + MAX_INCENTIVES_REDEEMED (3): + The maximum number of coupons has been + redeemed. + ACCOUNT_TOO_OLD (4): + This incentive cannot be applied because too + much time has passed since the account's first + ad impression. """ UNSPECIFIED = 0 UNKNOWN = 1 INVALID_INCENTIVE_ID = 2 + MAX_INCENTIVES_REDEEMED = 3 + ACCOUNT_TOO_OLD = 4 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/errors/types/mutate_error.py b/google/ads/googleads/v23/errors/types/mutate_error.py index f6e856730..837c69eaa 100644 --- a/google/ads/googleads/v23/errors/types/mutate_error.py +++ b/google/ads/googleads/v23/errors/types/mutate_error.py @@ -62,6 +62,10 @@ class MutateError(proto.Enum): This operation cannot be used with "partial_failure". RESOURCE_READ_ONLY (13): Attempt to write to read-only fields. + EU_POLITICAL_ADVERTISING_DECLARATION_REQUIRED (17): + Mutates are generally not allowed if the + customer contains non-exempt campaigns without + the EU political advertising declaration. """ UNSPECIFIED = 0 @@ -75,6 +79,7 @@ class MutateError(proto.Enum): RESOURCE_DOES_NOT_SUPPORT_VALIDATE_ONLY = 12 OPERATION_DOES_NOT_SUPPORT_PARTIAL_FAILURE = 16 RESOURCE_READ_ONLY = 13 + EU_POLITICAL_ADVERTISING_DECLARATION_REQUIRED = 17 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/errors/types/product_link_invitation_error.py b/google/ads/googleads/v23/errors/types/product_link_invitation_error.py index e2630fe21..0bdbb563d 100644 --- a/google/ads/googleads/v23/errors/types/product_link_invitation_error.py +++ b/google/ads/googleads/v23/errors/types/product_link_invitation_error.py @@ -56,6 +56,9 @@ class ProductLinkInvitationError(proto.Enum): CUSTOMER_NOT_PERMITTED_TO_CREATE_INVITATION (5): The customer is not permitted to create the invitation. + INVALID_ADVERTISING_PARTNER_ALLOWED_DOMAIN (6): + The ``allowed_domain`` property for the advertising partner + is invalid. """ UNSPECIFIED = 0 @@ -64,6 +67,7 @@ class ProductLinkInvitationError(proto.Enum): PERMISSION_DENIED = 3 NO_INVITATION_REQUIRED = 4 CUSTOMER_NOT_PERMITTED_TO_CREATE_INVITATION = 5 + INVALID_ADVERTISING_PARTNER_ALLOWED_DOMAIN = 6 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/gapic_metadata.json b/google/ads/googleads/v23/gapic_metadata.json index 1bc46a006..775f7ac9b 100644 --- a/google/ads/googleads/v23/gapic_metadata.json +++ b/google/ads/googleads/v23/gapic_metadata.json @@ -3180,6 +3180,50 @@ } } } + }, + "YouTubeVideoUploadService": { + "clients": { + "grpc": { + "libraryClient": "YouTubeVideoUploadServiceClient", + "rpcs": { + "CreateYouTubeVideoUpload": { + "methods": [ + "create_you_tube_video_upload" + ] + }, + "RemoveYouTubeVideoUpload": { + "methods": [ + "remove_you_tube_video_upload" + ] + }, + "UpdateYouTubeVideoUpload": { + "methods": [ + "update_you_tube_video_upload" + ] + } + } + }, + "grpc-async": { + "libraryClient": "YouTubeVideoUploadServiceAsyncClient", + "rpcs": { + "CreateYouTubeVideoUpload": { + "methods": [ + "create_you_tube_video_upload" + ] + }, + "RemoveYouTubeVideoUpload": { + "methods": [ + "remove_you_tube_video_upload" + ] + }, + "UpdateYouTubeVideoUpload": { + "methods": [ + "update_you_tube_video_upload" + ] + } + } + } + } } } } diff --git a/google/ads/googleads/v23/resources/__init__.py b/google/ads/googleads/v23/resources/__init__.py index f69610731..53388e29b 100644 --- a/google/ads/googleads/v23/resources/__init__.py +++ b/google/ads/googleads/v23/resources/__init__.py @@ -285,6 +285,7 @@ from .types.product_category_constant import ProductCategoryConstant from .types.product_group_view import ProductGroupView from .types.product_link import AdvertisingPartnerIdentifier +from .types.product_link import AdvertisingPartnerProperties from .types.product_link import DataPartnerIdentifier from .types.product_link import GoogleAdsIdentifier from .types.product_link import MerchantCenterIdentifier @@ -292,6 +293,9 @@ from .types.product_link_invitation import ( AdvertisingPartnerLinkInvitationIdentifier, ) +from .types.product_link_invitation import ( + AdvertisingPartnerLinkInvitationProperties, +) from .types.product_link_invitation import HotelCenterLinkInvitationIdentifier from .types.product_link_invitation import ( MerchantCenterLinkInvitationIdentifier, @@ -322,6 +326,7 @@ from .types.user_location_view import UserLocationView from .types.video import Video from .types.webpage_view import WebpageView +from .types.youtube_video_upload import YouTubeVideoUpload if hasattr(api_core, "check_python_version") and hasattr( api_core, "check_dependency_versions" @@ -449,6 +454,8 @@ def _get_version(dependency_name): "AdStrengthActionItem", "AdvertisingPartnerIdentifier", "AdvertisingPartnerLinkInvitationIdentifier", + "AdvertisingPartnerLinkInvitationProperties", + "AdvertisingPartnerProperties", "AgeRangeView", "AiMaxSearchTermAdCombinationView", "AndroidPrivacySharedKeyGoogleAdGroup", @@ -657,5 +664,6 @@ def _get_version(dependency_name): "Video", "VideoCustomer", "WebpageView", + "YouTubeVideoUpload", "YoutubeVideoIdentifier", ) diff --git a/google/ads/googleads/v23/resources/types/__init__.py b/google/ads/googleads/v23/resources/types/__init__.py index 3cc9fc737..b9f3919dc 100644 --- a/google/ads/googleads/v23/resources/types/__init__.py +++ b/google/ads/googleads/v23/resources/types/__init__.py @@ -535,6 +535,7 @@ ) from .product_link import ( AdvertisingPartnerIdentifier, + AdvertisingPartnerProperties, DataPartnerIdentifier, GoogleAdsIdentifier, MerchantCenterIdentifier, @@ -542,6 +543,7 @@ ) from .product_link_invitation import ( AdvertisingPartnerLinkInvitationIdentifier, + AdvertisingPartnerLinkInvitationProperties, HotelCenterLinkInvitationIdentifier, MerchantCenterLinkInvitationIdentifier, ProductLinkInvitation, @@ -615,6 +617,9 @@ from .webpage_view import ( WebpageView, ) +from .youtube_video_upload import ( + YouTubeVideoUpload, +) __all__ = ( "AccessibleBiddingStrategy", @@ -824,11 +829,13 @@ "ProductCategoryConstant", "ProductGroupView", "AdvertisingPartnerIdentifier", + "AdvertisingPartnerProperties", "DataPartnerIdentifier", "GoogleAdsIdentifier", "MerchantCenterIdentifier", "ProductLink", "AdvertisingPartnerLinkInvitationIdentifier", + "AdvertisingPartnerLinkInvitationProperties", "HotelCenterLinkInvitationIdentifier", "MerchantCenterLinkInvitationIdentifier", "ProductLinkInvitation", @@ -855,4 +862,5 @@ "UserLocationView", "Video", "WebpageView", + "YouTubeVideoUpload", ) diff --git a/google/ads/googleads/v23/resources/types/ad_group_ad_asset_view.py b/google/ads/googleads/v23/resources/types/ad_group_ad_asset_view.py index 4fe19fde4..9ebd61981 100644 --- a/google/ads/googleads/v23/resources/types/ad_group_ad_asset_view.py +++ b/google/ads/googleads/v23/resources/types/ad_group_ad_asset_view.py @@ -39,9 +39,17 @@ class AdGroupAdAssetView(proto.Message): - r"""A link between an AdGroupAd and an Asset. AdGroupAdAssetView - supports AppAds, Demand Gen campaigns, and Responsive Search - Ads. + r"""Represents a link between an AdGroupAd and an Asset. This view + provides insights into the performance of assets within specific + ads. + + AdGroupAdAssetView supports the following ad types: + + - App Ads + - Demand Gen campaigns + - Responsive Search Ads + + It does not support Responsive Display Ads. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/google/ads/googleads/v23/resources/types/campaign.py b/google/ads/googleads/v23/resources/types/campaign.py index e1d43fd6d..e0154de58 100644 --- a/google/ads/googleads/v23/resources/types/campaign.py +++ b/google/ads/googleads/v23/resources/types/campaign.py @@ -61,6 +61,7 @@ from google.ads.googleads.v23.enums.types import ( bidding_strategy_type as gage_bidding_strategy_type, ) +from google.ads.googleads.v23.enums.types import booking_status from google.ads.googleads.v23.enums.types import brand_safety_suitability from google.ads.googleads.v23.enums.types import campaign_experiment_type from google.ads.googleads.v23.enums.types import campaign_keyword_match_type @@ -75,6 +76,7 @@ from google.ads.googleads.v23.enums.types import ( location_source_type as gage_location_source_type, ) +from google.ads.googleads.v23.enums.types import messaging_restriction_type from google.ads.googleads.v23.enums.types import ( negative_geo_target_type as gage_negative_geo_target_type, ) @@ -425,6 +427,11 @@ class Campaign(proto.Message): within this campaign. Note: These settings can only be used for Performance Max campaigns that have Brand Guidelines enabled. + text_guidelines (google.ads.googleads.v23.resources.types.Campaign.TextGuidelines): + Settings to control automatically generated + text assets. Only available in Performance Max + and Search campaigns (Brand Guidelines does not + need to be enabled). third_party_integration_partners (google.ads.googleads.v23.common.types.CampaignThirdPartyIntegrationPartners): Third-Party integration partners. ai_max_setting (google.ads.googleads.v23.resources.types.Campaign.AiMaxSetting): @@ -436,6 +443,15 @@ class Campaign(proto.Message): feed_types (MutableSequence[google.ads.googleads.v23.enums.types.AssetSetTypeEnum.AssetSetType]): Output only. Types of feeds that are attached directly to this campaign. + missing_eu_political_advertising_declaration (bool): + Output only. Indicates whether this campaign is missing a + declaration about whether it contains political advertising + targeted towards the EU and is ineligible for any + exemptions. If this field is true, use the + contains_eu_political_advertising field to add the required + declaration. + + This field is read-only. bidding_strategy (str): The resource name of the portfolio bidding strategy used by the campaign. @@ -1092,6 +1108,12 @@ class VideoCampaignSettings(proto.Message): video_ad_sequence (google.ads.googleads.v23.resources.types.Campaign.VideoCampaignSettings.VideoAdSequence): Container for video ads sequencing definition. + reservation_ad_category_self_disclosure (google.ads.googleads.v23.resources.types.Campaign.VideoCampaignSettings.ReservationAdCategorySelfDisclosure): + Ad category self-disclosure for campaigns with the FIXED_CPM + or FIXED_SHARE_OF_VOICE bidding strategies. + booking_details (google.ads.googleads.v23.resources.types.Campaign.VideoCampaignSettings.BookingDetails): + Output only. Booking information for campaigns with the + FIXED_CPM or FIXED_SHARE_OF_VOICE bidding strategies. video_ad_inventory_control (google.ads.googleads.v23.resources.types.Campaign.VideoCampaignSettings.VideoAdInventoryControl): Inventory control for video responsive ads in reach campaigns. @@ -1293,6 +1315,71 @@ class VideoAdSequenceStep(proto.Message): enum=video_ad_sequence_interaction_type.VideoAdSequenceInteractionTypeEnum.VideoAdSequenceInteractionType, ) + class ReservationAdCategorySelfDisclosure(proto.Message): + r"""Container for ad category self-disclosure for campaigns with the + FIXED_CPM or FIXED_SHARE_OF_VOICE bidding strategies. + + Attributes: + gambling (bool): + The campaign is expected to contain + gambling-related ads. + alcohol (bool): + The campaign is expected to contain + alcohol-related ads. + politics (bool): + The campaign is expected to contain + politics-related ads. + """ + + gambling: bool = proto.Field( + proto.BOOL, + number=1, + ) + alcohol: bool = proto.Field( + proto.BOOL, + number=2, + ) + politics: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class BookingDetails(proto.Message): + r"""Container for booking details for campaigns with the FIXED_CPM or + FIXED_SHARE_OF_VOICE bidding strategies. + + Attributes: + status (google.ads.googleads.v23.enums.types.BookingStatusEnum.BookingStatus): + Output only. The status of the booking. + hold_expiration_date_time (str): + Output only. Time until which booked inventory will be held + or has been held for this campaign. Available for status + HELD and HOLD_EXPIRED. Format is "yyyy-MM-dd HH:mm:ss" in + the customer's time zone. + cancellation_date_time (str): + Output only. Time when the booked inventory of this campaign + will be cancelled or has been cancelled. Available for + primary status NOT_ELIGIBLE if the campaign will be + cancelled and for primary status reason BOOKING_CANCELLED. + Format is "yyyy-MM-dd HH:mm:ss" in the customer's time zone. + """ + + status: booking_status.BookingStatusEnum.BookingStatus = ( + proto.Field( + proto.ENUM, + number=1, + enum=booking_status.BookingStatusEnum.BookingStatus, + ) + ) + hold_expiration_date_time: str = proto.Field( + proto.STRING, + number=2, + ) + cancellation_date_time: str = proto.Field( + proto.STRING, + number=3, + ) + video_ad_sequence: "Campaign.VideoCampaignSettings.VideoAdSequence" = ( proto.Field( proto.MESSAGE, @@ -1300,6 +1387,20 @@ class VideoAdSequenceStep(proto.Message): message="Campaign.VideoCampaignSettings.VideoAdSequence", ) ) + reservation_ad_category_self_disclosure: ( + "Campaign.VideoCampaignSettings.ReservationAdCategorySelfDisclosure" + ) = proto.Field( + proto.MESSAGE, + number=5, + message="Campaign.VideoCampaignSettings.ReservationAdCategorySelfDisclosure", + ) + booking_details: "Campaign.VideoCampaignSettings.BookingDetails" = ( + proto.Field( + proto.MESSAGE, + number=6, + message="Campaign.VideoCampaignSettings.BookingDetails", + ) + ) video_ad_inventory_control: ( "Campaign.VideoCampaignSettings.VideoAdInventoryControl" ) = proto.Field( @@ -1424,6 +1525,60 @@ class BrandGuidelines(proto.Message): number=3, ) + class TextGuidelines(proto.Message): + r"""Settings to control automatically generated text assets. + + Attributes: + term_exclusions (MutableSequence[str]): + Exact words or phrases that will be excluded + from generated text assets. At most 25 + exclusions may be provided. Valid exclusions may + contain a maximum of 30 characters. + messaging_restrictions (MutableSequence[google.ads.googleads.v23.resources.types.Campaign.MessagingRestriction]): + Freeform instructions that will be used to + guide text asset generation using LLM inference. + At most 40 restrictions may be provided. + """ + + term_exclusions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + messaging_restrictions: MutableSequence[ + "Campaign.MessagingRestriction" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Campaign.MessagingRestriction", + ) + + class MessagingRestriction(proto.Message): + r"""Freeform instructions that will be used to guide text asset + generation using LLM inference. + + Attributes: + restriction_text (str): + Freeform instructions to guide text asset + generation using LLM inference. Valid + instructions may contain a maximum of 300 + characters. + restriction_type (google.ads.googleads.v23.enums.types.MessagingRestrictionTypeEnum.MessagingRestrictionType): + Determines how the guideline is applied. Only + ``RESTRICTION_BASED_EXCLUSION`` is currently supported. + """ + + restriction_text: str = proto.Field( + proto.STRING, + number=1, + ) + restriction_type: ( + messaging_restriction_type.MessagingRestrictionTypeEnum.MessagingRestrictionType + ) = proto.Field( + proto.ENUM, + number=2, + enum=messaging_restriction_type.MessagingRestrictionTypeEnum.MessagingRestrictionType, + ) + class AiMaxSetting(proto.Message): r"""Settings for AI Max in search campaigns. @@ -1806,6 +1961,11 @@ class AiMaxBundlingRequired(proto.Enum): number=98, message=BrandGuidelines, ) + text_guidelines: TextGuidelines = proto.Field( + proto.MESSAGE, + number=107, + message=TextGuidelines, + ) third_party_integration_partners: ( gagc_third_party_integration_partners.CampaignThirdPartyIntegrationPartners ) = proto.Field( @@ -1832,6 +1992,10 @@ class AiMaxBundlingRequired(proto.Enum): number=103, enum=asset_set_type.AssetSetTypeEnum.AssetSetType, ) + missing_eu_political_advertising_declaration: bool = proto.Field( + proto.BOOL, + number=108, + ) bidding_strategy: str = proto.Field( proto.STRING, number=67, diff --git a/google/ads/googleads/v23/resources/types/campaign_budget.py b/google/ads/googleads/v23/resources/types/campaign_budget.py index e38dd5aa5..fa4a96cdd 100644 --- a/google/ads/googleads/v23/resources/types/campaign_budget.py +++ b/google/ads/googleads/v23/resources/types/campaign_budget.py @@ -70,18 +70,32 @@ class CampaignBudget(proto.Message): This field is a member of `oneof`_ ``_name``. amount_micros (int): - The amount of the budget, in the local - currency for the account. Amount is specified in - micros, where one million is equivalent to one - currency unit. Monthly spend is capped at 30.4 - times this amount. + The average daily amount to be spent by the campaign. This + field is used when the CampaignBudget ``period`` is set to + ``DAILY``, which is the default. + + Amount is specified in micros in the account's local + currency. One million micros is equivalent to one currency + unit. The effective monthly spend is capped at 30.4 times + this daily amount. + + This field is mutually exclusive with 'total_amount_micros'. + Only one of 'amount_micros' or 'total_amount_micros' should + be set. This field is a member of `oneof`_ ``_amount_micros``. total_amount_micros (int): - The lifetime amount of the budget, in the - local currency for the account. Amount is - specified in micros, where one million is - equivalent to one currency unit. + The total amount to be spent by the campaign over its entire + duration. This field is used *only* when the CampaignBudget + ``period`` is set to ``CUSTOM_PERIOD``. It represents the + budget cap for the campaign's lifetime, rather than a daily + limit. The amount is specified in micros in the account's + local currency. One million micros is equivalent to one + currency unit. + + This field is mutually exclusive with 'amount_micros'. Only + one of 'total_amount_micros' or 'amount_micros' should be + set. This field is a member of `oneof`_ ``_total_amount_micros``. status (google.ads.googleads.v23.enums.types.BudgetStatusEnum.BudgetStatus): diff --git a/google/ads/googleads/v23/resources/types/customer.py b/google/ads/googleads/v23/resources/types/customer.py index c24f53558..7b50b9f5b 100644 --- a/google/ads/googleads/v23/resources/types/customer.py +++ b/google/ads/googleads/v23/resources/types/customer.py @@ -28,6 +28,7 @@ customer_pay_per_conversion_eligibility_failure_reason, ) from google.ads.googleads.v23.enums.types import customer_status +from google.ads.googleads.v23.enums.types import eu_political_advertising_status from google.ads.googleads.v23.enums.types import ( local_services_verification_status, ) @@ -192,6 +193,14 @@ class Customer(proto.Message): https://support.google.com/google-ads/answer/7515513. video_customer (google.ads.googleads.v23.resources.types.VideoCustomer): Video specific information about a Customer. + contains_eu_political_advertising (google.ads.googleads.v23.enums.types.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus): + Output only. Returns the advertiser + self-declaration status of whether this customer + contains political advertising content targeted + towards the European Union. You can use the + Google Ads UI to update this account-level + declaration, or use the API to update the + self-declaration status of individual campaigns. """ resource_name: str = proto.Field( @@ -326,6 +335,13 @@ class Customer(proto.Message): number=54, message="VideoCustomer", ) + contains_eu_political_advertising: ( + eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus + ) = proto.Field( + proto.ENUM, + number=55, + enum=eu_political_advertising_status.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus, + ) class CallReportingSetting(proto.Message): diff --git a/google/ads/googleads/v23/resources/types/local_services_lead.py b/google/ads/googleads/v23/resources/types/local_services_lead.py index 724ec0ded..09cf8b8fe 100644 --- a/google/ads/googleads/v23/resources/types/local_services_lead.py +++ b/google/ads/googleads/v23/resources/types/local_services_lead.py @@ -168,8 +168,12 @@ class ContactDetails(proto.Message): Attributes: phone_number (str): - Output only. Consumer phone number in E164 - format. + Output only. Phone number of the consumer for + the lead. This can be a real phone number or a + tracking number. The phone number is returned in + E164 format. See + https://support.google.com/google-ads/answer/16355235?hl=en + to learn more. Example: +16504519489. email (str): Output only. Consumer email address. consumer_name (str): diff --git a/google/ads/googleads/v23/resources/types/product_link.py b/google/ads/googleads/v23/resources/types/product_link.py index 5b9713106..91eb4614f 100644 --- a/google/ads/googleads/v23/resources/types/product_link.py +++ b/google/ads/googleads/v23/resources/types/product_link.py @@ -30,6 +30,7 @@ "GoogleAdsIdentifier", "MerchantCenterIdentifier", "AdvertisingPartnerIdentifier", + "AdvertisingPartnerProperties", }, ) @@ -74,6 +75,12 @@ class ProductLink(proto.Message): Output only. Advertising Partner link. This field is a member of `oneof`_ ``linked_product``. + advertising_partner_properties (google.ads.googleads.v23.resources.types.AdvertisingPartnerProperties): + Output only. Advertising Partner link + properties. These properties are only applicable + when the link is for an Advertising Partner. + + This field is a member of `oneof`_ ``product_link_properties``. """ resource_name: str = proto.Field( @@ -116,6 +123,14 @@ class ProductLink(proto.Message): oneof="linked_product", message="AdvertisingPartnerIdentifier", ) + advertising_partner_properties: "AdvertisingPartnerProperties" = ( + proto.Field( + proto.MESSAGE, + number=15, + oneof="product_link_properties", + message="AdvertisingPartnerProperties", + ) + ) class DataPartnerIdentifier(proto.Message): @@ -213,4 +228,26 @@ class AdvertisingPartnerIdentifier(proto.Message): ) +class AdvertisingPartnerProperties(proto.Message): + r"""Properties specific to an Advertising Partner link. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allowed_domain (str): + Output only. The allowed domain for the + Advertising Partner link. The advertising + partner will only be able to advertise on this + domain. The field is immutable. + + This field is a member of `oneof`_ ``_allowed_domain``. + """ + + allowed_domain: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/resources/types/product_link_invitation.py b/google/ads/googleads/v23/resources/types/product_link_invitation.py index 0d7f61875..51a3e46f8 100644 --- a/google/ads/googleads/v23/resources/types/product_link_invitation.py +++ b/google/ads/googleads/v23/resources/types/product_link_invitation.py @@ -30,6 +30,7 @@ "HotelCenterLinkInvitationIdentifier", "MerchantCenterLinkInvitationIdentifier", "AdvertisingPartnerLinkInvitationIdentifier", + "AdvertisingPartnerLinkInvitationProperties", }, ) @@ -75,6 +76,13 @@ class ProductLinkInvitation(proto.Message): invitation. This field is a member of `oneof`_ ``invited_account``. + advertising_partner_properties (google.ads.googleads.v23.resources.types.AdvertisingPartnerLinkInvitationProperties): + Output only. Advertising Partner link + invitation properties. These properties are only + applicable when the link is for an Advertising + Partner. + + This field is a member of `oneof`_ ``invited_account_properties``. """ resource_name: str = proto.Field( @@ -119,6 +127,14 @@ class ProductLinkInvitation(proto.Message): message="AdvertisingPartnerLinkInvitationIdentifier", ) ) + advertising_partner_properties: ( + "AdvertisingPartnerLinkInvitationProperties" + ) = proto.Field( + proto.MESSAGE, + number=8, + oneof="invited_account_properties", + message="AdvertisingPartnerLinkInvitationProperties", + ) class HotelCenterLinkInvitationIdentifier(proto.Message): @@ -174,4 +190,29 @@ class AdvertisingPartnerLinkInvitationIdentifier(proto.Message): ) +class AdvertisingPartnerLinkInvitationProperties(proto.Message): + r"""Properties specific to an Advertising Partner link + invitation. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allowed_domain (str): + Immutable. The allowed domain for the + Advertising Partner link invitation. The + advertising partner will only be able to + advertise on this domain. The field is immutable + after the creation of the link invitation. + + This field is a member of `oneof`_ ``_allowed_domain``. + """ + + allowed_domain: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/resources/types/user_list.py b/google/ads/googleads/v23/resources/types/user_list.py index e599dc0ce..b77242780 100644 --- a/google/ads/googleads/v23/resources/types/user_list.py +++ b/google/ads/googleads/v23/resources/types/user_list.py @@ -39,7 +39,12 @@ class UserList(proto.Message): - r"""A user list. This is a list of users a customer may target. + r"""A user list. This is a list of users a customer may target. The + unique key of a user list consists of the following fields: ``id``. + Note that the ``name`` must also be unique for user lists owned by a + given customer, except in some cases where ``access_reason`` is set + to ``SHARED``. Violating the unique name constraint produces error: + ``UserListError.INVALID_NAME``. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -68,9 +73,9 @@ class UserList(proto.Message): This field is a member of `oneof`_ ``_read_only``. name (str): - Name of this user list. Depending on its access_reason, the - user list name may not be unique (for example, if - access_reason=SHARED) + Name of this user list. Unique per user list, except in some + cases where a user list of the same name has + ``access_reason`` set to ``SHARED``. This field is a member of `oneof`_ ``_name``. description (str): diff --git a/google/ads/googleads/v23/resources/types/youtube_video_upload.py b/google/ads/googleads/v23/resources/types/youtube_video_upload.py new file mode 100644 index 000000000..80840b54f --- /dev/null +++ b/google/ads/googleads/v23/resources/types/youtube_video_upload.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + + +import proto # type: ignore + +from google.ads.googleads.v23.enums.types import youtube_video_privacy +from google.ads.googleads.v23.enums.types import youtube_video_upload_state + + +__protobuf__ = proto.module( + package="google.ads.googleads.v23.resources", + marshal="google.ads.googleads.v23", + manifest={ + "YouTubeVideoUpload", + }, +) + + +class YouTubeVideoUpload(proto.Message): + r"""Represents a video upload to YouTube using the Google Ads + API. + + Attributes: + resource_name (str): + Immutable. Resource name of the YouTube video + upload. + video_upload_id (int): + Output only. The unique ID of the YouTube + video upload. + channel_id (str): + Immutable. The destination YouTube channel ID + for the video upload. + Only mutable on YouTube video upload creation. + If omitted, the video will be uploaded to the + Google-managed YouTube channel associated with + the Ads account. + video_id (str): + Output only. The YouTube video ID of the + uploaded video. + state (google.ads.googleads.v23.enums.types.YouTubeVideoUploadStateEnum.YouTubeVideoUploadState): + Output only. The current state of the YouTube + video upload. + video_title (str): + Input only. Immutable. The title of the + video. + Only mutable on YouTube video upload creation. + Immutable after creation. + video_description (str): + Input only. Immutable. The description of the + video. + Only mutable on YouTube video upload creation. + Immutable after creation. + video_privacy (google.ads.googleads.v23.enums.types.YouTubeVideoPrivacyEnum.YouTubeVideoPrivacy): + The privacy state of the video. + + Only mutable for videos uploaded to the + advertiser owned (brand) YouTube channel. For + videos uploaded to the Google-managed channels + only UNLISTED privacy is allowed. Defaults to + UNLISTED privacy if not specified. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + video_upload_id: int = proto.Field( + proto.INT64, + number=2, + ) + channel_id: str = proto.Field( + proto.STRING, + number=3, + ) + video_id: str = proto.Field( + proto.STRING, + number=4, + ) + state: ( + youtube_video_upload_state.YouTubeVideoUploadStateEnum.YouTubeVideoUploadState + ) = proto.Field( + proto.ENUM, + number=5, + enum=youtube_video_upload_state.YouTubeVideoUploadStateEnum.YouTubeVideoUploadState, + ) + video_title: str = proto.Field( + proto.STRING, + number=6, + ) + video_description: str = proto.Field( + proto.STRING, + number=7, + ) + video_privacy: ( + youtube_video_privacy.YouTubeVideoPrivacyEnum.YouTubeVideoPrivacy + ) = proto.Field( + proto.ENUM, + number=8, + enum=youtube_video_privacy.YouTubeVideoPrivacyEnum.YouTubeVideoPrivacy, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/ads/googleads/v23/services/__init__.py b/google/ads/googleads/v23/services/__init__.py index 60671663b..fb3f814f9 100644 --- a/google/ads/googleads/v23/services/__init__.py +++ b/google/ads/googleads/v23/services/__init__.py @@ -220,6 +220,9 @@ BenchmarksProductMetadata, BenchmarksSource, BenchmarksSourceMetadata, + BreakdownDefinition, + BreakdownKey, + BreakdownMetrics, GenerateBenchmarksMetricsRequest, GenerateBenchmarksMetricsResponse, IndustryVerticalInfo, @@ -365,6 +368,7 @@ SearchAudience, SearchTopics, TrendInsight, + TrendInsightDataPoint, TrendInsightMetrics, YouTubeChannelInsights, YouTubeCreatorInsights, @@ -845,6 +849,14 @@ MutateUserListsResponse, UserListOperation, ) +from .types.youtube_video_upload_service import ( + CreateYouTubeVideoUploadRequest, + CreateYouTubeVideoUploadResponse, + RemoveYouTubeVideoUploadRequest, + RemoveYouTubeVideoUploadResponse, + UpdateYouTubeVideoUploadRequest, + UpdateYouTubeVideoUploadResponse, +) __all__ = ( "AccountBudgetProposalOperation", @@ -999,6 +1011,9 @@ "BenchmarksProductMetadata", "BenchmarksSource", "BenchmarksSourceMetadata", + "BreakdownDefinition", + "BreakdownKey", + "BreakdownMetrics", "GenerateBenchmarksMetricsRequest", "GenerateBenchmarksMetricsResponse", "IndustryVerticalInfo", @@ -1104,6 +1119,7 @@ "SearchAudience", "SearchTopics", "TrendInsight", + "TrendInsightDataPoint", "TrendInsightMetrics", "YouTubeChannelInsights", "YouTubeCreatorInsights", @@ -1461,4 +1477,10 @@ "MutateUserListsRequest", "MutateUserListsResponse", "UserListOperation", + "CreateYouTubeVideoUploadRequest", + "CreateYouTubeVideoUploadResponse", + "RemoveYouTubeVideoUploadRequest", + "RemoveYouTubeVideoUploadResponse", + "UpdateYouTubeVideoUploadRequest", + "UpdateYouTubeVideoUploadResponse", ) diff --git a/google/ads/googleads/v23/services/services/google_ads_service/async_client.py b/google/ads/googleads/v23/services/services/google_ads_service/async_client.py index ce9102f85..9f47d0d57 100644 --- a/google/ads/googleads/v23/services/services/google_ads_service/async_client.py +++ b/google/ads/googleads/v23/services/services/google_ads_service/async_client.py @@ -1067,6 +1067,12 @@ class GoogleAdsServiceAsyncClient: parse_webpage_view_path = staticmethod( GoogleAdsServiceClient.parse_webpage_view_path ) + you_tube_video_upload_path = staticmethod( + GoogleAdsServiceClient.you_tube_video_upload_path + ) + parse_you_tube_video_upload_path = staticmethod( + GoogleAdsServiceClient.parse_you_tube_video_upload_path + ) common_billing_account_path = staticmethod( GoogleAdsServiceClient.common_billing_account_path ) diff --git a/google/ads/googleads/v23/services/services/google_ads_service/client.py b/google/ads/googleads/v23/services/services/google_ads_service/client.py index 0116aab2c..284a36b89 100644 --- a/google/ads/googleads/v23/services/services/google_ads_service/client.py +++ b/google/ads/googleads/v23/services/services/google_ads_service/client.py @@ -4062,6 +4062,26 @@ def parse_webpage_view_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def you_tube_video_upload_path( + customer_id: str, + video_upload_id: str, + ) -> str: + """Returns a fully-qualified you_tube_video_upload string.""" + return "customers/{customer_id}/youTubeVideoUploads/{video_upload_id}".format( + customer_id=customer_id, + video_upload_id=video_upload_id, + ) + + @staticmethod + def parse_you_tube_video_upload_path(path: str) -> Dict[str, str]: + """Parses a you_tube_video_upload path into its component segments.""" + m = re.match( + r"^customers/(?P.+?)/youTubeVideoUploads/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/__init__.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/__init__.py new file mode 100644 index 000000000..18d94eb38 --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import YouTubeVideoUploadServiceClient +from .async_client import YouTubeVideoUploadServiceAsyncClient + +__all__ = ( + "YouTubeVideoUploadServiceClient", + "YouTubeVideoUploadServiceAsyncClient", +) diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/async_client.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/async_client.py new file mode 100644 index 000000000..27dcbf1e8 --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/async_client.py @@ -0,0 +1,624 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +from typing import Callable, Optional, BinaryIO, Sequence, Tuple, Union + +from google.ads.googleads.v23 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +try: + OptionalRetry = Union[ + retries.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.ads.googleads.v23.resources.types import youtube_video_upload +from google.ads.googleads.v23.services.types import youtube_video_upload_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ( + YouTubeVideoUploadServiceTransport, + DEFAULT_CLIENT_INFO, +) +from .client import YouTubeVideoUploadServiceClient + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class YouTubeVideoUploadServiceAsyncClient: + """Service to manage YouTube video uploads.""" + + _client: YouTubeVideoUploadServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = YouTubeVideoUploadServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ( + YouTubeVideoUploadServiceClient.DEFAULT_MTLS_ENDPOINT + ) + _DEFAULT_ENDPOINT_TEMPLATE = ( + YouTubeVideoUploadServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = YouTubeVideoUploadServiceClient._DEFAULT_UNIVERSE + + you_tube_video_upload_path = staticmethod( + YouTubeVideoUploadServiceClient.you_tube_video_upload_path + ) + parse_you_tube_video_upload_path = staticmethod( + YouTubeVideoUploadServiceClient.parse_you_tube_video_upload_path + ) + common_billing_account_path = staticmethod( + YouTubeVideoUploadServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + YouTubeVideoUploadServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + YouTubeVideoUploadServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + YouTubeVideoUploadServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + YouTubeVideoUploadServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + YouTubeVideoUploadServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + YouTubeVideoUploadServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + YouTubeVideoUploadServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + YouTubeVideoUploadServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + YouTubeVideoUploadServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + YouTubeVideoUploadServiceAsyncClient: The constructed client. + """ + return YouTubeVideoUploadServiceClient.from_service_account_info.__func__(YouTubeVideoUploadServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + YouTubeVideoUploadServiceAsyncClient: The constructed client. + """ + return YouTubeVideoUploadServiceClient.from_service_account_file.__func__(YouTubeVideoUploadServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return YouTubeVideoUploadServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> YouTubeVideoUploadServiceTransport: + """Returns the transport used by the client instance. + + Returns: + YouTubeVideoUploadServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = YouTubeVideoUploadServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + developer_token: Optional[str] = None, + login_customer_id: Optional[str] = None, + linked_customer_id: Optional[str] = None, + use_cloud_org_for_api_access: bool = False, + transport: Optional[ + Union[ + str, + YouTubeVideoUploadServiceTransport, + Callable[..., YouTubeVideoUploadServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the you tube video upload service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + developer_token (Optional[str]): The developer token to use for the + resumable upload transport. This will be used by the resumable upload methods + (create_you_tube_video_upload) ONLY! + login_customer_id (Optional[str]): The login customer ID to use for + the resumable upload transport. This will be used by the resumable upload methods + (create_you_tube_video_upload) ONLY! + linked_customer_id (Optional[str]): The linked customer ID to use for + the resumable upload transport. This will be used by the resumable upload methods + (create_you_tube_video_upload) ONLY! + use_cloud_org_for_api_access (bool): Whether to use the cloud org for + API access for the resumable upload transport. This will be used by the resumable upload methods + (create_you_tube_video_upload) ONLY! + transport (Optional[Union[str,YouTubeVideoUploadServiceTransport,Callable[..., YouTubeVideoUploadServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the YouTubeVideoUploadServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = YouTubeVideoUploadServiceClient( + credentials=credentials, + developer_token=developer_token, + login_customer_id=login_customer_id, + linked_customer_id=linked_customer_id, + use_cloud_org_for_api_access=use_cloud_org_for_api_access, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ads.googleads.v23.services.YouTubeVideoUploadServiceAsyncClient`.", + extra=( + { + "serviceName": "google.ads.googleads.v23.services.YouTubeVideoUploadService", + "universeDomain": getattr( + self._client._transport._credentials, + "universe_domain", + "", + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, + "get_cred_info", + lambda: None, + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.ads.googleads.v23.services.YouTubeVideoUploadService", + "credentialsType": None, + } + ), + ) + + async def create_you_tube_video_upload( + self, + request: Optional[ + Union[ + youtube_video_upload_service.CreateYouTubeVideoUploadRequest, + dict, + ] + ] = None, + *, + customer_id: Optional[str] = None, + you_tube_video_upload: Optional[ + youtube_video_upload.YouTubeVideoUpload + ] = None, + stream: BinaryIO, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> youtube_video_upload_service.CreateYouTubeVideoUploadResponse: + r"""Uploads a video to Google-managed or advertiser owned + (brand) YouTube channel. + + Args: + request (Optional[Union[google.ads.googleads.v23.services.types.CreateYouTubeVideoUploadRequest, dict]]): + The request object. Request message for + [YouTubeVideoUploadService.CreateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.CreateYouTubeVideoUpload]. + customer_id (:class:`str`): + Required. The customer ID requesting + the upload. Required. + + This corresponds to the ``customer_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + you_tube_video_upload (:class:`google.ads.googleads.v23.resources.types.YouTubeVideoUpload`): + Required. The initial details of the + video to upload. Required. + + This corresponds to the ``you_tube_video_upload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream (BinaryIO): + The stream to upload. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.googleads.v23.services.types.CreateYouTubeVideoUploadResponse: + Response message for + [YouTubeVideoUploadService.CreateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.CreateYouTubeVideoUpload]. + + """ + raise NotImplementedError( + "Resumable upload is not yet supported in the async client." + ) + + async def update_you_tube_video_upload( + self, + request: Optional[ + Union[ + youtube_video_upload_service.UpdateYouTubeVideoUploadRequest, + dict, + ] + ] = None, + *, + customer_id: Optional[str] = None, + you_tube_video_upload: Optional[ + youtube_video_upload.YouTubeVideoUpload + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> youtube_video_upload_service.UpdateYouTubeVideoUploadResponse: + r"""Updates YouTube video's metadata, but only for videos + uploaded using this API. + + Args: + request (Optional[Union[google.ads.googleads.v23.services.types.UpdateYouTubeVideoUploadRequest, dict]]): + The request object. Request message for + [YouTubeVideoUploadService.UpdateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.UpdateYouTubeVideoUpload]. + customer_id (:class:`str`): + Required. The customer ID requesting + the YouTube video upload update. + Required. + + This corresponds to the ``customer_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + you_tube_video_upload (:class:`google.ads.googleads.v23.resources.types.YouTubeVideoUpload`): + Required. The YouTube video upload + resource to be updated. It's expected to + have a valid resource name. Required. + + This corresponds to the ``you_tube_video_upload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. FieldMask that determines + which resource fields are modified in an + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.googleads.v23.services.types.UpdateYouTubeVideoUploadResponse: + Response message for + [YouTubeVideoUploadService.UpdateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.UpdateYouTubeVideoUpload]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [customer_id, you_tube_video_upload, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + youtube_video_upload_service.UpdateYouTubeVideoUploadRequest, + ): + request = ( + youtube_video_upload_service.UpdateYouTubeVideoUploadRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if customer_id is not None: + request.customer_id = customer_id + if you_tube_video_upload is not None: + request.you_tube_video_upload = you_tube_video_upload + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_you_tube_video_upload + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("customer_id", request.customer_id),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def remove_you_tube_video_upload( + self, + request: Optional[ + Union[ + youtube_video_upload_service.RemoveYouTubeVideoUploadRequest, + dict, + ] + ] = None, + *, + customer_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> youtube_video_upload_service.RemoveYouTubeVideoUploadResponse: + r"""Removes YouTube videos uploaded using this API. + + Args: + request (Optional[Union[google.ads.googleads.v23.services.types.RemoveYouTubeVideoUploadRequest, dict]]): + The request object. Request message for + [YouTubeVideoUploadService.RemoveYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.RemoveYouTubeVideoUpload]. + customer_id (:class:`str`): + Required. The customer ID requesting + the YouTube video upload deletion. + Required. + + This corresponds to the ``customer_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.googleads.v23.services.types.RemoveYouTubeVideoUploadResponse: + Response message for + [YouTubeVideoUploadService.RemoveYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.RemoveYouTubeVideoUpload]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [customer_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + youtube_video_upload_service.RemoveYouTubeVideoUploadRequest, + ): + request = ( + youtube_video_upload_service.RemoveYouTubeVideoUploadRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if customer_id is not None: + request.customer_id = customer_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.remove_you_tube_video_upload + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("customer_id", request.customer_id),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "YouTubeVideoUploadServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("YouTubeVideoUploadServiceAsyncClient",) diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/client.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/client.py new file mode 100644 index 000000000..564ffc928 --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/client.py @@ -0,0 +1,1191 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Dict, + Callable, + Optional, + BinaryIO, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.ads.googleads.v23 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.ads.googleads.v23.resources.types import youtube_video_upload +from google.ads.googleads.v23.services.types import youtube_video_upload_service +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import ( + YouTubeVideoUploadServiceTransport, + DEFAULT_CLIENT_INFO, +) +from .transports.rest_resumable import ( + YouTubeVideoUploadServiceRestResumableTransport, +) +from .transports.grpc import YouTubeVideoUploadServiceGrpcTransport +from .transports.grpc_asyncio import ( + YouTubeVideoUploadServiceGrpcAsyncIOTransport, +) + + +class YouTubeVideoUploadServiceClientMeta(type): + """Metaclass for the YouTubeVideoUploadService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[YouTubeVideoUploadServiceTransport]] + _transport_registry["grpc"] = YouTubeVideoUploadServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ( + YouTubeVideoUploadServiceGrpcAsyncIOTransport + ) + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[YouTubeVideoUploadServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class YouTubeVideoUploadServiceClient( + metaclass=YouTubeVideoUploadServiceClientMeta +): + """Service to manage YouTube video uploads.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "googleads.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "googleads.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + YouTubeVideoUploadServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info( + info + ) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + YouTubeVideoUploadServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename + ) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> YouTubeVideoUploadServiceTransport: + """Returns the transport used by the client instance. + + Returns: + YouTubeVideoUploadServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def you_tube_video_upload_path( + customer_id: str, + video_upload_id: str, + ) -> str: + """Returns a fully-qualified you_tube_video_upload string.""" + return "customers/{customer_id}/youTubeVideoUploads/{video_upload_id}".format( + customer_id=customer_id, + video_upload_id=video_upload_id, + ) + + @staticmethod + def parse_you_tube_video_upload_path(path: str) -> Dict[str, str]: + """Parses a you_tube_video_upload path into its component segments.""" + m = re.match( + r"^customers/(?P.+?)/youTubeVideoUploads/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = ( + YouTubeVideoUploadServiceClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = ( + YouTubeVideoUploadServiceClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv( + "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" + ).lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = ( + YouTubeVideoUploadServiceClient._DEFAULT_UNIVERSE + ) + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = YouTubeVideoUploadServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = YouTubeVideoUploadServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], + universe_domain_env: Optional[str], + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = YouTubeVideoUploadServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + developer_token: Optional[str] = None, + login_customer_id: Optional[str] = None, + linked_customer_id: Optional[str] = None, + use_cloud_org_for_api_access: bool = False, + transport: Optional[ + Union[ + str, + YouTubeVideoUploadServiceTransport, + Callable[..., YouTubeVideoUploadServiceTransport], + ] + ] = None, + client_options: Optional[ + Union[client_options_lib.ClientOptions, dict] + ] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the you tube video upload service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + developer_token (Optional[str]): The developer token to use for the + resumable upload transport. This will be used by the resumable upload methods + (create_you_tube_video_upload) ONLY! + login_customer_id (Optional[str]): The login customer ID to use for + the resumable upload transport. This will be used by the resumable upload methods + (create_you_tube_video_upload) ONLY! + linked_customer_id (Optional[str]): The linked customer ID to use for + the resumable upload transport. This will be used by the resumable upload methods + (create_you_tube_video_upload) ONLY! + use_cloud_org_for_api_access (bool): Whether to use the cloud org for + API access for the resumable upload transport. This will be used by the resumable upload methods + (create_you_tube_video_upload) ONLY! + transport (Optional[Union[str,YouTubeVideoUploadServiceTransport,Callable[..., YouTubeVideoUploadServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the YouTubeVideoUploadServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict( + self._client_options + ) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr( + self._client_options, "universe_domain", None + ) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = YouTubeVideoUploadServiceClient._read_environment_variables() + self._client_cert_source = ( + YouTubeVideoUploadServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ( + YouTubeVideoUploadServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance( + transport, YouTubeVideoUploadServiceTransport + ) + if transport_provided: + # transport is a YouTubeVideoUploadServiceTransport instance. + if self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast( + YouTubeVideoUploadServiceTransport, transport + ) + self._api_endpoint = self._transport.host + resumable_creds = credentials or getattr( + self._transport, "_credentials", None + ) + + if resumable_creds is None: + raise ValueError( + "For the correct REST resumable transport initialization, either the credentials should be explicitly provided as a `credentials` parameter, or the transport passed should contain readable `_credentials` property. E.g. passing a GRPC channel as a transport does not satisfy this since the credentials cannot be extracted from it. This requirement is unique to the YouTubeVideoUploadService." + ) + + self._rest_resumable_transport = ( + YouTubeVideoUploadServiceRestResumableTransport( + credentials=resumable_creds, + credentials_file=None, + host=self._transport.host, + scopes=self._transport._scopes, + developer_token=developer_token, + login_customer_id=login_customer_id, + linked_customer_id=linked_customer_id, + use_cloud_org_for_api_access=use_cloud_org_for_api_access, + ) + ) + + self._api_endpoint = ( + self._api_endpoint + or YouTubeVideoUploadServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[YouTubeVideoUploadServiceTransport], + Callable[..., YouTubeVideoUploadServiceTransport], + ] = ( + YouTubeVideoUploadServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast( + Callable[..., YouTubeVideoUploadServiceTransport], transport + ) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + # Initialize a separate transport for the rest resumable uploads + self._rest_resumable_transport = ( + YouTubeVideoUploadServiceRestResumableTransport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + developer_token=developer_token, + login_customer_id=login_customer_id, + linked_customer_id=linked_customer_id, + use_cloud_org_for_api_access=use_cloud_org_for_api_access, + ) + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ads.googleads.v23.services.YouTubeVideoUploadServiceClient`.", + extra=( + { + "serviceName": "google.ads.googleads.v23.services.YouTubeVideoUploadService", + "universeDomain": getattr( + self._transport._credentials, + "universe_domain", + "", + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, + "get_cred_info", + lambda: None, + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.ads.googleads.v23.services.YouTubeVideoUploadService", + "credentialsType": None, + } + ), + ) + + def create_you_tube_video_upload( + self, + request: Optional[ + Union[ + youtube_video_upload_service.CreateYouTubeVideoUploadRequest, + dict, + ] + ] = None, + *, + customer_id: Optional[str] = None, + you_tube_video_upload: Optional[ + youtube_video_upload.YouTubeVideoUpload + ] = None, + stream: BinaryIO, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> youtube_video_upload_service.CreateYouTubeVideoUploadResponse: + r"""Uploads a video to Google-managed or advertiser owned + (brand) YouTube channel. + + Args: + request (Union[google.ads.googleads.v23.services.types.CreateYouTubeVideoUploadRequest, dict]): + The request object. Request message for + [YouTubeVideoUploadService.CreateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.CreateYouTubeVideoUpload]. + customer_id (str): + Required. The customer ID requesting + the upload. Required. + + This corresponds to the ``customer_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + you_tube_video_upload (google.ads.googleads.v23.resources.types.YouTubeVideoUpload): + Required. The initial details of the + video to upload. Required. + + This corresponds to the ``you_tube_video_upload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + stream (BinaryIO): + The stream to upload. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.googleads.v23.services.types.CreateYouTubeVideoUploadResponse: + Response message for + [YouTubeVideoUploadService.CreateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.CreateYouTubeVideoUpload]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [customer_id, you_tube_video_upload] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + youtube_video_upload_service.CreateYouTubeVideoUploadRequest, + ): + request = ( + youtube_video_upload_service.CreateYouTubeVideoUploadRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if customer_id is not None: + request.customer_id = customer_id + if you_tube_video_upload is not None: + request.you_tube_video_upload = you_tube_video_upload + + if stream is None: + raise ValueError("stream is required for resumable upload methods") + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("customer_id", request.customer_id),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = self._rest_resumable_transport.create_you_tube_video_upload_resumable( + request=request, + stream=stream, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_you_tube_video_upload( + self, + request: Optional[ + Union[ + youtube_video_upload_service.UpdateYouTubeVideoUploadRequest, + dict, + ] + ] = None, + *, + customer_id: Optional[str] = None, + you_tube_video_upload: Optional[ + youtube_video_upload.YouTubeVideoUpload + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> youtube_video_upload_service.UpdateYouTubeVideoUploadResponse: + r"""Updates YouTube video's metadata, but only for videos + uploaded using this API. + + Args: + request (Union[google.ads.googleads.v23.services.types.UpdateYouTubeVideoUploadRequest, dict]): + The request object. Request message for + [YouTubeVideoUploadService.UpdateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.UpdateYouTubeVideoUpload]. + customer_id (str): + Required. The customer ID requesting + the YouTube video upload update. + Required. + + This corresponds to the ``customer_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + you_tube_video_upload (google.ads.googleads.v23.resources.types.YouTubeVideoUpload): + Required. The YouTube video upload + resource to be updated. It's expected to + have a valid resource name. Required. + + This corresponds to the ``you_tube_video_upload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. FieldMask that determines + which resource fields are modified in an + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.googleads.v23.services.types.UpdateYouTubeVideoUploadResponse: + Response message for + [YouTubeVideoUploadService.UpdateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.UpdateYouTubeVideoUpload]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [customer_id, you_tube_video_upload, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + youtube_video_upload_service.UpdateYouTubeVideoUploadRequest, + ): + request = ( + youtube_video_upload_service.UpdateYouTubeVideoUploadRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if customer_id is not None: + request.customer_id = customer_id + if you_tube_video_upload is not None: + request.you_tube_video_upload = you_tube_video_upload + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_you_tube_video_upload + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("customer_id", request.customer_id),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def remove_you_tube_video_upload( + self, + request: Optional[ + Union[ + youtube_video_upload_service.RemoveYouTubeVideoUploadRequest, + dict, + ] + ] = None, + *, + customer_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> youtube_video_upload_service.RemoveYouTubeVideoUploadResponse: + r"""Removes YouTube videos uploaded using this API. + + Args: + request (Union[google.ads.googleads.v23.services.types.RemoveYouTubeVideoUploadRequest, dict]): + The request object. Request message for + [YouTubeVideoUploadService.RemoveYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.RemoveYouTubeVideoUpload]. + customer_id (str): + Required. The customer ID requesting + the YouTube video upload deletion. + Required. + + This corresponds to the ``customer_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.googleads.v23.services.types.RemoveYouTubeVideoUploadResponse: + Response message for + [YouTubeVideoUploadService.RemoveYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.RemoveYouTubeVideoUpload]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [customer_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + youtube_video_upload_service.RemoveYouTubeVideoUploadRequest, + ): + request = ( + youtube_video_upload_service.RemoveYouTubeVideoUploadRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if customer_id is not None: + request.customer_id = customer_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.remove_you_tube_video_upload + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("customer_id", request.customer_id),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "YouTubeVideoUploadServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("YouTubeVideoUploadServiceClient",) diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/README.rst b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/README.rst new file mode 100644 index 000000000..ec14177eb --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`YouTubeVideoUploadServiceTransport` is the ABC for all transports. +- public child `YouTubeVideoUploadServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `YouTubeVideoUploadServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseYouTubeVideoUploadServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `YouTubeVideoUploadServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/__init__.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/__init__.py new file mode 100644 index 000000000..8fa98f6ea --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict + +from .base import YouTubeVideoUploadServiceTransport +from .grpc import YouTubeVideoUploadServiceGrpcTransport +from .grpc_asyncio import YouTubeVideoUploadServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[YouTubeVideoUploadServiceTransport]] +_transport_registry["grpc"] = YouTubeVideoUploadServiceGrpcTransport +_transport_registry["grpc_asyncio"] = ( + YouTubeVideoUploadServiceGrpcAsyncIOTransport +) + +__all__ = ( + "YouTubeVideoUploadServiceTransport", + "YouTubeVideoUploadServiceGrpcTransport", + "YouTubeVideoUploadServiceGrpcAsyncIOTransport", +) diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/base.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/base.py new file mode 100644 index 000000000..794e30bb0 --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/base.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Optional, Sequence, Union + +from google.ads.googleads.v23 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.ads.googleads.v23.services.types import youtube_video_upload_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class YouTubeVideoUploadServiceTransport(abc.ABC): + """Abstract transport class for YouTubeVideoUploadService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/adwords",) + + DEFAULT_HOST: str = "googleads.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'googleads.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr( + service_account.Credentials, "with_always_use_jwt_access" + ) + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_you_tube_video_upload: gapic_v1.method.wrap_method( + self.create_you_tube_video_upload, + default_timeout=None, + client_info=client_info, + ), + self.update_you_tube_video_upload: gapic_v1.method.wrap_method( + self.update_you_tube_video_upload, + default_timeout=None, + client_info=client_info, + ), + self.remove_you_tube_video_upload: gapic_v1.method.wrap_method( + self.remove_you_tube_video_upload, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_you_tube_video_upload( + self, + ) -> Callable[ + [youtube_video_upload_service.CreateYouTubeVideoUploadRequest], + Union[ + youtube_video_upload_service.CreateYouTubeVideoUploadResponse, + Awaitable[ + youtube_video_upload_service.CreateYouTubeVideoUploadResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def update_you_tube_video_upload( + self, + ) -> Callable[ + [youtube_video_upload_service.UpdateYouTubeVideoUploadRequest], + Union[ + youtube_video_upload_service.UpdateYouTubeVideoUploadResponse, + Awaitable[ + youtube_video_upload_service.UpdateYouTubeVideoUploadResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def remove_you_tube_video_upload( + self, + ) -> Callable[ + [youtube_video_upload_service.RemoveYouTubeVideoUploadRequest], + Union[ + youtube_video_upload_service.RemoveYouTubeVideoUploadResponse, + Awaitable[ + youtube_video_upload_service.RemoveYouTubeVideoUploadResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("YouTubeVideoUploadServiceTransport",) diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/grpc.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/grpc.py new file mode 100644 index 000000000..4e54c1c52 --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/grpc.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.ads.googleads.v23.services.types import youtube_video_upload_service +from .base import YouTubeVideoUploadServiceTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor( + grpc.UnaryUnaryClientInterceptor +): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = ( + f"{type(request).__name__}: {pickle.dumps(request)}" + ) + + request_metadata = { + key: ( + value.decode("utf-8") if isinstance(value, bytes) else value + ) + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ads.googleads.v23.services.YouTubeVideoUploadService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = ( + f"{type(result).__name__}: {pickle.dumps(result)}" + ) + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.ads.googleads.v23.services.YouTubeVideoUploadService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class YouTubeVideoUploadServiceGrpcTransport( + YouTubeVideoUploadServiceTransport +): + """gRPC backend transport for YouTubeVideoUploadService. + + Service to manage YouTube video uploads. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "googleads.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[ + Union[grpc.Channel, Callable[..., grpc.Channel]] + ] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[ + Callable[[], Tuple[bytes, bytes]] + ] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'googleads.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn( + "client_cert_source is deprecated", DeprecationWarning + ) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = ( + grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + ) + else: + self._ssl_channel_credentials = ( + SslCredentials().ssl_credentials + ) + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = ( + grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "googleads.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_you_tube_video_upload( + self, + ) -> Callable[ + [youtube_video_upload_service.CreateYouTubeVideoUploadRequest], + youtube_video_upload_service.CreateYouTubeVideoUploadResponse, + ]: + r"""Return a callable for the create you tube video upload method over gRPC. + + Uploads a video to Google-managed or advertiser owned + (brand) YouTube channel. + + Returns: + Callable[[~.CreateYouTubeVideoUploadRequest], + ~.CreateYouTubeVideoUploadResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_you_tube_video_upload" not in self._stubs: + self._stubs["create_you_tube_video_upload"] = ( + self._logged_channel.unary_unary( + "/google.ads.googleads.v23.services.YouTubeVideoUploadService/CreateYouTubeVideoUpload", + request_serializer=youtube_video_upload_service.CreateYouTubeVideoUploadRequest.serialize, + response_deserializer=youtube_video_upload_service.CreateYouTubeVideoUploadResponse.deserialize, + ) + ) + return self._stubs["create_you_tube_video_upload"] + + @property + def update_you_tube_video_upload( + self, + ) -> Callable[ + [youtube_video_upload_service.UpdateYouTubeVideoUploadRequest], + youtube_video_upload_service.UpdateYouTubeVideoUploadResponse, + ]: + r"""Return a callable for the update you tube video upload method over gRPC. + + Updates YouTube video's metadata, but only for videos + uploaded using this API. + + Returns: + Callable[[~.UpdateYouTubeVideoUploadRequest], + ~.UpdateYouTubeVideoUploadResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_you_tube_video_upload" not in self._stubs: + self._stubs["update_you_tube_video_upload"] = ( + self._logged_channel.unary_unary( + "/google.ads.googleads.v23.services.YouTubeVideoUploadService/UpdateYouTubeVideoUpload", + request_serializer=youtube_video_upload_service.UpdateYouTubeVideoUploadRequest.serialize, + response_deserializer=youtube_video_upload_service.UpdateYouTubeVideoUploadResponse.deserialize, + ) + ) + return self._stubs["update_you_tube_video_upload"] + + @property + def remove_you_tube_video_upload( + self, + ) -> Callable[ + [youtube_video_upload_service.RemoveYouTubeVideoUploadRequest], + youtube_video_upload_service.RemoveYouTubeVideoUploadResponse, + ]: + r"""Return a callable for the remove you tube video upload method over gRPC. + + Removes YouTube videos uploaded using this API. + + Returns: + Callable[[~.RemoveYouTubeVideoUploadRequest], + ~.RemoveYouTubeVideoUploadResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_you_tube_video_upload" not in self._stubs: + self._stubs["remove_you_tube_video_upload"] = ( + self._logged_channel.unary_unary( + "/google.ads.googleads.v23.services.YouTubeVideoUploadService/RemoveYouTubeVideoUpload", + request_serializer=youtube_video_upload_service.RemoveYouTubeVideoUploadRequest.serialize, + response_deserializer=youtube_video_upload_service.RemoveYouTubeVideoUploadResponse.deserialize, + ) + ) + return self._stubs["remove_you_tube_video_upload"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("YouTubeVideoUploadServiceGrpcTransport",) diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/grpc_asyncio.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/grpc_asyncio.py new file mode 100644 index 000000000..83d91cd27 --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/grpc_asyncio.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.ads.googleads.v23.services.types import youtube_video_upload_service +from .base import YouTubeVideoUploadServiceTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary( + self, continuation, client_call_details, request + ): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = ( + f"{type(request).__name__}: {pickle.dumps(request)}" + ) + + request_metadata = { + key: ( + value.decode("utf-8") if isinstance(value, bytes) else value + ) + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ads.googleads.v23.services.YouTubeVideoUploadService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = ( + f"{type(result).__name__}: {pickle.dumps(result)}" + ) + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.ads.googleads.v23.services.YouTubeVideoUploadService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class YouTubeVideoUploadServiceGrpcAsyncIOTransport( + YouTubeVideoUploadServiceTransport +): + """gRPC AsyncIO backend transport for YouTubeVideoUploadService. + + Service to manage YouTube video uploads. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "googleads.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "googleads.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[ + Union[aio.Channel, Callable[..., aio.Channel]] + ] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[ + Callable[[], Tuple[bytes, bytes]] + ] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'googleads.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn( + "client_cert_source is deprecated", DeprecationWarning + ) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = ( + grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + ) + else: + self._ssl_channel_credentials = ( + SslCredentials().ssl_credentials + ) + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = ( + grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" + in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_you_tube_video_upload( + self, + ) -> Callable[ + [youtube_video_upload_service.CreateYouTubeVideoUploadRequest], + Awaitable[ + youtube_video_upload_service.CreateYouTubeVideoUploadResponse + ], + ]: + r"""Return a callable for the create you tube video upload method over gRPC. + + Uploads a video to Google-managed or advertiser owned + (brand) YouTube channel. + + Returns: + Callable[[~.CreateYouTubeVideoUploadRequest], + Awaitable[~.CreateYouTubeVideoUploadResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_you_tube_video_upload" not in self._stubs: + self._stubs["create_you_tube_video_upload"] = ( + self._logged_channel.unary_unary( + "/google.ads.googleads.v23.services.YouTubeVideoUploadService/CreateYouTubeVideoUpload", + request_serializer=youtube_video_upload_service.CreateYouTubeVideoUploadRequest.serialize, + response_deserializer=youtube_video_upload_service.CreateYouTubeVideoUploadResponse.deserialize, + ) + ) + return self._stubs["create_you_tube_video_upload"] + + @property + def update_you_tube_video_upload( + self, + ) -> Callable[ + [youtube_video_upload_service.UpdateYouTubeVideoUploadRequest], + Awaitable[ + youtube_video_upload_service.UpdateYouTubeVideoUploadResponse + ], + ]: + r"""Return a callable for the update you tube video upload method over gRPC. + + Updates YouTube video's metadata, but only for videos + uploaded using this API. + + Returns: + Callable[[~.UpdateYouTubeVideoUploadRequest], + Awaitable[~.UpdateYouTubeVideoUploadResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_you_tube_video_upload" not in self._stubs: + self._stubs["update_you_tube_video_upload"] = ( + self._logged_channel.unary_unary( + "/google.ads.googleads.v23.services.YouTubeVideoUploadService/UpdateYouTubeVideoUpload", + request_serializer=youtube_video_upload_service.UpdateYouTubeVideoUploadRequest.serialize, + response_deserializer=youtube_video_upload_service.UpdateYouTubeVideoUploadResponse.deserialize, + ) + ) + return self._stubs["update_you_tube_video_upload"] + + @property + def remove_you_tube_video_upload( + self, + ) -> Callable[ + [youtube_video_upload_service.RemoveYouTubeVideoUploadRequest], + Awaitable[ + youtube_video_upload_service.RemoveYouTubeVideoUploadResponse + ], + ]: + r"""Return a callable for the remove you tube video upload method over gRPC. + + Removes YouTube videos uploaded using this API. + + Returns: + Callable[[~.RemoveYouTubeVideoUploadRequest], + Awaitable[~.RemoveYouTubeVideoUploadResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_you_tube_video_upload" not in self._stubs: + self._stubs["remove_you_tube_video_upload"] = ( + self._logged_channel.unary_unary( + "/google.ads.googleads.v23.services.YouTubeVideoUploadService/RemoveYouTubeVideoUpload", + request_serializer=youtube_video_upload_service.RemoveYouTubeVideoUploadRequest.serialize, + response_deserializer=youtube_video_upload_service.RemoveYouTubeVideoUploadResponse.deserialize, + ) + ) + return self._stubs["remove_you_tube_video_upload"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_you_tube_video_upload: self._wrap_method( + self.create_you_tube_video_upload, + default_timeout=None, + client_info=client_info, + ), + self.update_you_tube_video_upload: self._wrap_method( + self.update_you_tube_video_upload, + default_timeout=None, + client_info=client_info, + ), + self.remove_you_tube_video_upload: self._wrap_method( + self.remove_you_tube_video_upload, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ("YouTubeVideoUploadServiceGrpcAsyncIOTransport",) diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/rest_resumable.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/rest_resumable.py new file mode 100644 index 000000000..bfe0f7f7c --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/rest_resumable.py @@ -0,0 +1,343 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import base64 +import json # type: ignore +import os +from typing import Callable, Dict, Optional, Sequence, Tuple, Union, BinaryIO +from datetime import datetime, timedelta, timezone + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore + +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.ads.googleads.v23.services.types import youtube_video_upload_service + +from .rest_resumable_base import ( + _BaseYouTubeVideoUploadServiceRestResumableTransport, +) +from .resumable_upload import make_resumable_upload + + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +_DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024 # 10MB +_DEFAULT_TIMEOUT = 14400 +_DEFAULT_CONTENT_TYPE = "application/octet-stream" + +_DEFAULT_RETRY = retries.Retry( + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + ), + initial=1.0, + maximum=60.0, + multiplier=1.3, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class YouTubeVideoUploadServiceRestResumableInterceptor: + """Interceptor for YouTubeVideoUploadService. Not implemented yet""" + + +class YouTubeVideoUploadServiceRestResumableTransport( + _BaseYouTubeVideoUploadServiceRestResumableTransport +): + """REST backend synchronous transport for YouTubeVideoUploadService. + It is only used by Resumable Media Upload functionality + """ + + def __init__( + self, + *, + host: str = "googleads.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[ + Callable[[], Tuple[bytes, bytes]] + ] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[ + YouTubeVideoUploadServiceRestResumableInterceptor + ] = None, + api_audience: Optional[str] = None, + developer_token: Optional[str] = None, + login_customer_id: Optional[str] = None, + linked_customer_id: Optional[str] = None, + use_cloud_org_for_api_access: bool = False, + **kwargs, # Catch-all for forward compatibility + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'googleads.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + developer_token (Optional[str]): The developer token to use for the + resumable upload transport. + login_customer_id (Optional[str]): The login customer ID to use for + the resumable upload transport. + linked_customer_id (Optional[str]): The linked customer ID to use for + the resumable upload transport. + use_cloud_org_for_api_access (bool): Whether to use the cloud org for + API access for the resumable upload transport. + """ + # Run the base constructor + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + + self._developer_token = developer_token + self._login_customer_id = login_customer_id + self._linked_customer_id = linked_customer_id + self._use_cloud_org_for_api_access = use_cloud_org_for_api_access + + def _sanitize_headers_for_rest( + self, metadata: Union[Dict, Sequence[Tuple[str, Union[str, bytes]]]] + ) -> Dict[str, str]: + """ + Converts gRPC metadata into REST-friendly headers. + + - Decodes byte keys to strings. + - Base64 encodes byte values if the key ends with '-bin'. + - Raises ValueError if binary data is found in a non-'-bin' key. + """ + # Normalize input to a dict if it's a sequence + raw_headers = ( + dict(metadata) if not isinstance(metadata, dict) else metadata + ) + clean_headers = {} + + for key, value in raw_headers.items(): + # Ensure Key is a String + k_str = key.decode("utf-8") if isinstance(key, bytes) else key + + if isinstance(value, bytes): + if not k_str.endswith("-bin"): + raise ValueError( + f"Invalid binary header '{k_str}'. Binary data is only " + "allowed in keys ending with '-bin'." + ) + # Valid binary header: Base64 encode + clean_headers[k_str] = base64.b64encode(value).decode("ascii") + else: + # String value: Keep as is + clean_headers[k_str] = str(value) + + return clean_headers + + def _update_headers_with_googleads( + self, headers: dict[str, str] + ) -> dict[str, str]: + """ + Returns a new dictionary with identity headers injected, mirroring the + MetadataInterceptor logic. Does not modify the input dictionary. + """ + # Create a shallow copy to avoid in-place modification + new_headers = headers.copy() if headers else {} + + # 1. Developer Token Logic + # Only add if we are NOT using Cloud Org access AND the token exists. + # This prevents the crash if developer_token is None. + if not self._use_cloud_org_for_api_access and self._developer_token: + new_headers["developer-token"] = self._developer_token + + # 2. Login Customer ID Logic + if self._login_customer_id: + new_headers["login-customer-id"] = self._login_customer_id + + # 3. Linked Customer ID Logic + if self._linked_customer_id: + new_headers["linked-customer-id"] = self._linked_customer_id + + return new_headers + + @staticmethod + def _maybe_rewind(stream, rewind=False): + """Rewind the stream if desired. + + :type stream: IO[bytes] + :param stream: A bytes IO object open for reading. + + :type rewind: bool + :param rewind: Indicates if we should seek to the beginning of the stream. + """ + if rewind: + stream.seek(0, os.SEEK_SET) + + def create_you_tube_video_upload_resumable( + self, + request: youtube_video_upload_service.CreateYouTubeVideoUploadRequest, + *, + stream: BinaryIO, + rewind: bool = False, + size: Optional[int] = None, + content_type: Optional[str] = None, + chunk_size: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> youtube_video_upload_service.CreateYouTubeVideoUploadResponse: + r"""Uploads a video to Google-managed or advertiser owned + (brand) YouTube channel. + + Args: + request (Union[google.ads.googleads.v23.services.types.CreateYouTubeVideoUploadRequest, dict]): + The request object. Request message for + [YouTubeVideoUploadService.CreateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.CreateYouTubeVideoUpload]. + stream (BinaryIO): + A stream of bytes, such as a file opened in binary mode for reading. + rewind (bool): + If True, seek to the beginning of the file handle before uploading from the stream. + size (int): + The number of bytes to be uploaded (which will be read from + ``stream``). If not provided, the upload will be concluded once + ``stream`` is exhausted. + content_type (str): + The MIME type of the content being uploaded. + chunk_size (int): + The size of each chunk to be uploaded. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.googleads.v23.services.types.CreateYouTubeVideoUploadResponse: + Response message for + [YouTubeVideoUploadService.CreateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.CreateYouTubeVideoUpload]. + + + """ + + self._maybe_rewind(stream, rewind=rewind) + + http_options = ( + _BaseYouTubeVideoUploadServiceRestResumableTransport._BaseCreateYouTubeVideoUploadRequest._get_http_options() + ) + transcoded_request = _BaseYouTubeVideoUploadServiceRestResumableTransport._BaseCreateYouTubeVideoUploadRequest._get_transcoded_request( + http_options, request + ) + request_url = "{host}/resumable/upload{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + + # preserving_proto_field_name=True ensures we get snake case "customer_id" + json_body = json_format.MessageToJson( + request._pb, + preserving_proto_field_name=True, + ) + + if chunk_size is None: + chunk_size = _DEFAULT_CHUNK_SIZE + if retry is gapic_v1.method.DEFAULT: + retry = _DEFAULT_RETRY + if timeout is None or timeout is gapic_v1.method.DEFAULT: + timeout = _DEFAULT_TIMEOUT + if content_type is None: + content_type = _DEFAULT_CONTENT_TYPE + + deadline = datetime.now(timezone.utc) + timedelta(seconds=timeout) + headers = dict(metadata) + + # 1. Sanitize (will raise ValueError if headers are invalid) + headers = self._sanitize_headers_for_rest(headers or {}) + + # 2. Inject google-ads specific metadata + headers = self._update_headers_with_googleads(headers) + + response = make_resumable_upload( + transport=self._session, + request_body=json_body, + stream=stream, + upload_url=request_url, + size=size, + content_type=content_type, + chunk_size=chunk_size, + request_retry=retry, + deadline=deadline, + headers=headers, + on_progress=None, + ) + + data = response.json() + response_message = ( + youtube_video_upload_service.CreateYouTubeVideoUploadResponse() + ) + json_format.ParseDict( + data, response_message._pb, ignore_unknown_fields=True + ) + + return response_message + + +__all__ = ("YouTubeVideoUploadServiceRestResumableTransport",) diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/rest_resumable_base.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/rest_resumable_base.py new file mode 100644 index 000000000..9b73b1221 --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/rest_resumable_base.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Dict, List, Optional + +from google.api_core import gapic_v1, path_template +from google.protobuf import empty_pb2 # type: ignore + +from google.ads.googleads.v23.services.types import youtube_video_upload_service + +from .base import DEFAULT_CLIENT_INFO, YouTubeVideoUploadServiceTransport + + +class _BaseYouTubeVideoUploadServiceRestResumableTransport( + YouTubeVideoUploadServiceTransport +): + """Base REST Resumable backend transport for YouTubeVideoUploadService. + + Note: This class is not meant to be used directly. Only services that has RPCs + that should be invoked as resumable upload should instantiate it and use it. + """ + + def __init__( + self, + *, + host: str = "googleads.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'googleads.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match( + "^(?Phttp(?:s)?://)?(?P.*)$", host + ) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = ( + f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + ) + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateYouTubeVideoUploadRequest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v23/customers/{customer_id=*}/youTubeVideoUploads:create", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + youtube_video_upload_service.CreateYouTubeVideoUploadRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode( + http_options, pb_request + ) + return transcoded_request + + +__all__ = ("_BaseYouTubeVideoUploadServiceRestResumableTransport",) diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/resumable_upload.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/resumable_upload.py new file mode 100644 index 000000000..34533022f --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/resumable_upload.py @@ -0,0 +1,483 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import datetime +import logging + +from dataclasses import dataclass +from typing import ( + Any, + BinaryIO, + Callable, + Dict, + Optional, + Sequence, + Tuple, + Union, +) + +import google.api_core.retry +import requests +from .resumable_upload_error_adapter import raise_formatted_for_status + +_LOGGER = logging.getLogger(__name__) + +_DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024 # 10MB + + +@dataclass(frozen=True) +class ResumableUploadStatus: + """Status of a resumable upload. + + Attributes: + upload_url (str): + The session URL for the resumable upload. + total_bytes (Optional[int]): + The total number of bytes to be uploaded, if known. + bytes_uploaded (int): + The number of bytes successfully uploaded so far. + finished (bool): + Whether the upload has completed. + """ + + upload_url: str + total_bytes: Optional[int] + bytes_uploaded: int + finished: bool + + +class ResumableUpload: + """Manages a resumable upload session. + + This class handles the initiation, chunk transmission, and recovery + of a resumable upload according to the Google Resumable Upload protocol. + """ + + def __init__( + self, + upload_url: str, + stream: BinaryIO, + size: Optional[int] = None, + content_type: Optional[str] = None, + chunk_size: Optional[int] = None, + deadline: Optional[datetime.datetime] = None, + headers: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None, + on_progress: Optional[Callable[[ResumableUploadStatus], None]] = None, + ): + """Initializes the ResumableUpload object. + + Args: + upload_url (str): + The initial URL to start the resumable upload. + stream (BinaryIO): + A stream of bytes to be uploaded. + size (Optional[int]): + The total number of bytes to be uploaded. If not provided, + the upload continues until the stream is exhausted. + content_type (Optional[str]): + The MIME type of the content being uploaded. + chunk_size (Optional[int]): + The size of each chunk to be uploaded. Defaults to 10MB. + deadline (Optional[datetime.datetime]): + The deadline for the entire upload process. + headers (Optional[Sequence[Tuple[str, Union[str, bytes]]]]): + Extra headers to be sent with the initiation and chunk requests. + on_progress (Optional[Callable[[ResumableUploadStatus], None]]): + A callback function called after each successful chunk upload. + """ + self.initial_url = upload_url + self.stream = stream + self.size = size + self.content_type = content_type + self.chunk_size = chunk_size or _DEFAULT_CHUNK_SIZE + self.deadline = deadline + self.extra_headers = dict(headers or []) + self.on_progress = on_progress + + self.session_url = None + self.bytes_uploaded = 0 + self.finished = False + self.chunk_granularity = None + + def _check_deadline(self) -> Optional[float]: + if self.deadline: + now = datetime.datetime.now(datetime.timezone.utc) + timeout = (self.deadline - now).total_seconds() + if timeout <= 0: + raise Exception( + f"Upload deadline {self.deadline} (as calculated from the timeout argument) was exceeded" + ) + return timeout + return None + + def _get_retry_predicate(self): + def should_retry(exc): + if isinstance(exc, requests.exceptions.RequestException): + if isinstance( + exc, + ( + requests.exceptions.ConnectionError, + requests.exceptions.Timeout, + ), + ): + return True + if exc.response is not None: + status_code = exc.response.status_code + return status_code in (408, 429, 500, 502, 503, 504) + return False + + return should_retry + + def _log_request( + self, method: str, url: str, headers: Dict[str, str], data: Any = None + ): + if not _LOGGER.isEnabledFor(logging.DEBUG): + return + + display_data = data + if isinstance(data, bytes) and len(data) > 64: + display_data = f"{data[:64]!r}... ({len(data)} bytes)" + + _LOGGER.debug( + "HTTP Request: %s %s\nHeaders: %s\nBody: %s", + method, + url, + headers, + display_data, + ) + + def _log_response(self, response: requests.Response): + if not _LOGGER.isEnabledFor(logging.DEBUG): + return + + _LOGGER.debug( + "HTTP Response: %s %s\nHeaders: %s\nBody: %s", + response.status_code, + response.reason, + response.headers, + response.text, + ) + + def _prepare_initiate_request( + self, body: str + ) -> Tuple[str, str, str, Dict[str, str]]: + headers = { + "X-Goog-Upload-Protocol": "resumable", + "X-Goog-Upload-Command": "start", + } + + # Prefix logical headers + if self.content_type: + headers["X-Goog-Upload-Header-Content-Type"] = self.content_type + if self.size is not None: + headers["X-Goog-Upload-Header-Content-Length"] = str(self.size) + + # Add extra headers, prefixing if necessary + for k, v in self.extra_headers.items(): + if k.lower() in ( + "content-length", + "content-type", + "content-encoding", + "transfer-encoding", + ): + headers[f"X-Goog-Upload-Header-{k}"] = str(v) + else: + headers[k] = str(v) + + return "POST", self.initial_url, body, headers + + def _process_initiate_response(self, response: requests.Response): + raise_formatted_for_status(response) + + self.session_url = response.headers.get("X-Goog-Upload-URL") + if not self.session_url: + raise ValueError("Server did not return X-Goog-Upload-URL") + + granularity = response.headers.get("X-Goog-Upload-Chunk-Granularity") + if granularity: + self.chunk_granularity = int(granularity) + _LOGGER.debug( + "Server requested chunk granularity: %d", self.chunk_granularity + ) + + if self.on_progress: + self.on_progress( + ResumableUploadStatus( + upload_url=self.session_url, + total_bytes=self.size, + bytes_uploaded=0, + finished=False, + ) + ) + + def initiate( + self, + transport: requests.Session, + request_body: str = "", + request_retry: Optional[google.api_core.retry.Retry] = None, + ): + """Initiates the resumable upload session. + + This method sends the initial request to the server to start a new + resumable upload session and retrieves the session URL. + + Args: + transport (requests.Session): + The authorized session to use for the initiation request. + request_body (str): + The JSON-encoded request body for the initiation request. + request_retry (Optional[google.api_core.retry.Retry]): + Designation of what errors, if any, should be retried. + """ + _LOGGER.info("Initiating resumable upload to %s", self.initial_url) + method, url, body, headers = self._prepare_initiate_request( + request_body + ) + + def do_initiate(): + timeout = self._check_deadline() + self._log_request(method, url, headers, body) + response = transport.request( + method, url, data=body, headers=headers, timeout=timeout + ) + self._log_response(response) + raise_formatted_for_status(response) + return response + + if request_retry: + response = request_retry(do_initiate)() + else: + response = do_initiate() + + self._process_initiate_response(response) + + def _prepare_chunk_request( + self, + ) -> Tuple[str, str, bytes, Dict[str, str], int]: + # Adjust chunk size based on granularity if needed + actual_chunk_size = self.chunk_size + if self.chunk_granularity: + if actual_chunk_size % self.chunk_granularity != 0: + actual_chunk_size = ( + (actual_chunk_size // self.chunk_granularity) + 1 + ) * self.chunk_granularity + _LOGGER.debug( + "Adjusted chunk size to %d based on granularity %d", + actual_chunk_size, + self.chunk_granularity, + ) + + data = self.stream.read(actual_chunk_size) + data_len = len(data) + is_last_chunk = data_len < actual_chunk_size or ( + self.size is not None + and self.bytes_uploaded + data_len >= self.size + ) + + command = "upload" + if is_last_chunk: + command = "upload, finalize" + + headers = { + "X-Goog-Upload-Command": command, + "X-Goog-Upload-Offset": str(self.bytes_uploaded), + } + + return "POST", self.session_url, data, headers, data_len + + def _process_chunk_response( + self, response: requests.Response, chunk_len: int + ): + raise_formatted_for_status(response) + + status = response.headers.get("X-Goog-Upload-Status") + if status == "active": + self.bytes_uploaded += chunk_len + elif status == "final": + self.finished = True + self.bytes_uploaded += chunk_len + + def transmit_next_chunk( + self, transport: requests.Session + ) -> requests.Response: + """Uploads the next chunk of data from the stream. + + This method reads a chunk from the stream, prepares the upload request, + transmits it to the server, and processes the response. + + Args: + transport (requests.Session): + The authorized session to use for the upload. + + Returns: + requests.Response: + The response from the server for this chunk upload. + """ + self._check_deadline() + method, url, data, headers, chunk_len = self._prepare_chunk_request() + + retry = google.api_core.retry.Retry( + predicate=self._get_retry_predicate(), + deadline=self._check_deadline(), + ) + + def do_upload(): + _LOGGER.info( + "Uploading chunk at offset %s, size %d, command %s", + headers["X-Goog-Upload-Offset"], + chunk_len, + headers["X-Goog-Upload-Command"], + ) + timeout = self._check_deadline() + self._log_request(method, url, headers, data) + response = transport.request( + method, url, data=data, headers=headers, timeout=timeout + ) + self._log_response(response) + raise_formatted_for_status(response) + return response + + try: + response = retry(do_upload)() + self._process_chunk_response(response, chunk_len) + except Exception as e: + _LOGGER.error("Error during chunk upload: %s", e) + self._recover(transport, retry) + if ( + isinstance(e, requests.exceptions.HTTPError) + and e.response is not None + ): + return e.response + raise + + if self.on_progress: + self.on_progress( + ResumableUploadStatus( + upload_url=self.session_url, + total_bytes=self.size, + bytes_uploaded=self.bytes_uploaded, + finished=self.finished, + ) + ) + + return response + + def _prepare_recovery_request(self) -> Tuple[str, str, Dict[str, str]]: + headers = {"X-Goog-Upload-Command": "query"} + return "POST", self.session_url, headers + + def _process_recovery_response(self, response: requests.Response): + raise_formatted_for_status(response) + status = response.headers.get("X-Goog-Upload-Status") + + if status == "active": + received = int( + response.headers.get("X-Goog-Upload-Size-Received", 0) + ) + _LOGGER.info( + "Server reported %d bytes received. Seeking stream.", received + ) + self.bytes_uploaded = received + self.stream.seek(received) + elif status == "final": + _LOGGER.info("Upload already finalized according to server.") + self.finished = True + elif status == "cancelled": + raise RuntimeError("Upload was cancelled by server") + + def _recover( + self, transport: requests.Session, retry: google.api_core.retry.Retry + ): + _LOGGER.info("Attempting recovery via query command") + method, url, headers = self._prepare_recovery_request() + + def do_query(): + timeout = self._check_deadline() + self._log_request(method, url, headers) + response = transport.request( + method, url, headers=headers, timeout=timeout + ) + self._log_response(response) + raise_formatted_for_status(response) + return response + + response = retry(do_query)() + self._process_recovery_response(response) + + +def make_resumable_upload( + transport: requests.Session, + request_body: str, + stream: BinaryIO, + upload_url: str, + size: Optional[int] = None, + content_type: Optional[str] = None, + chunk_size: Optional[int] = None, + request_retry: Optional[google.api_core.retry.Retry] = None, + deadline: Optional[datetime.datetime] = None, + headers: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None, + on_progress: Optional[Callable[[ResumableUploadStatus], None]] = None, +) -> requests.Response: + """Makes a resumable upload. + + Args: + transport (requests.Session): + The authorized session to use for the upload. + request_body (str): + The JSON-encoded request body to send during initiation. + stream (BinaryIO): + A stream of bytes to be uploaded. + upload_url (str): + The initial URL to start the resumable upload. + size (int): + The number of bytes to be uploaded. If not provided, + the upload will continue until the stream is exhausted. + content_type (str): + The MIME type of the content being uploaded. + chunk_size (int): + The size of each chunk to be uploaded. + request_retry (google.api_core.retry.Retry): + Designation of what errors, if any, should be retried during initiation. + deadline (datetime.datetime): + The deadline for the entire upload process. + headers (Sequence[Tuple[str, Union[str, bytes]]]): + Key/value pairs which should be sent along with the request as metadata. + on_progress (Callable[[ResumableUploadStatus], None]): + A callback function that will be called after each chunk is uploaded. + + Returns: + requests.Response: + The final response from the server after the upload is complete. + """ + upload = ResumableUpload( + upload_url, + stream=stream, + size=size, + content_type=content_type, + chunk_size=chunk_size, + deadline=deadline, + headers=headers, + on_progress=on_progress, + ) + upload.initiate( + transport=transport, + request_body=request_body, + request_retry=request_retry, + ) + + final_response = None + while not upload.finished: + final_response = upload.transmit_next_chunk(transport=transport) + return final_response diff --git a/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/resumable_upload_error_adapter.py b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/resumable_upload_error_adapter.py new file mode 100644 index 000000000..c871ac124 --- /dev/null +++ b/google/ads/googleads/v23/services/services/you_tube_video_upload_service/transports/resumable_upload_error_adapter.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import grpc +import requests +from typing import Any, Optional +from google.api_core import exceptions as core_exceptions + +from google.ads.googleads.errors import GoogleAdsException +from google.ads.googleads.v23.errors.types.errors import ( + GoogleAdsError, + GoogleAdsFailure, + ErrorCode, +) + + +class ResumableUploadErrorAdapter(grpc.RpcError, grpc.Call): + """ + A concrete implementation of gRPC abstract classes. + Wraps a requests.Response to mimic a gRPC call for GoogleAdsException. + """ + + def __init__( + self, response: requests.Response, mapped_grpc_code: grpc.StatusCode + ): + self._response = response + self._mapped_code = mapped_grpc_code + + # --- grpc.Call & grpc.RpcContext Required Methods --- + def code(self) -> grpc.StatusCode: + return self._mapped_code + + def details(self) -> str: + # RUP specifies error details are in the response body + return self._response.text + + def initial_metadata(self) -> Any: + return None + + def trailing_metadata(self) -> Any: + # HTTP headers serve as trailing metadata in RUP + return tuple(self._response.headers.items()) + + def is_active(self) -> bool: + return False + + def time_remaining(self) -> Optional[float]: + return None + + def cancel(self) -> None: + pass + + def add_callback(self, callback: Any) -> None: + pass + + +def raise_formatted_ads_exception(response: requests.Response): + """Converts a RUP HTTP response into a rich GoogleAdsException. + + Args: + response (requests.Response): + The HTTP response containing error details. + + Raises: + GoogleAdsException: + A rich exception containing the mapped gRPC status, failure details, + and request ID. + """ + # 1. Map HTTP status (e.g., 400) to gRPC status (e.g., INVALID_ARGUMENT) + core_error = core_exceptions.from_http_response(response) + grpc_code = core_error.grpc_status_code or grpc.StatusCode.INTERNAL + + # 2. Build the ErrorCode using the specific oneof member 'request_error' + # Setting this automatically sets the 'error_code' oneof group. + # We use '1' (UNSPECIFIED/UNKNOWN) for the enum value within RequestError. + e_code = ErrorCode(request_error=1) + + # 3. Build the GoogleAdsError + # Message is populated from the RUP response text + g_error = GoogleAdsError(message=core_error.message, error_code=e_code) + + # 4. Build the GoogleAdsFailure container + # request_id comes from X-Goog-Upload-Status per protocol + request_id = response.headers.get("X-Goog-Upload-Status", "unknown") + failure = GoogleAdsFailure(errors=[g_error], request_id=request_id) + + # 5. Instantiate the adapter and raise the final exception + adapter = ResumableUploadErrorAdapter(response, grpc_code) + + raise GoogleAdsException( + error=adapter, call=adapter, failure=failure, request_id=request_id + ) + + +def raise_formatted_for_status(response: requests.Response): + """Replacement for response.raise_for_status() that raises GoogleAdsException. + + Args: + response (requests.Response): + The HTTP response to check for errors. + + Raises: + GoogleAdsException: + If the response status code indicates an error. + """ + if not response.ok: + raise_formatted_ads_exception(response) diff --git a/google/ads/googleads/v23/services/types/__init__.py b/google/ads/googleads/v23/services/types/__init__.py index 0bea55c09..189d34c6b 100644 --- a/google/ads/googleads/v23/services/types/__init__.py +++ b/google/ads/googleads/v23/services/types/__init__.py @@ -220,6 +220,9 @@ BenchmarksProductMetadata, BenchmarksSource, BenchmarksSourceMetadata, + BreakdownDefinition, + BreakdownKey, + BreakdownMetrics, GenerateBenchmarksMetricsRequest, GenerateBenchmarksMetricsResponse, IndustryVerticalInfo, @@ -365,6 +368,7 @@ SearchAudience, SearchTopics, TrendInsight, + TrendInsightDataPoint, TrendInsightMetrics, YouTubeChannelInsights, YouTubeCreatorInsights, @@ -845,6 +849,14 @@ MutateUserListsResponse, UserListOperation, ) +from .youtube_video_upload_service import ( + CreateYouTubeVideoUploadRequest, + CreateYouTubeVideoUploadResponse, + RemoveYouTubeVideoUploadRequest, + RemoveYouTubeVideoUploadResponse, + UpdateYouTubeVideoUploadRequest, + UpdateYouTubeVideoUploadResponse, +) __all__ = ( "AccountBudgetProposalOperation", @@ -999,6 +1011,9 @@ "BenchmarksProductMetadata", "BenchmarksSource", "BenchmarksSourceMetadata", + "BreakdownDefinition", + "BreakdownKey", + "BreakdownMetrics", "GenerateBenchmarksMetricsRequest", "GenerateBenchmarksMetricsResponse", "IndustryVerticalInfo", @@ -1104,6 +1119,7 @@ "SearchAudience", "SearchTopics", "TrendInsight", + "TrendInsightDataPoint", "TrendInsightMetrics", "YouTubeChannelInsights", "YouTubeCreatorInsights", @@ -1461,4 +1477,10 @@ "MutateUserListsRequest", "MutateUserListsResponse", "UserListOperation", + "CreateYouTubeVideoUploadRequest", + "CreateYouTubeVideoUploadResponse", + "RemoveYouTubeVideoUploadRequest", + "RemoveYouTubeVideoUploadResponse", + "UpdateYouTubeVideoUploadRequest", + "UpdateYouTubeVideoUploadResponse", ) diff --git a/google/ads/googleads/v23/services/types/benchmarks_service.py b/google/ads/googleads/v23/services/types/benchmarks_service.py index a54551346..6014e8116 100644 --- a/google/ads/googleads/v23/services/types/benchmarks_service.py +++ b/google/ads/googleads/v23/services/types/benchmarks_service.py @@ -21,11 +21,12 @@ from google.ads.googleads.v23.common.types import additional_application_info from google.ads.googleads.v23.common.types import criteria -from google.ads.googleads.v23.common.types import dates +from google.ads.googleads.v23.common.types import dates as gagc_dates from google.ads.googleads.v23.enums.types import benchmarks_marketing_objective from google.ads.googleads.v23.enums.types import ( benchmarks_source_type as gage_benchmarks_source_type, ) +from google.ads.googleads.v23.enums.types import benchmarks_time_granularity __protobuf__ = proto.module( @@ -47,7 +48,10 @@ "GenerateBenchmarksMetricsRequest", "BenchmarksSource", "ProductFilter", + "BreakdownDefinition", "GenerateBenchmarksMetricsResponse", + "BreakdownMetrics", + "BreakdownKey", "Metrics", "RateMetrics", }, @@ -84,10 +88,10 @@ class ListBenchmarksAvailableDatesResponse(proto.Message): range inclusive. """ - supported_dates: dates.DateRange = proto.Field( + supported_dates: gagc_dates.DateRange = proto.Field( proto.MESSAGE, number=1, - message=dates.DateRange, + message=gagc_dates.DateRange, ) @@ -362,6 +366,10 @@ class GenerateBenchmarksMetricsRequest(proto.Message): Required. The products to aggregate metrics over. Product filter settings support a list of product IDs or a list of marketing objectives. + breakdown_definition (google.ads.googleads.v23.services.types.BreakdownDefinition): + Optional. The set of dimensions to group + metrics by. If multiple dimensions are selected, + cross-dimension breakdowns are returned. currency_code (str): Optional. The three-character ISO 4217 currency code. If unspecified, the default @@ -378,10 +386,10 @@ class GenerateBenchmarksMetricsRequest(proto.Message): proto.STRING, number=1, ) - date_range: dates.DateRange = proto.Field( + date_range: gagc_dates.DateRange = proto.Field( proto.MESSAGE, number=2, - message=dates.DateRange, + message=gagc_dates.DateRange, ) location: criteria.LocationInfo = proto.Field( proto.MESSAGE, @@ -398,6 +406,11 @@ class GenerateBenchmarksMetricsRequest(proto.Message): number=5, message="ProductFilter", ) + breakdown_definition: "BreakdownDefinition" = proto.Field( + proto.MESSAGE, + number=9, + message="BreakdownDefinition", + ) currency_code: str = proto.Field( proto.STRING, number=6, @@ -507,6 +520,31 @@ class MarketingObjectiveList(proto.Message): ) +class BreakdownDefinition(proto.Message): + r"""The set of dimensions to group metrics by. + + Attributes: + date_breakdown (google.ads.googleads.v23.enums.types.BenchmarksTimeGranularityEnum.BenchmarksTimeGranularity): + A date breakdown using the selected + granularity. The effective date range is + extended to include the full time periods that + overlap with the selected start and end dates. + For example, a monthly breakdown with a start + date of 2025-06-15 will include a breakdown for + June. Weeks start on Sunday and end on Saturday. + This is different from the ISO 8601 standard, + where weeks start on Monday. + """ + + date_breakdown: ( + benchmarks_time_granularity.BenchmarksTimeGranularityEnum.BenchmarksTimeGranularity + ) = proto.Field( + proto.ENUM, + number=1, + enum=benchmarks_time_granularity.BenchmarksTimeGranularityEnum.BenchmarksTimeGranularity, + ) + + class GenerateBenchmarksMetricsResponse(proto.Message): r"""Response message for [BenchmarksService.GenerateBenchmarksMetrics][google.ads.googleads.v23.services.BenchmarksService.GenerateBenchmarksMetrics]. @@ -516,6 +554,8 @@ class GenerateBenchmarksMetricsResponse(proto.Message): Metrics belonging to the customer. average_benchmarks_metrics (google.ads.googleads.v23.services.types.Metrics): Metrics for the selected benchmarks source. + breakdown_metrics (MutableSequence[google.ads.googleads.v23.services.types.BreakdownMetrics]): + Breakdown metrics grouped by dimensions. """ customer_metrics: "Metrics" = proto.Field( @@ -528,6 +568,60 @@ class GenerateBenchmarksMetricsResponse(proto.Message): number=2, message="Metrics", ) + breakdown_metrics: MutableSequence["BreakdownMetrics"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + message="BreakdownMetrics", + ) + ) + + +class BreakdownMetrics(proto.Message): + r"""Metrics for a given breakdown. + + Attributes: + breakdown_key (google.ads.googleads.v23.services.types.BreakdownKey): + Dimensions by which the breakdown metrics are + grouped by. + customer_metrics (google.ads.googleads.v23.services.types.Metrics): + Metrics belonging to the customer. + average_benchmarks_metrics (google.ads.googleads.v23.services.types.Metrics): + Metrics for the selected benchmarks source. + """ + + breakdown_key: "BreakdownKey" = proto.Field( + proto.MESSAGE, + number=1, + message="BreakdownKey", + ) + customer_metrics: "Metrics" = proto.Field( + proto.MESSAGE, + number=2, + message="Metrics", + ) + average_benchmarks_metrics: "Metrics" = proto.Field( + proto.MESSAGE, + number=3, + message="Metrics", + ) + + +class BreakdownKey(proto.Message): + r"""Dimensions by which the breakdown metrics are grouped by. + + Attributes: + dates (google.ads.googleads.v23.common.types.DateRange): + Dates used for the breakdown. For example, + this represents the start and end dates of the + week for a weekly breakdown. + """ + + dates: gagc_dates.DateRange = proto.Field( + proto.MESSAGE, + number=1, + message=gagc_dates.DateRange, + ) class Metrics(proto.Message): diff --git a/google/ads/googleads/v23/services/types/content_creator_insights_service.py b/google/ads/googleads/v23/services/types/content_creator_insights_service.py index 8c825994f..fc259d2a8 100644 --- a/google/ads/googleads/v23/services/types/content_creator_insights_service.py +++ b/google/ads/googleads/v23/services/types/content_creator_insights_service.py @@ -40,6 +40,7 @@ "SearchTopics", "TrendInsight", "TrendInsightMetrics", + "TrendInsightDataPoint", "LanguageDistribution", }, ) @@ -146,9 +147,10 @@ class SearchBrand(proto.Message): find insights. include_related_topics (bool): Optional. When true, we will expand the search to beyond - just the entities specified in [brand_entities] to other - related knowledge graph entities similar to the brand. The - default value is ``false``. + just the entities specified in + [brand_entities][google.ads.googleads.v23.services.GenerateCreatorInsightsRequest.SearchBrand.brand_entities] + to other related knowledge graph entities similar to the + brand. The default value is ``false``. """ brand_entities: MutableSequence[ @@ -643,6 +645,9 @@ class SearchTopics(proto.Message): Required. A list of knowledge graph entities to retrieve trend information for. Supported entities are tagged with [CONTENT_TRENDING_INSIGHTS][google.ads.googleads.v23.enums.InsightsKnowledgeGraphEntityCapabilitiesEnum.InsightsKnowledgeGraphEntityCapabilities.CONTENT_TRENDING_INSIGHTS]. + Use + [AudienceInsightsService.ListAudienceInsightsAttributes][google.ads.googleads.v23.services.AudienceInsightsService.ListAudienceInsightsAttributes] + to get the list of supported entities. """ entities: MutableSequence[ @@ -661,10 +666,19 @@ class TrendInsight(proto.Message): trend_attribute (google.ads.googleads.v23.common.types.AudienceInsightsAttributeMetadata): The attribute this trend is for. trend_metrics (google.ads.googleads.v23.services.types.TrendInsightMetrics): - Metrics associated with this trend. + Metrics associated with this trend. These + metrics are for the latest available month and + the comparison period is 3 months. trend (google.ads.googleads.v23.enums.types.InsightsTrendEnum.InsightsTrend): The direction of trend (such as RISING or DECLINING). + trend_data_points (MutableSequence[google.ads.googleads.v23.services.types.TrendInsightDataPoint]): + 12 months of historical data for the trend, including the + most recent month the TrendInsight represents. Each data + point represents 1 month of data and the comparison period + is 1 month. The data points are ordered from most recent + month to least recent month. Only populated for trends using + search_topics. related_videos (MutableSequence[google.ads.googleads.v23.common.types.AudienceInsightsAttributeMetadata]): Related videos for this topic. Only populated for trends using search_topics. @@ -690,6 +704,13 @@ class TrendInsight(proto.Message): number=3, enum=insights_trend.InsightsTrendEnum.InsightsTrend, ) + trend_data_points: MutableSequence["TrendInsightDataPoint"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=6, + message="TrendInsightDataPoint", + ) + ) related_videos: MutableSequence[ audience_insights_attribute.AudienceInsightsAttributeMetadata ] = proto.RepeatedField( @@ -712,7 +733,12 @@ class TrendInsightMetrics(proto.Message): Attributes: views_count (int): The number of views for this trend. This is - only populated for SearchTopics requests. + only populated for the latest month of data for + SearchTopics requests. + views_indexed_value (int): + Views value normalized to be in the range + 0-100. This is only populated for SearchTopics + requests. audience_share (float): The fraction (from 0 to 1 inclusive) of the requested audience that has has searched or @@ -721,14 +747,19 @@ class TrendInsightMetrics(proto.Message): trend_change_percent (float): The percentage of the change in the trend's value over the comparison period, where 1.0 - represents 100%. If this is not set, it means - that the trend is emerging. + represents 100%. If this is 0, it means that the + trend is emerging (new) or sustained (existing + but unchanged). """ views_count: int = proto.Field( proto.INT64, number=1, ) + views_indexed_value: int = proto.Field( + proto.INT64, + number=4, + ) audience_share: float = proto.Field( proto.DOUBLE, number=2, @@ -739,6 +770,30 @@ class TrendInsightMetrics(proto.Message): ) +class TrendInsightDataPoint(proto.Message): + r"""Trend data for a specific month. + + Attributes: + month (str): + The month that the trend data point + represents in the string format "YYYY-MM". + trend_metrics (google.ads.googleads.v23.services.types.TrendInsightMetrics): + Metrics associated with this trend and month. + The comparison period for these metrics is 1 + month. + """ + + month: str = proto.Field( + proto.STRING, + number=1, + ) + trend_metrics: "TrendInsightMetrics" = proto.Field( + proto.MESSAGE, + number=2, + message="TrendInsightMetrics", + ) + + class LanguageDistribution(proto.Message): r"""Languages that pertain to a YouTube channel based on the channel content. Only languages above a certain proportion diff --git a/google/ads/googleads/v23/services/types/conversion_upload_service.py b/google/ads/googleads/v23/services/types/conversion_upload_service.py index f1de9ddf9..3fbd6da5e 100644 --- a/google/ads/googleads/v23/services/types/conversion_upload_service.py +++ b/google/ads/googleads/v23/services/types/conversion_upload_service.py @@ -322,7 +322,10 @@ class ClickConversion(proto.Message): consent where required by law or any applicable Google policies. See the https://support.google.com/google-ads/answer/2998031 - page for more details. + page for more details. This field is only + available to allowlisted users. To include this + field in conversion imports, upgrade to the Data + Manager API. This field is a member of `oneof`_ ``_user_ip_address``. session_attributes_encoded (bytes): @@ -330,12 +333,17 @@ class ClickConversion(proto.Message): base64-encoded JSON string. The content should be generated by Google-provided library. To set session attributes individually, use session_attributes_key_value_pairs - instead. + instead. This field is only available to allowlisted users. + To include this field in conversion imports, upgrade to the + Data Manager API. This field is a member of `oneof`_ ``session_attributes``. session_attributes_key_value_pairs (google.ads.googleads.v23.services.types.SessionAttributesKeyValuePairs): The session attributes for the event, - represented as key-value pairs. + represented as key-value pairs. This field is + only available to allowlisted users. To include + this field in conversion imports, upgrade to the + Data Manager API. This field is a member of `oneof`_ ``session_attributes``. """ diff --git a/google/ads/googleads/v23/services/types/google_ads_service.py b/google/ads/googleads/v23/services/types/google_ads_service.py index 2b9d6ffa6..6baf2c714 100644 --- a/google/ads/googleads/v23/services/types/google_ads_service.py +++ b/google/ads/googleads/v23/services/types/google_ads_service.py @@ -533,6 +533,7 @@ from google.ads.googleads.v23.resources.types import ( webpage_view as gagr_webpage_view, ) +from google.ads.googleads.v23.resources.types import youtube_video_upload from google.ads.googleads.v23.services.types import ad_group_ad_label_service from google.ads.googleads.v23.services.types import ad_group_ad_service from google.ads.googleads.v23.services.types import ad_group_asset_service @@ -1347,6 +1348,9 @@ class GoogleAdsRow(proto.Message): android_privacy_shared_key_google_network_type (google.ads.googleads.v23.resources.types.AndroidPrivacySharedKeyGoogleNetworkType): The android privacy shared key google network type referenced in the query. + you_tube_video_upload (google.ads.googleads.v23.resources.types.YouTubeVideoUpload): + The YouTube video upload referenced in the + query. applied_incentive (google.ads.googleads.v23.resources.types.AppliedIncentive): The applied incentive referenced in the query. @@ -2435,6 +2439,13 @@ class GoogleAdsRow(proto.Message): number=219, message=gagr_android_privacy_shared_key_google_network_type.AndroidPrivacySharedKeyGoogleNetworkType, ) + you_tube_video_upload: youtube_video_upload.YouTubeVideoUpload = ( + proto.Field( + proto.MESSAGE, + number=245, + message=youtube_video_upload.YouTubeVideoUpload, + ) + ) applied_incentive: gagr_applied_incentive.AppliedIncentive = proto.Field( proto.MESSAGE, number=246, diff --git a/google/ads/googleads/v23/services/types/youtube_video_upload_service.py b/google/ads/googleads/v23/services/types/youtube_video_upload_service.py new file mode 100644 index 000000000..9e0b2d159 --- /dev/null +++ b/google/ads/googleads/v23/services/types/youtube_video_upload_service.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableSequence + +import proto # type: ignore + +from google.ads.googleads.v23.resources.types import youtube_video_upload +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.ads.googleads.v23.services", + marshal="google.ads.googleads.v23", + manifest={ + "CreateYouTubeVideoUploadRequest", + "CreateYouTubeVideoUploadResponse", + "UpdateYouTubeVideoUploadRequest", + "UpdateYouTubeVideoUploadResponse", + "RemoveYouTubeVideoUploadRequest", + "RemoveYouTubeVideoUploadResponse", + }, +) + + +class CreateYouTubeVideoUploadRequest(proto.Message): + r"""Request message for + [YouTubeVideoUploadService.CreateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.CreateYouTubeVideoUpload]. + + Attributes: + customer_id (str): + Required. The customer ID requesting the + upload. Required. + you_tube_video_upload (google.ads.googleads.v23.resources.types.YouTubeVideoUpload): + Required. The initial details of the video to + upload. Required. + """ + + customer_id: str = proto.Field( + proto.STRING, + number=1, + ) + you_tube_video_upload: youtube_video_upload.YouTubeVideoUpload = ( + proto.Field( + proto.MESSAGE, + number=2, + message=youtube_video_upload.YouTubeVideoUpload, + ) + ) + + +class CreateYouTubeVideoUploadResponse(proto.Message): + r"""Response message for + [YouTubeVideoUploadService.CreateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.CreateYouTubeVideoUpload]. + + Attributes: + resource_name (str): + The resource name of the successfully created + YouTube video upload. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateYouTubeVideoUploadRequest(proto.Message): + r"""Request message for + [YouTubeVideoUploadService.UpdateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.UpdateYouTubeVideoUpload]. + + Attributes: + customer_id (str): + Required. The customer ID requesting the + YouTube video upload update. Required. + you_tube_video_upload (google.ads.googleads.v23.resources.types.YouTubeVideoUpload): + Required. The YouTube video upload resource + to be updated. It's expected to have a valid + resource name. Required. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. FieldMask that determines which + resource fields are modified in an update. + """ + + customer_id: str = proto.Field( + proto.STRING, + number=1, + ) + you_tube_video_upload: youtube_video_upload.YouTubeVideoUpload = ( + proto.Field( + proto.MESSAGE, + number=2, + message=youtube_video_upload.YouTubeVideoUpload, + ) + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateYouTubeVideoUploadResponse(proto.Message): + r"""Response message for + [YouTubeVideoUploadService.UpdateYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.UpdateYouTubeVideoUpload]. + + Attributes: + resource_name (str): + The resource name of the successfully updated + YouTube video upload. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RemoveYouTubeVideoUploadRequest(proto.Message): + r"""Request message for + [YouTubeVideoUploadService.RemoveYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.RemoveYouTubeVideoUpload]. + + Attributes: + customer_id (str): + Required. The customer ID requesting the + YouTube video upload deletion. Required. + resource_names (MutableSequence[str]): + The resource names of the YouTube video + uploads to be removed. Required. + """ + + customer_id: str = proto.Field( + proto.STRING, + number=1, + ) + resource_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class RemoveYouTubeVideoUploadResponse(proto.Message): + r"""Response message for + [YouTubeVideoUploadService.RemoveYouTubeVideoUpload][google.ads.googleads.v23.services.YouTubeVideoUploadService.RemoveYouTubeVideoUpload]. + + Attributes: + resource_names (MutableSequence[str]): + The resource names of the successfully + removed YouTube video uploads. + """ + + resource_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/pyproject.toml b/pyproject.toml index 666844fc2..21d1ee3a4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,7 +18,7 @@ build-backend = "setuptools.build_meta" [project] name = "google-ads" -version = "29.1.0" +version = "29.2.0" description = "Client library for the Google Ads API" readme = "./README.rst" requires-python = ">=3.9, <3.15"